@maind-dev/mcp-bridge 0.93.0 → 0.95.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 Bf=Object.defineProperty;var o=(e,t)=>Bf(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Bf(e,n,{get:t[n],enumerable:!0})};import{existsSync as zx,mkdirSync as qx,readdirSync as Jx,readFileSync as Yx,renameSync as Xx,statSync as Zx,unlinkSync as Qx,writeFileSync as eE}from"node:fs";import{homedir as tE}from"node:os";import{join as ps}from"node:path";function ms(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,i=us(r.id),s=us(r.key),a=us(r.title),c=us(r.status);if(!(!i||!s||!a||!c)&&(t.push({id:i,key:s,title:a,status:c}),t.length>=nE))break}return t}function hs(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 Gf(e=tE()){return ps(e,".maind","assigned-told")}function Kf(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function Wf(e){try{let t=JSON.parse(Yx(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 sE(e,t,n){qx(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;eE(r,JSON.stringify(n),{mode:384}),Xx(r,t)}function Vf(e,t,n=Gf()){let r=ps(n,`${Kf(e)}.json`);return zx(r)?t-Wf(r).checked_at<iE:!1}function Va(e,t,n,r=Gf()){try{let i=ps(r,`${Kf(e)}.json`),s=Wf(i),a=t.filter(c=>!s.ids.includes(c.id));return sE(r,i,{ids:[...s.ids,...a.map(c=>c.id)].slice(-200),checked_at:n}),oE(r,n,i),a}catch{return[]}}function oE(e,t,n){try{for(let r of Jx(e)){let i=ps(e,r);i!==n&&t-Zx(i).mtimeMs>rE&&Qx(i)}}catch{}}function zf(e){return e==="claude-code"}var nE,rE,iE,us,fs,Xr=_(()=>{"use strict";nE=5,rE=7*24*60*60*1e3,iE=6e4,us=o(e=>typeof e=="string"&&e.length>0?e:null,"str");o(ms,"parseAssignedList");o(hs,"assignedNoticeText");o(Gf,"assignedToldDir");o(Kf,"safeName");o(Wf,"readTold");o(sE,"writeTold");o(Vf,"checkedRecently");o(Va,"takeUntold");o(oE,"pruneTold");fs=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=ms(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 hs(t)}};o(zf,"clientHasHooks")});function Xf(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 qn(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 Ja(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ya(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Xa(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Za=_(()=>{"use strict";o(Xf,"parseFrame");o(qn,"denyResult");o(Ja,"toolEvent");o(Ya,"policyEvent");o(Xa,"shaEvent")});import{execFileSync as ep}from"node:child_process";function tp(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=yE}function _E(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 mE){let a=r[s];typeof a=="string"&&Zf.test(a)&&i.push({field:s,sha:a})}for(let[s,a]of hE){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Zf.test(l)&&i.push({field:`${s}.${a}`,sha:l})}return i}function bE(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,Qf);for(let i=Qf;i>=gE;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 Jn(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 np(){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 ys(e=process.cwd()){try{let n=ep("git",["rev-parse","--show-toplevel"],{cwd:e,env:np(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function wE(e){return t=>{try{let r=ep("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:np(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function _s(e,t){if(t===null)return[];let n=_E(e);if(n.length===0)return[];let r=wE(t),i=[];for(let{field:s,sha:a}of n){let c=bE(a,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var mE,hE,Zf,gE,Qf,yE,Qa=_(()=>{"use strict";mE=["commit_sha","base_sha","head_sha"],hE=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Zf=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,gE=7,Qf=12,yE=10;o(tp,"isDenyGrade");o(_E,"extractShaArgs");o(bE,"classifySha");o(Jn,"shaFindingText");o(np,"cleanGitEnv");o(ys,"resolveRepoRootForSha");o(wE,"gitShaResolver");o(_s,"inspectLineForShas")});var ip=_(()=>{"use strict"});var j,tc,A,Ke,Zr=_(()=>{(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})})(tc||(tc={}));A=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=o(e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}},"getParsedType")});var E,vE,me,bs=_(()=>{Zr();E=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"]),vE=o(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),me=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()}};me.create=e=>new me(e)});var kE,rt,nc=_(()=>{bs();Zr();kE=o((e,t)=>{let n;switch(e.code){case E.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${j.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}"`:j.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,j.assertNever(e)}return{message:n}},"errorMap"),rt=kE});function SE(e){sp=e}function Yn(){return sp}var sp,ws=_(()=>{nc();sp=rt;o(SE,"setErrorMap");o(Yn,"getErrorMap")});function R(e,t){let n=Yn(),r=Qr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===rt?void 0:rt].filter(i=>!!i)});e.common.issues.push(r)}var Qr,xE,ne,O,Xt,le,vs,ks,wt,Xn,rc=_(()=>{ws();nc();Qr=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"),xE=[];o(R,"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"}),Xt=o(e=>({status:"dirty",value:e}),"DIRTY"),le=o(e=>({status:"valid",value:e}),"OK"),vs=o(e=>e.status==="aborted","isAborted"),ks=o(e=>e.status==="dirty","isDirty"),wt=o(e=>e.status==="valid","isValid"),Xn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var op=_(()=>{});var I,ap=_(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}))});function $(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 up(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 HE(e){return new RegExp(`^${up(e)}$`)}function fp(e){let t=`${dp}T${up(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 BE(e,t){return!!((t==="v4"||!t)&&PE.test(e)||(t==="v6"||!t)&&$E.test(e))}function GE(e,t){if(!IE.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 KE(e,t){return!!((t==="v4"||!t)&&ME.test(e)||(t==="v6"||!t)&&LE.test(e))}function WE(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 Zn(e){if(e instanceof he){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=xe.create(Zn(r))}return new he({...e._def,shape:o(()=>t,"shape")})}else return e instanceof ot?new ot({...e._def,type:Zn(e.element)}):e instanceof xe?xe.create(Zn(e.unwrap())):e instanceof Ve?Ve.create(Zn(e.unwrap())):e instanceof We?We.create(e.items.map(t=>Zn(t))):e}function sc(e,t){let n=Ke(e),r=Ke(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.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=sc(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===A.array&&r===A.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=sc(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function pp(e,t){return new ln({values:e,typeName:D.ZodEnum,...$(t)})}function lp(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function mp(e,t={},n){return e?kt.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(a=>{if(!a){let c=lp(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let a=lp(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):kt.create()}var Ee,cp,L,EE,TE,RE,AE,CE,IE,NE,OE,DE,ic,PE,ME,$E,LE,FE,jE,dp,UE,vt,Zt,Qt,en,tn,Qn,nn,rn,kt,st,Me,er,ot,he,sn,it,Ss,on,We,xs,tr,nr,Es,an,cn,ln,dn,St,Te,xe,Ve,un,fn,rr,VE,ei,ti,pn,zE,D,qE,hp,gp,JE,YE,yp,XE,ZE,QE,e0,t0,n0,r0,i0,s0,o0,a0,c0,l0,d0,u0,f0,p0,m0,h0,g0,y0,_0,b0,w0,v0,k0,S0,x0,E0,T0,R0,A0,C0,I0,_p=_(()=>{bs();ws();ap();rc();Zr();Ee=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}},cp=o((e,t)=>{if(wt(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 me(e.common.issues);return this._error=n,this._error}}},"handleResult");o($,"processCreateParams");L=class{static{o(this,"ZodType")}get description(){return this._def.description}_getType(t){return Ke(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ke(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:Ke(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Xn(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:Ke(t)},i=this._parseSync({data:t,path:r.path,parent:r});return cp(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ke(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return wt(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=>wt(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:Ke(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(Xn(i)?i:Promise.resolve(i));return cp(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 Te({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 xe.create(this,this._def)}nullable(){return Ve.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ot.create(this)}promise(){return St.create(this,this._def)}or(t){return sn.create([this,t],this._def)}and(t){return on.create(this,t,this._def)}transform(t){return new Te({...$(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new un({...$(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new ei({typeName:D.ZodBranded,type:this,...$(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new fn({...$(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 ti.create(this,t)}readonly(){return pn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},EE=/^c[^\s-]{8,}$/i,TE=/^[0-9a-z]+$/,RE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AE=/^[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,CE=/^[a-z0-9_-]{21}$/i,IE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,NE=/^[-+]?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)?)??$/,OE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,DE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",PE=/^(?:(?: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])$/,ME=/^(?:(?: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])$/,$E=/^(([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]))$/,LE=/^(([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])$/,FE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dp="((\\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])))",UE=new RegExp(`^${dp}$`);o(up,"timeRegexSource");o(HE,"timeRegex");o(fp,"datetimeRegex");o(BE,"isValidIP");o(GE,"isValidJWT");o(KE,"isValidCidr");vt=class e extends L{static{o(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let s=this._getOrReturnCtx(t);return R(s,{code:E.invalid_type,expected:A.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),R(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),R(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?R(i,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&R(i,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")OE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")ic||(ic=new RegExp(DE,"u")),ic.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")AE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")CE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")EE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")TE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")RE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(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),R(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),R(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),R(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),R(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),R(i,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?fp(s).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?UE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?HE(s).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?NE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?BE(t.data,s.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?GE(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?KE(t.data,s.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?FE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?jE.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64url",code:E.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: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}};vt.create=e=>new vt({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...$(e)});o(WE,"floatSafeRemainder");Zt=class e extends L{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)!==A.number){let s=this._getOrReturnCtx(t);return R(s,{code:E.invalid_type,expected:A.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),R(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),R(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),R(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?WE(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),R(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),R(r,{code:E.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,...$(e)});Qt=class e extends L{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)!==A.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),R(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),R(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),R(r,{code:E.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 R(n,{code:E.invalid_type,expected:A.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,...$(e)});en=class extends L{static{o(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),O}return le(t.data)}};en.create=e=>new en({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...$(e)});tn=class e extends L{static{o(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let s=this._getOrReturnCtx(t);return R(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),O}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return R(s,{code:E.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),R(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),R(i,{code:E.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}};tn.create=e=>new tn({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...$(e)});Qn=class extends L{static{o(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),O}return le(t.data)}};Qn.create=e=>new Qn({typeName:D.ZodSymbol,...$(e)});nn=class extends L{static{o(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),O}return le(t.data)}};nn.create=e=>new nn({typeName:D.ZodUndefined,...$(e)});rn=class extends L{static{o(this,"ZodNull")}_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),O}return le(t.data)}};rn.create=e=>new rn({typeName:D.ZodNull,...$(e)});kt=class extends L{static{o(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return le(t.data)}};kt.create=e=>new kt({typeName:D.ZodAny,...$(e)});st=class extends L{static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return le(t.data)}};st.create=e=>new st({typeName:D.ZodUnknown,...$(e)});Me=class extends L{static{o(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return R(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),O}};Me.create=e=>new Me({typeName:D.ZodNever,...$(e)});er=class extends L{static{o(this,"ZodVoid")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),O}return le(t.data)}};er.create=e=>new er({typeName:D.ZodVoid,...$(e)});ot=class e extends L{static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==A.array)return R(n,{code:E.invalid_type,expected:A.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)&&(R(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&&(R(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&&(R(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 Ee(n,a,n.path,c)))).then(a=>ne.mergeArray(r,a));let s=[...n.data].map((a,c)=>i.type._parseSync(new Ee(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)}};ot.create=(e,t)=>new ot({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...$(t)});o(Zn,"deepPartialify");he=class e extends L{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)!==A.object){let d=this._getOrReturnCtx(t);return R(d,{code:E.invalid_type,expected:A.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 Me&&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 Ee(i,f,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof Me){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&&(R(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 f=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Ee(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 Zn(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 xe;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return pp(j.objectKeys(this.shape))}};he.create=(e,t)=>new he({shape:o(()=>e,"shape"),unknownKeys:"strip",catchall:Me.create(),typeName:D.ZodObject,...$(t)});he.strictCreate=(e,t)=>new he({shape:o(()=>e,"shape"),unknownKeys:"strict",catchall:Me.create(),typeName:D.ZodObject,...$(t)});he.lazycreate=(e,t)=>new he({shape:e,unknownKeys:"strip",catchall:Me.create(),typeName:D.ZodObject,...$(t)});sn=class extends L{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 me(c.ctx.common.issues));return R(n,{code:E.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 me(l));return R(n,{code:E.invalid_union,unionErrors:c}),O}}get options(){return this._def.options}};sn.create=(e,t)=>new sn({options:e,typeName:D.ZodUnion,...$(t)});it=o(e=>e instanceof an?it(e.schema):e instanceof Te?it(e.innerType()):e instanceof cn?[e.value]:e instanceof ln?e.options:e instanceof dn?j.objectValues(e.enum):e instanceof un?it(e._def.innerType):e instanceof nn?[void 0]:e instanceof rn?[null]:e instanceof xe?[void 0,...it(e.unwrap())]:e instanceof Ve?[null,...it(e.unwrap())]:e instanceof ei||e instanceof pn?it(e.unwrap()):e instanceof fn?it(e._def.innerType):[],"getDiscriminator"),Ss=class e extends L{static{o(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return R(n,{code:E.invalid_type,expected:A.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}):(R(n,{code:E.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=it(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,...$(r)})}};o(sc,"mergeValues");on=class extends L{static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=o((s,a)=>{if(vs(s)||vs(a))return O;let c=sc(s.value,a.value);return c.valid?((ks(s)||ks(a))&&n.dirty(),{status:n.value,value:c.data}):(R(r,{code:E.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}))}};on.create=(e,t,n)=>new on({left:e,right:t,typeName:D.ZodIntersection,...$(n)});We=class e extends L{static{o(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return R(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return R(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(R(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 Ee(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})}};We.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new We({items:e,typeName:D.ZodTuple,rest:null,...$(t)})};xs=class e extends L{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!==A.object)return R(r,{code:E.invalid_type,expected:A.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 Ee(r,c,r.path,c)),value:a._parse(new Ee(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 L?new e({keyType:t,valueType:n,typeName:D.ZodRecord,...$(r)}):new e({keyType:vt.create(),valueType:t,typeName:D.ZodRecord,...$(n)})}},tr=class extends L{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!==A.map)return R(r,{code:E.invalid_type,expected:A.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 Ee(r,c,r.path,[d,"key"])),value:s._parse(new Ee(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}}}};tr.create=(e,t,n)=>new tr({valueType:t,keyType:e,typeName:D.ZodMap,...$(n)});nr=class e extends L{static{o(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return R(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),O;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(R(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&&(R(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 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 Ee(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)}};nr.create=(e,t)=>new nr({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...$(t)});Es=class e extends L{static{o(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return R(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),O;function r(c,l){return Qr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Yn(),rt].filter(d=>!!d),issueData:{code:E.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function i(c,l){return Qr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Yn(),rt].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 St){let c=this;return le(async function(...l){let d=new me([]),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 le(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new me([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new me([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:We.create(t).rest(st.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||We.create([]).rest(st.create()),returns:n||st.create(),typeName:D.ZodFunction,...$(r)})}},an=class extends L{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})}};an.create=(e,t)=>new an({getter:e,typeName:D.ZodLazy,...$(t)});cn=class extends L{static{o(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return R(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:t.data}}get value(){return this._def.value}};cn.create=(e,t)=>new cn({value:e,typeName:D.ZodLiteral,...$(t)});o(pp,"createZodEnum");ln=class e extends L{static{o(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return R(n,{expected:j.joinValues(r),received:n.parsedType,code:E.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 R(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return le(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})}};ln.create=pp;dn=class extends L{static{o(this,"ZodNativeEnum")}_parse(t){let n=j.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let i=j.objectValues(n);return R(r,{expected:j.joinValues(i),received:r.parsedType,code:E.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 R(r,{received:r.data,code:E.invalid_enum_value,options:i}),O}return le(t.data)}get enum(){return this._def.values}};dn.create=(e,t)=>new dn({values:e,typeName:D.ZodNativeEnum,...$(t)});St=class extends L{static{o(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return R(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),O;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return le(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};St.create=(e,t)=>new St({type:e,typeName:D.ZodPromise,...$(t)});Te=class extends L{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=>{R(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"?Xt(l.value):n.value==="dirty"?Xt(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"?Xt(c.value):n.value==="dirty"?Xt(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(!wt(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=>wt(a)?Promise.resolve(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):O);j.assertNever(i)}};Te.create=(e,t,n)=>new Te({schema:e,typeName:D.ZodEffects,effect:t,...$(n)});Te.createWithPreprocess=(e,t,n)=>new Te({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...$(n)});xe=class extends L{static{o(this,"ZodOptional")}_parse(t){return this._getType(t)===A.undefined?le(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xe.create=(e,t)=>new xe({innerType:e,typeName:D.ZodOptional,...$(t)});Ve=class extends L{static{o(this,"ZodNullable")}_parse(t){return this._getType(t)===A.null?le(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ve.create=(e,t)=>new Ve({innerType:e,typeName:D.ZodNullable,...$(t)});un=class extends L{static{o(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};un.create=(e,t)=>new un({innerType:e,typeName:D.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$(t)});fn=class extends L{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 Xn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new me(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new me(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};fn.create=(e,t)=>new fn({innerType:e,typeName:D.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$(t)});rr=class extends L{static{o(this,"ZodNaN")}_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),O}return{status:"valid",value:t.data}}};rr.create=e=>new rr({typeName:D.ZodNaN,...$(e)});VE=Symbol("zod_brand"),ei=class extends L{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}},ti=class e extends L{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(),Xt(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})}},pn=class extends L{static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(i=>(wt(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Xn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};pn.create=(e,t)=>new pn({innerType:e,typeName:D.ZodReadonly,...$(t)});o(lp,"cleanParams");o(mp,"custom");zE={object:he.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={}));qE=o((e,t={message:`Input not instance of ${e.name}`})=>mp(n=>n instanceof e,t),"instanceOfType"),hp=vt.create,gp=Zt.create,JE=rr.create,YE=Qt.create,yp=en.create,XE=tn.create,ZE=Qn.create,QE=nn.create,e0=rn.create,t0=kt.create,n0=st.create,r0=Me.create,i0=er.create,s0=ot.create,o0=he.create,a0=he.strictCreate,c0=sn.create,l0=Ss.create,d0=on.create,u0=We.create,f0=xs.create,p0=tr.create,m0=nr.create,h0=Es.create,g0=an.create,y0=cn.create,_0=ln.create,b0=dn.create,w0=St.create,v0=Te.create,k0=xe.create,S0=Ve.create,x0=Te.createWithPreprocess,E0=ti.create,T0=o(()=>hp().optional(),"ostring"),R0=o(()=>gp().optional(),"onumber"),A0=o(()=>yp().optional(),"oboolean"),C0={string:o(e=>vt.create({...e,coerce:!0}),"string"),number:o(e=>Zt.create({...e,coerce:!0}),"number"),boolean:o(e=>en.create({...e,coerce:!0}),"boolean"),bigint:o(e=>Qt.create({...e,coerce:!0}),"bigint"),date:o(e=>tn.create({...e,coerce:!0}),"date")},I0=O});var m={};ee(m,{BRAND:()=>VE,DIRTY:()=>Xt,EMPTY_PATH:()=>xE,INVALID:()=>O,NEVER:()=>I0,OK:()=>le,ParseStatus:()=>ne,Schema:()=>L,ZodAny:()=>kt,ZodArray:()=>ot,ZodBigInt:()=>Qt,ZodBoolean:()=>en,ZodBranded:()=>ei,ZodCatch:()=>fn,ZodDate:()=>tn,ZodDefault:()=>un,ZodDiscriminatedUnion:()=>Ss,ZodEffects:()=>Te,ZodEnum:()=>ln,ZodError:()=>me,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Es,ZodIntersection:()=>on,ZodIssueCode:()=>E,ZodLazy:()=>an,ZodLiteral:()=>cn,ZodMap:()=>tr,ZodNaN:()=>rr,ZodNativeEnum:()=>dn,ZodNever:()=>Me,ZodNull:()=>rn,ZodNullable:()=>Ve,ZodNumber:()=>Zt,ZodObject:()=>he,ZodOptional:()=>xe,ZodParsedType:()=>A,ZodPipeline:()=>ti,ZodPromise:()=>St,ZodReadonly:()=>pn,ZodRecord:()=>xs,ZodSchema:()=>L,ZodSet:()=>nr,ZodString:()=>vt,ZodSymbol:()=>Qn,ZodTransformer:()=>Te,ZodTuple:()=>We,ZodType:()=>L,ZodUndefined:()=>nn,ZodUnion:()=>sn,ZodUnknown:()=>st,ZodVoid:()=>er,addIssueToContext:()=>R,any:()=>t0,array:()=>s0,bigint:()=>YE,boolean:()=>yp,coerce:()=>C0,custom:()=>mp,date:()=>XE,datetimeRegex:()=>fp,defaultErrorMap:()=>rt,discriminatedUnion:()=>l0,effect:()=>v0,enum:()=>_0,function:()=>h0,getErrorMap:()=>Yn,getParsedType:()=>Ke,instanceof:()=>qE,intersection:()=>d0,isAborted:()=>vs,isAsync:()=>Xn,isDirty:()=>ks,isValid:()=>wt,late:()=>zE,lazy:()=>g0,literal:()=>y0,makeIssue:()=>Qr,map:()=>p0,nan:()=>JE,nativeEnum:()=>b0,never:()=>r0,null:()=>e0,nullable:()=>S0,number:()=>gp,object:()=>o0,objectUtil:()=>tc,oboolean:()=>A0,onumber:()=>R0,optional:()=>k0,ostring:()=>T0,pipeline:()=>E0,preprocess:()=>x0,promise:()=>w0,quotelessJson:()=>vE,record:()=>f0,set:()=>m0,setErrorMap:()=>SE,strictObject:()=>a0,string:()=>hp,symbol:()=>ZE,transformer:()=>v0,tuple:()=>u0,undefined:()=>QE,union:()=>c0,unknown:()=>n0,util:()=>j,void:()=>i0});var oc=_(()=>{ws();rc();op();Zr();_p();bs()});var de=_(()=>{oc();oc()});var ac,cc=_(()=>{"use strict";de();ac=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 N0,bp=_(()=>{"use strict";de();cc();N0=ac.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 wp,vp,kp,Sp,lc,xp,Ep,Tp,O0,Rp=_(()=>{"use strict";de();wp=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],vp=m.enum(wp),kp=["new_to_ai_agents","new_to_this_client","experienced"],Sp=m.enum(kp),lc=[{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"}],xp=lc.map(e=>e.header),Ep=m.object({experience_level:m.array(Sp).default([]),stack_filters:m.array(m.string()).default([])}).default({experience_level:[],stack_filters:[]}),Tp=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:Ep,version:m.number().int().min(1).default(1),changelog:m.string().max(500).optional()}),O0=Tp.extend({body:m.string().min(1)})});var Cp,Ts,Ip,Rs,D0,P0,Np,Op,Dp,Pp,As,M0,$0,Ap,L0,Mp,F0,$p=_(()=>{"use strict";de();Cp=["operating_procedure","code_review","communication_style"],Ts=m.enum(Cp),Ip=["info","recommended","required"],Rs=m.enum(Ip),D0=["optional","default_on","mandatory"],P0=m.enum(D0),Np=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Op=m.enum(Np),Dp=["verify","contribute","mixed"],Pp=m.enum(Dp),As=m.object({clients:m.array(Op).default([]),stacks:m.array(m.string()).default([]),intents:m.array(Pp).default([])}).default({clients:[],stacks:[],intents:[]}),M0=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,$0=64,Ap=200,L0=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")),Mp=m.object({id:m.string().min(5).max($0).regex(M0,"id must match conv_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),scope:Ts,version:m.number().int().min(1),changed_at:L0,changelog:m.string().max(500).optional(),applies_to:As,severity:Rs.default("recommended"),disableability:P0.default("default_on"),summary:m.string().min(1).max(Ap,`summary must be \u2264 ${Ap} 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()}),F0=Mp.extend({body:m.string().min(1)})});var xt=_(()=>{"use strict";cc();bp();Rp();$p()});var dc,Cs,uc,Lp,Fp,jp,j0,Up=_(()=>{"use strict";de();dc=m.object({type:m.literal("text"),md:m.string().min(1).max(2e4)}),Cs=m.number().min(0).max(1).optional(),uc=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:Cs,right:Cs,bottom:Cs,left:Cs}).optional()}),Lp=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")}),Fp=m.object({type:m.literal("accordion"),title:m.string().min(1).max(200),subtag:Lp.optional(),blocks:m.array(m.discriminatedUnion("type",[dc,uc])).max(50)}),jp=m.discriminatedUnion("type",[dc,uc,Fp]),j0=m.array(jp).max(100)});var Hp,U0,Bp,Gp,H0,B0,G0,Kp=_(()=>{"use strict";de();Hp=["free","solo_pro","team","enterprise"],U0=m.enum(Hp),Bp=["solo_pro","team","enterprise"],Gp=m.enum(Bp),H0=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),B0=m.object({user_id:m.string().uuid(),tier:Gp,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:H0.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"}),G0=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Wp=_(()=>{"use strict"});var K0,W0,V0,Vp=_(()=>{"use strict";de();K0=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),W0=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:K0.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"}),V0=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var zp,z0,qp,Jp,Yp,Xp,q0,Zp=_(()=>{"use strict";de();zp=m.enum(["info","important","critical"]),z0=m.enum(["pass","warn","fail"]),qp=m.object({type:m.enum(["template","lesson"]),id:m.string().min(1)}),Jp=m.object({languages:m.array(m.string()).optional(),tools:m.array(m.string()).optional()}).optional(),Yp=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")})]),Xp=m.object({id:m.string().min(1),title:m.string().min(1),severity:zp,weight:m.number().int().positive().max(100),applies_when:Jp,check:Yp,fail_message:m.string().min(1),warn_message:m.string().optional(),remediation:qp.optional()}),q0=m.object({version:m.literal(1),checks:m.array(Xp).min(1)})});function Y0(e){if(!J0.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Is(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 X0(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var J0,Ns,Qp,em,ze,fc,tm,Z0,nm=_(()=>{"use strict";de();J0=/^\d{4}-\d{2}-\d{2}$/;o(Y0,"isRealDate");Ns=m.string().refine(Y0,{message:"expected a real calendar date as YYYY-MM-DD"}),Qp=["exact","prefix"],em=m.enum(Qp),ze=m.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),fc=[2e5,272e3],tm=m.object({model_pattern:m.string().min(1).max(100),match_kind:em,valid_from:Ns,valid_to:Ns.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=>Is(e)===0||Is(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"||Is(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=>Is(e)===0||e.context_threshold_tokens==null||fc.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${fc.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});o(Is,"aboveRateCount");o(X0,"rowKey");Z0=m.object({changelog:m.string().min(1).max(500),as_of:Ns,source_url:m.string().url().max(500),rows:m.array(tm).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let a=X0(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 ir=_(()=>{"use strict"});var ni=_(()=>{"use strict"});var om=_(()=>{"use strict";ni();ir()});var am=_(()=>{"use strict";ir()});var cm=_(()=>{"use strict";xt();ni();ir()});var lm=_(()=>{"use strict";ni();ir()});var dm=_(()=>{"use strict";ir();om();am();cm();lm();ni()});var yT,_T,um,bT,fm,pc,pm,mm,hm,gm,wT,mc=_(()=>{"use strict";de();xt();yT=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,_T=64,um=200,bT=1e3,fm=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")),pc=m.enum(["low","medium","high"]),pm=m.object({owner:m.string().min(1).max(160).optional(),risk_level:pc.optional(),reviewed_at:fm.optional()}).default({}),mm=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}),hm=m.object({lesson_query:mm,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:[]}),gm=m.object({id:m.string().min(6).max(_T).regex(yT,"id must match skill_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),version:m.number().int().min(1),changed_at:fm,tier:m.enum(["community","curated"]).default("curated"),summary:m.string().min(1).max(um,`summary must be \u2264 ${um} chars (rendered as one line in skill_index)`),description:m.string().max(bT).optional(),applies_to:As,membership:hm,governance:pm}),wT=gm.extend({body:m.string().default(""),org_id:m.string().uuid().optional(),org_name:m.string().optional()})});var ym,_m,bm,wm,vm,km,vT,Sm,kT,ST,xm=_(()=>{"use strict";de();mc();ym=m.enum(["maind","agent-skill"]),_m=m.enum(["ready","needs_attention","blocked"]),bm=m.enum(["info","important","critical"]),wm=m.enum(["pass","warn","fail"]),vm=m.enum(["structure","governance","scope","membership","package","references"]),km=m.object({id:m.string().min(1),title:m.string().min(1),status:wm,severity:bm,category:vm,field:m.string().nullable().optional(),message:m.string().min(1),hint:m.string().optional()}),vT=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({}),Sm=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(),kT=m.object({directory_name:m.string().min(1).max(120).optional(),frontmatter:Sm,body:m.string().default(""),file_listing:m.array(m.string()).optional()}),ST=m.object({format:ym,subject:m.string().min(1),status:_m,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(km),next_steps:m.array(m.string()),trust_note:m.string().min(1)})});var hc=_(()=>{"use strict"});var Em,ET,Tm,Rm,Am,sr,TT,Cm,Im,Nm,Om,Dm,Pm,Mm,$m,RT,Lm,Fm,jm,Et,gc,Um,Hm,AT,Bm=_(()=>{"use strict";de();xt();hc();Em=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],ET=m.enum(Em),Tm=["verdict","advisory"],Rm=m.enum(Tm),Am=["block","warn","note"],sr=m.enum(Am),TT=m.object({convention_id:m.string().min(1).max(64),convention_version:m.number().int().min(1),severity:Rs,scope:Ts,grade:Rm,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()}),Cm=["open","warn","info"],Im=m.enum(Cm),Nm=["introduced","pre_existing"],Om=m.enum(Nm),Dm=["full","partial","none"],Pm=m.enum(Dm),Mm=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:Im,baseline:Om,evidence_hash:m.string().regex(/^[a-f0-9]{64}$/),count:m.number().int().min(1).max(1e5)}),$m=m.object({version:m.literal(1).default(1),actions:m.object({required:sr.default("block"),recommended:sr.default("warn"),info:sr.default("note")}).default({}),overrides:m.array(m.object({convention_id:m.string().min(1).max(64),action:sr})).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:sr,reason:m.string().min(1).max(200)})).max(32).optional()}),RT=$m.parse({}),Lm=["ran","not_applicable","unavailable","ungraded"],Fm=m.enum(Lm),jm=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),state:Fm}),Et=1e3,gc=m.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Um=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()}),Hm=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:Pm}),AT=m.object({changed_symbols:m.array(Um).max(Et),risk_flags:m.array(m.string().max(64)).max(16),detector_findings:m.array(Mm).max(64),detector_runs:m.array(jm).min(1).max(32),diff_stats:Hm,commit_sha:gc.optional(),base_sha:gc.optional(),merge_base_sha:gc.optional(),dirty:m.boolean().optional(),code_index_version:m.string().min(1).max(32).optional()})});var Gm,Km,Wm,Vm,zm,yc,CT,IT,qm,Jm,Ym,Xm,Zm,NT,OT,Qm,eh,th,DT,nh=_(()=>{"use strict";de();Gm=14,Km=14,Wm=14,Vm=1,zm=365,yc=m.number().int().min(Vm).max(zm),CT=["propose","direct"],IT="propose",qm=["propose","direct"],Jm="propose",Ym=["propose","direct"],Xm="propose",Zm=["off","propose","direct"],NT=["member","admin","owner"],OT="member",Qm="off",eh="en",th=m.object({version:m.literal(1).default(1),at_risk_days:yc.default(Gm),stagnation_days:yc.default(Km),agent_date_mode:m.enum(CT).default(IT),health_manual_ttl_days:yc.default(Wm),agent_event_mode:m.enum(qm).default(Jm),agent_update_mode:m.enum(Ym).default(Xm),agent_pull_mode:m.enum(Zm).default(Qm),org_wide_authoring_min_role:m.enum(NT).default(OT),planning_language:m.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(eh)}),DT=th.parse({})});var rh,PT,ih=_(()=>{"use strict";de();rh=m.object({version:m.literal(1).default(1),org_visibility:m.boolean().default(!1),session_span_visibility:m.boolean().default(!0)}),PT=rh.parse({})});var sh,oh,MT,$T,ah=_(()=>{"use strict";de();sh=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([])}),oh=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:sh.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()}),MT=oh.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()}),$T=m.object({id:m.string().uuid(),title:m.string(),summary:m.string(),tags:m.array(m.string()).default([])})});var ch=_(()=>{"use strict"});function Os(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=FT.exec(r);if(!c)return;let l=c[3]??"";if(LT.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 LT,FT,lh=_(()=>{"use strict";LT=new Set(["|",">","|-",">-","|+",">+"]),FT=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;o(Os,"plainScalarViolations")});function ii(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 dh=_(()=>{"use strict";o(ii,"compareSemver")});var si=_(()=>{"use strict";xt();Up();xt();xt();Kp();Wp();Vp();Zp();nm();dm();xt();mc();xm();Bm();nh();ih();ah();ch();hc();lh();dh()});function uh(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
- `).slice(0,1e3)}var fh=_(()=>{"use strict";o(uh,"nodeEmbedText")});var _c,bc=_(()=>{"use strict";_c=["function","method","class","interface","enum","type_alias"]});function ph(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 mh=_(()=>{"use strict";o(ph,"cosineSimilarity")});import{execFileSync as jT}from"node:child_process";import{createHash as UT}from"node:crypto";import{readFileSync as HT}from"node:fs";import{posix as $e}from"node:path";function hh(e){let t=UT("sha256"),n=[];try{n=jT("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(l=>BT.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=HT($e.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=gh(l,i,0),u=$e.dirname(l)==="."?"":$e.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=yh(i(l));if(!d||typeof d.name!="string")continue;let u=$e.dirname(l)==="."?"":$e.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 gh(e,t,n){let r=yh(t(e));if(!r)return{};let i=$e.dirname(e)==="."?"":$e.dirname(e),s={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=$e.normalize($e.join(i,a.endsWith(".json")?a:a+".json"));s=gh(d,t,n+1)}let c=r.compilerOptions??{},l={...s};return typeof c.outDir=="string"&&(l.outDir=$e.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=$e.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 yh(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 of=Object.defineProperty;var s=(e,t)=>of(e,"name",{value:t,configurable:!0});var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var n in t)of(e,n,{get:t[n],enumerable:!0})};import{existsSync as kE,mkdirSync as xE,readdirSync as SE,readFileSync as EE,renameSync as TE,statSync as RE,unlinkSync as CE,writeFileSync as AE}from"node:fs";import{homedir as IE}from"node:os";import{join as Co}from"node:path";function Ao(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,i=To(r.id),o=To(r.key),a=To(r.title),c=To(r.status);if(!(!i||!o||!a||!c)&&(t.push({id:i,key:o,title:a,status:c}),t.length>=NE))break}return t}function Io(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 sf(e=IE()){return Co(e,".maind","assigned-told")}function af(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function cf(e){try{let t=JSON.parse(EE(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 PE(e,t,n){xE(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;AE(r,JSON.stringify(n),{mode:384}),TE(r,t)}function lf(e,t,n=sf()){let r=Co(n,`${af(e)}.json`);return kE(r)?t-cf(r).checked_at<DE:!1}function lc(e,t,n,r=sf()){try{let i=Co(r,`${af(e)}.json`),o=cf(i),a=t.filter(c=>!o.ids.includes(c.id));return PE(r,i,{ids:[...o.ids,...a.map(c=>c.id)].slice(-200),checked_at:n}),ME(r,n,i),a}catch{return[]}}function ME(e,t,n){try{for(let r of SE(e)){let i=Co(e,r);i!==n&&t-RE(i).mtimeMs>OE&&CE(i)}}catch{}}function df(e){return e==="claude-code"}var NE,OE,DE,To,Ro,si=v(()=>{"use strict";NE=5,OE=7*24*60*60*1e3,DE=6e4,To=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Ao,"parseAssignedList");s(Io,"assignedNoticeText");s(sf,"assignedToldDir");s(af,"safeName");s(cf,"readTold");s(PE,"writeTold");s(lf,"checkedRecently");s(lc,"takeUntold");s(ME,"pruneTold");Ro=class{static{s(this,"AssignedInbox")}current=[];told=new Set;update(t){if(!t||typeof t!="object")return;let n=t;n.ok===!0&&(this.current=Ao(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 Io(t)}};s(df,"clientHasHooks")});function mf(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 o={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"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function ir(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 pc(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function fc(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function mc(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var hc=v(()=>{"use strict";s(mf,"parseFrame");s(ir,"denyResult");s(pc,"toolEvent");s(fc,"policyEvent");s(mc,"shaEvent")});import{execFileSync as yf}from"node:child_process";function _f(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=VE}function zE(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 o of GE){let a=r[o];typeof a=="string"&&hf.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of KE){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&hf.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function qE(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,gf);for(let i=gf;i>=WE;i--){let o=r.slice(0,i),a=t(o);if(a!==null&&a.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function or(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 bf(){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 Oo(e=process.cwd()){try{let n=yf("git",["rev-parse","--show-toplevel"],{cwd:e,env:bf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function JE(e){return t=>{try{let r=yf("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:bf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function Do(e,t){if(t===null)return[];let n=zE(e);if(n.length===0)return[];let r=JE(t),i=[];for(let{field:o,sha:a}of n){let c=qE(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var GE,KE,hf,WE,gf,VE,gc=v(()=>{"use strict";GE=["commit_sha","base_sha","head_sha"],KE=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],hf=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,WE=7,gf=12,VE=10;s(_f,"isDenyGrade");s(zE,"extractShaArgs");s(qE,"classifySha");s(or,"shaFindingText");s(bf,"cleanGitEnv");s(Oo,"resolveRepoRootForSha");s(JE,"gitShaResolver");s(Do,"inspectLineForShas")});var wf=v(()=>{"use strict"});var H,_c,C,Je,ai=v(()=>{(function(e){e.assertEqual=i=>{};function t(i){}s(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of o)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(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,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(H||(H={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(_c||(_c={}));C=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=s(e=>{switch(typeof e){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(e)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(e)?C.array:e===null?C.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C.promise:typeof Map<"u"&&e instanceof Map?C.map:typeof Set<"u"&&e instanceof Set?C.set:typeof Date<"u"&&e instanceof Date?C.date:C.object;default:return C.unknown}},"getParsedType")});var E,YE,be,Po=v(()=>{ai();E=H.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"]),YE=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),be=class e extends Error{static{s(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(o){return o.message},r={_errors:[]},i=s(o=>{for(let a of o.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,H.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 o=i.path[0];n[o]=n[o]||[],n[o].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};be.create=e=>new be(e)});var XE,pt,bc=v(()=>{Po();ai();XE=s((e,t)=>{let n;switch(e.code){case E.invalid_type:e.received===C.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,H.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${H.joinValues(e.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${H.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${H.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}"`:H.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,H.assertNever(e)}return{message:n}},"errorMap"),pt=XE});function ZE(e){kf=e}function sr(){return kf}var kf,Mo=v(()=>{bc();kf=pt;s(ZE,"setErrorMap");s(sr,"getErrorMap")});function R(e,t){let n=sr(),r=ci({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===pt?void 0:pt].filter(i=>!!i)});e.common.issues.push(r)}var ci,QE,ie,O,rn,pe,$o,Lo,At,ar,vc=v(()=>{Mo();bc();ci=s(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,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:o,message:c}},"makeIssue"),QE=[];s(R,"addIssueToContext");ie=class e{static{s(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 o=await i.key,a=await i.value;r.push({key:o,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return O;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}},O=Object.freeze({status:"aborted"}),rn=s(e=>({status:"dirty",value:e}),"DIRTY"),pe=s(e=>({status:"valid",value:e}),"OK"),$o=s(e=>e.status==="aborted","isAborted"),Lo=s(e=>e.status==="dirty","isDirty"),At=s(e=>e.status==="valid","isValid"),ar=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var xf=v(()=>{});var I,Sf=v(()=>{(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:s((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 Cf(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 g0(e){return new RegExp(`^${Cf(e)}$`)}function Af(e){let t=`${Rf}T${Cf(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 y0(e,t){return!!((t==="v4"||!t)&&l0.test(e)||(t==="v6"||!t)&&u0.test(e))}function _0(e,t){if(!o0.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 b0(e,t){return!!((t==="v4"||!t)&&d0.test(e)||(t==="v6"||!t)&&p0.test(e))}function v0(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}function cr(e){if(e instanceof ve){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ae.create(cr(r))}return new ve({...e._def,shape:s(()=>t,"shape")})}else return e instanceof ht?new ht({...e._def,type:cr(e.element)}):e instanceof Ae?Ae.create(cr(e.unwrap())):e instanceof Xe?Xe.create(cr(e.unwrap())):e instanceof Ye?Ye.create(e.items.map(t=>cr(t))):e}function kc(e,t){let n=Je(e),r=Je(t);if(e===t)return{valid:!0,data:e};if(n===C.object&&r===C.object){let i=H.objectKeys(t),o=H.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of o){let l=kc(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===C.array&&r===C.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],c=t[o],l=kc(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===C.date&&r===C.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function If(e,t){return new hn({values:e,typeName:D.ZodEnum,...M(t)})}function Tf(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Nf(e,t={},n){return e?Nt.create().superRefine((r,i)=>{let o=e(r);if(o instanceof Promise)return o.then(a=>{if(!a){let c=Tf(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!o){let a=Tf(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Nt.create()}var Ie,Ef,F,e0,t0,n0,r0,i0,o0,s0,a0,c0,wc,l0,d0,u0,p0,f0,m0,Rf,h0,It,on,sn,an,cn,lr,ln,dn,Nt,mt,Fe,dr,ht,ve,un,ft,Fo,pn,Ye,jo,ur,pr,Ho,fn,mn,hn,gn,Ot,Ne,Ae,Xe,yn,_n,fr,w0,li,di,bn,k0,D,x0,Of,Df,S0,E0,Pf,T0,R0,C0,A0,I0,N0,O0,D0,P0,M0,$0,L0,F0,j0,H0,U0,B0,G0,K0,W0,V0,z0,q0,J0,Y0,X0,Z0,Q0,eT,tT,nT,rT,iT,oT,Mf=v(()=>{Po();Mo();Sf();vc();ai();Ie=class{static{s(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}},Ef=s((e,t)=>{if(At(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 be(e.common.issues);return this._error=n,this._error}}},"handleResult");s(M,"processCreateParams");F=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return Je(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ie,ctx:{common:t.parent.common,data:t.data,parsedType:Je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(ar(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:Je(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Ef(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return At(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=>At(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:Je(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(ar(i)?i:Promise.resolve(i));return Ef(r,o)}refine(t,n){let r=s(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,o)=>{let a=t(i),c=s(()=>o.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 Ne({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:s(n=>this["~validate"](n),"validate")}}optional(){return Ae.create(this,this._def)}nullable(){return Xe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ht.create(this)}promise(){return Ot.create(this,this._def)}or(t){return un.create([this,t],this._def)}and(t){return pn.create(this,t,this._def)}transform(t){return new Ne({...M(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new yn({...M(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new li({typeName:D.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new _n({...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 di.create(this,t)}readonly(){return bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},e0=/^c[^\s-]{8,}$/i,t0=/^[0-9a-z]+$/,n0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,r0=/^[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,i0=/^[a-z0-9_-]{21}$/i,o0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,s0=/^[-+]?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)?)??$/,a0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,c0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",l0=/^(?:(?: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])$/,d0=/^(?:(?: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])$/,u0=/^(([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]))$/,p0=/^(([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])$/,f0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,m0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rf="((\\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])))",h0=new RegExp(`^${Rf}$`);s(Cf,"timeRegexSource");s(g0,"timeRegex");s(Af,"datetimeRegex");s(y0,"isValidIP");s(_0,"isValidJWT");s(b0,"isValidCidr");It=class e extends F{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C.string){let o=this._getOrReturnCtx(t);return R(o,{code:E.invalid_type,expected:C.string,received:o.parsedType}),O}let r=new ie,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,c=t.data.length<o.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?R(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&R(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")a0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"email",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")wc||(wc=new RegExp(c0,"u")),wc.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"emoji",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")r0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"uuid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")i0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"nanoid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")e0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")t0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid2",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")n0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ulid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),R(i,{validation:"url",code:E.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"regex",code:E.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Af(o).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?h0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?g0(o).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:E.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?s0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"duration",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?y0(t.data,o.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ip",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?_0(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"jwt",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?b0(t.data,o.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cidr",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?f0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?m0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64url",code:E.invalid_string,message:o.message}),r.dirty()):H.assertNever(o);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}};It.create=e=>new It({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...M(e)});s(v0,"floatSafeRemainder");on=class e extends F{static{s(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)!==C.number){let o=this._getOrReturnCtx(t);return R(o,{code:E.invalid_type,expected:C.number,received:o.parsedType}),O}let r,i=new ie;for(let o of this._def.checks)o.kind==="int"?H.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),R(r,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?v0(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),R(r,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),R(r,{code:E.not_finite,message:o.message}),i.dirty()):H.assertNever(o);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"&&H.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)}};on.create=e=>new on({checks:[],typeName:D.ZodNumber,coerce:e?.coerce||!1,...M(e)});sn=class e extends F{static{s(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)!==C.bigint)return this._getInvalidInput(t);let r,i=new ie;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),R(r,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):H.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return R(n,{code:E.invalid_type,expected:C.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}};sn.create=e=>new sn({checks:[],typeName:D.ZodBigInt,coerce:e?.coerce??!1,...M(e)});an=class extends F{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C.boolean){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:C.boolean,received:r.parsedType}),O}return pe(t.data)}};an.create=e=>new an({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...M(e)});cn=class e extends F{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C.date){let o=this._getOrReturnCtx(t);return R(o,{code:E.invalid_type,expected:C.date,received:o.parsedType}),O}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return R(o,{code:E.invalid_date}),O}let r=new ie,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):H.assertNever(o);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}};cn.create=e=>new cn({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...M(e)});lr=class extends F{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==C.symbol){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:C.symbol,received:r.parsedType}),O}return pe(t.data)}};lr.create=e=>new lr({typeName:D.ZodSymbol,...M(e)});ln=class extends F{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:C.undefined,received:r.parsedType}),O}return pe(t.data)}};ln.create=e=>new ln({typeName:D.ZodUndefined,...M(e)});dn=class extends F{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==C.null){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:C.null,received:r.parsedType}),O}return pe(t.data)}};dn.create=e=>new dn({typeName:D.ZodNull,...M(e)});Nt=class extends F{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}};Nt.create=e=>new Nt({typeName:D.ZodAny,...M(e)});mt=class extends F{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}};mt.create=e=>new mt({typeName:D.ZodUnknown,...M(e)});Fe=class extends F{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return R(n,{code:E.invalid_type,expected:C.never,received:n.parsedType}),O}};Fe.create=e=>new Fe({typeName:D.ZodNever,...M(e)});dr=class extends F{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:C.void,received:r.parsedType}),O}return pe(t.data)}};dr.create=e=>new dr({typeName:D.ZodVoid,...M(e)});ht=class e extends F{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==C.array)return R(n,{code:E.invalid_type,expected:C.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)&&(R(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&&(R(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&&(R(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 Ie(n,a,n.path,c)))).then(a=>ie.mergeArray(r,a));let o=[...n.data].map((a,c)=>i.type._parseSync(new Ie(n,a,n.path,c)));return ie.mergeArray(r,o)}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)}};ht.create=(e,t)=>new ht({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...M(t)});s(cr,"deepPartialify");ve=class e extends F{static{s(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=H.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==C.object){let d=this._getOrReturnCtx(t);return R(d,{code:E.invalid_type,expected:C.object,received:d.parsedType}),O}let{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Fe&&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=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Ie(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof Fe){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&&(R(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 Ie(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=>ie.mergeObjectSync(r,d)):ie.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:s((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:s(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:s(()=>({...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 H.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}omit(t){let n={};for(let r of H.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}deepPartial(){return cr(this)}partial(t){let n={};for(let r of H.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of H.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ae;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return If(H.objectKeys(this.shape))}};ve.create=(e,t)=>new ve({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:Fe.create(),typeName:D.ZodObject,...M(t)});ve.strictCreate=(e,t)=>new ve({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:Fe.create(),typeName:D.ZodObject,...M(t)});ve.lazycreate=(e,t)=>new ve({shape:e,unknownKeys:"strip",catchall:Fe.create(),typeName:D.ZodObject,...M(t)});un=class extends F{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=o.map(c=>new be(c.ctx.common.issues));return R(n,{code:E.invalid_union,unionErrors:a}),O}if(s(i,"handleResults"),n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let o,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"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let c=a.map(l=>new be(l));return R(n,{code:E.invalid_union,unionErrors:c}),O}}get options(){return this._def.options}};un.create=(e,t)=>new un({options:e,typeName:D.ZodUnion,...M(t)});ft=s(e=>e instanceof fn?ft(e.schema):e instanceof Ne?ft(e.innerType()):e instanceof mn?[e.value]:e instanceof hn?e.options:e instanceof gn?H.objectValues(e.enum):e instanceof yn?ft(e._def.innerType):e instanceof ln?[void 0]:e instanceof dn?[null]:e instanceof Ae?[void 0,...ft(e.unwrap())]:e instanceof Xe?[null,...ft(e.unwrap())]:e instanceof li||e instanceof bn?ft(e.unwrap()):e instanceof _n?ft(e._def.innerType):[],"getDiscriminator"),Fo=class e extends F{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.object)return R(n,{code:E.invalid_type,expected:C.object,received:n.parsedType}),O;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(R(n,{code:E.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 o of n){let a=ft(o.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,o)}}return new e({typeName:D.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...M(r)})}};s(kc,"mergeValues");pn=class extends F{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=s((o,a)=>{if($o(o)||$o(a))return O;let c=kc(o.value,a.value);return c.valid?((Lo(o)||Lo(a))&&n.dirty(),{status:n.value,value:c.data}):(R(r,{code:E.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(([o,a])=>i(o,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}))}};pn.create=(e,t,n)=>new pn({left:e,right:t,typeName:D.ZodIntersection,...M(n)});Ye=class e extends F{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.array)return R(r,{code:E.invalid_type,expected:C.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return R(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(R(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Ie(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>ie.mergeArray(n,a)):ie.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ye.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ye({items:e,typeName:D.ZodTuple,rest:null,...M(t)})};jo=class e extends F{static{s(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!==C.object)return R(r,{code:E.invalid_type,expected:C.object,received:r.parsedType}),O;let i=[],o=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:o._parse(new Ie(r,c,r.path,c)),value:a._parse(new Ie(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ie.mergeObjectAsync(n,i):ie.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof F?new e({keyType:t,valueType:n,typeName:D.ZodRecord,...M(r)}):new e({keyType:It.create(),valueType:t,typeName:D.ZodRecord,...M(n)})}},ur=class extends F{static{s(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!==C.map)return R(r,{code:E.invalid_type,expected:C.map,received:r.parsedType}),O;let i=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new Ie(r,c,r.path,[d,"key"])),value:o._parse(new Ie(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}}}};ur.create=(e,t,n)=>new ur({valueType:t,keyType:e,typeName:D.ZodMap,...M(n)});pr=class e extends F{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.set)return R(r,{code:E.invalid_type,expected:C.set,received:r.parsedType}),O;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(R(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&&(R(r,{code:E.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=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}}s(a,"finalizeSet");let c=[...r.data.values()].map((l,d)=>o._parse(new Ie(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)}};pr.create=(e,t)=>new pr({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...M(t)});Ho=class e extends F{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.function)return R(n,{code:E.invalid_type,expected:C.function,received:n.parsedType}),O;function r(c,l){return ci({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sr(),pt].filter(d=>!!d),issueData:{code:E.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function i(c,l){return ci({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sr(),pt].filter(d=>!!d),issueData:{code:E.invalid_return_type,returnTypeError:l}})}s(i,"makeReturnsIssue");let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Ot){let c=this;return pe(async function(...l){let d=new be([]),u=await c._def.args.parseAsync(l,o).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(m=>{throw d.addIssue(i(p,m)),d})})}else{let c=this;return pe(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new be([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new be([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:Ye.create(t).rest(mt.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||Ye.create([]).rest(mt.create()),returns:n||mt.create(),typeName:D.ZodFunction,...M(r)})}},fn=class extends F{static{s(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})}};fn.create=(e,t)=>new fn({getter:e,typeName:D.ZodLazy,...M(t)});mn=class extends F{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return R(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:t.data}}get value(){return this._def.value}};mn.create=(e,t)=>new mn({value:e,typeName:D.ZodLiteral,...M(t)});s(If,"createZodEnum");hn=class e extends F{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return R(n,{expected:H.joinValues(r),received:n.parsedType,code:E.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 R(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return pe(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})}};hn.create=If;gn=class extends F{static{s(this,"ZodNativeEnum")}_parse(t){let n=H.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==C.string&&r.parsedType!==C.number){let i=H.objectValues(n);return R(r,{expected:H.joinValues(i),received:r.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=H.objectValues(n);return R(r,{received:r.data,code:E.invalid_enum_value,options:i}),O}return pe(t.data)}get enum(){return this._def.values}};gn.create=(e,t)=>new gn({values:e,typeName:D.ZodNativeEnum,...M(t)});Ot=class extends F{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.promise&&n.common.async===!1)return R(n,{code:E.invalid_type,expected:C.promise,received:n.parsedType}),O;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return pe(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Ot.create=(e,t)=>new Ot({type:e,typeName:D.ZodPromise,...M(t)});Ne=class extends F{static{s(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,o={addIssue:s(a=>{R(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(r.data,o);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"?rn(l.value):n.value==="dirty"?rn(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"?rn(c.value):n.value==="dirty"?rn(c.value):c}}if(i.type==="refinement"){let a=s(c=>{let l=i.refinement(c,o);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(!At(a))return O;let c=i.transform(a.value,o);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=>At(a)?Promise.resolve(i.transform(a.value,o)).then(c=>({status:n.value,value:c})):O);H.assertNever(i)}};Ne.create=(e,t,n)=>new Ne({schema:e,typeName:D.ZodEffects,effect:t,...M(n)});Ne.createWithPreprocess=(e,t,n)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...M(n)});Ae=class extends F{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===C.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ae.create=(e,t)=>new Ae({innerType:e,typeName:D.ZodOptional,...M(t)});Xe=class extends F{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===C.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Xe.create=(e,t)=>new Xe({innerType:e,typeName:D.ZodNullable,...M(t)});yn=class extends F{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};yn.create=(e,t)=>new yn({innerType:e,typeName:D.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});_n=class extends F{static{s(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 ar(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new be(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new be(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};_n.create=(e,t)=>new _n({innerType:e,typeName:D.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});fr=class extends F{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==C.nan){let r=this._getOrReturnCtx(t);return R(r,{code:E.invalid_type,expected:C.nan,received:r.parsedType}),O}return{status:"valid",value:t.data}}};fr.create=e=>new fr({typeName:D.ZodNaN,...M(e)});w0=Symbol("zod_brand"),li=class extends F{static{s(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}},di=class e extends F{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),rn(o.value)):this._def.out._parseAsync({data:o.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})}},bn=class extends F{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(i=>(At(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return ar(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};bn.create=(e,t)=>new bn({innerType:e,typeName:D.ZodReadonly,...M(t)});s(Tf,"cleanParams");s(Nf,"custom");k0={object:ve.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={}));x0=s((e,t={message:`Input not instance of ${e.name}`})=>Nf(n=>n instanceof e,t),"instanceOfType"),Of=It.create,Df=on.create,S0=fr.create,E0=sn.create,Pf=an.create,T0=cn.create,R0=lr.create,C0=ln.create,A0=dn.create,I0=Nt.create,N0=mt.create,O0=Fe.create,D0=dr.create,P0=ht.create,M0=ve.create,$0=ve.strictCreate,L0=un.create,F0=Fo.create,j0=pn.create,H0=Ye.create,U0=jo.create,B0=ur.create,G0=pr.create,K0=Ho.create,W0=fn.create,V0=mn.create,z0=hn.create,q0=gn.create,J0=Ot.create,Y0=Ne.create,X0=Ae.create,Z0=Xe.create,Q0=Ne.createWithPreprocess,eT=di.create,tT=s(()=>Of().optional(),"ostring"),nT=s(()=>Df().optional(),"onumber"),rT=s(()=>Pf().optional(),"oboolean"),iT={string:s(e=>It.create({...e,coerce:!0}),"string"),number:s(e=>on.create({...e,coerce:!0}),"number"),boolean:s(e=>an.create({...e,coerce:!0}),"boolean"),bigint:s(e=>sn.create({...e,coerce:!0}),"bigint"),date:s(e=>cn.create({...e,coerce:!0}),"date")},oT=O});var h={};Q(h,{BRAND:()=>w0,DIRTY:()=>rn,EMPTY_PATH:()=>QE,INVALID:()=>O,NEVER:()=>oT,OK:()=>pe,ParseStatus:()=>ie,Schema:()=>F,ZodAny:()=>Nt,ZodArray:()=>ht,ZodBigInt:()=>sn,ZodBoolean:()=>an,ZodBranded:()=>li,ZodCatch:()=>_n,ZodDate:()=>cn,ZodDefault:()=>yn,ZodDiscriminatedUnion:()=>Fo,ZodEffects:()=>Ne,ZodEnum:()=>hn,ZodError:()=>be,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Ho,ZodIntersection:()=>pn,ZodIssueCode:()=>E,ZodLazy:()=>fn,ZodLiteral:()=>mn,ZodMap:()=>ur,ZodNaN:()=>fr,ZodNativeEnum:()=>gn,ZodNever:()=>Fe,ZodNull:()=>dn,ZodNullable:()=>Xe,ZodNumber:()=>on,ZodObject:()=>ve,ZodOptional:()=>Ae,ZodParsedType:()=>C,ZodPipeline:()=>di,ZodPromise:()=>Ot,ZodReadonly:()=>bn,ZodRecord:()=>jo,ZodSchema:()=>F,ZodSet:()=>pr,ZodString:()=>It,ZodSymbol:()=>lr,ZodTransformer:()=>Ne,ZodTuple:()=>Ye,ZodType:()=>F,ZodUndefined:()=>ln,ZodUnion:()=>un,ZodUnknown:()=>mt,ZodVoid:()=>dr,addIssueToContext:()=>R,any:()=>I0,array:()=>P0,bigint:()=>E0,boolean:()=>Pf,coerce:()=>iT,custom:()=>Nf,date:()=>T0,datetimeRegex:()=>Af,defaultErrorMap:()=>pt,discriminatedUnion:()=>F0,effect:()=>Y0,enum:()=>z0,function:()=>K0,getErrorMap:()=>sr,getParsedType:()=>Je,instanceof:()=>x0,intersection:()=>j0,isAborted:()=>$o,isAsync:()=>ar,isDirty:()=>Lo,isValid:()=>At,late:()=>k0,lazy:()=>W0,literal:()=>V0,makeIssue:()=>ci,map:()=>B0,nan:()=>S0,nativeEnum:()=>q0,never:()=>O0,null:()=>A0,nullable:()=>Z0,number:()=>Df,object:()=>M0,objectUtil:()=>_c,oboolean:()=>rT,onumber:()=>nT,optional:()=>X0,ostring:()=>tT,pipeline:()=>eT,preprocess:()=>Q0,promise:()=>J0,quotelessJson:()=>YE,record:()=>U0,set:()=>G0,setErrorMap:()=>ZE,strictObject:()=>$0,string:()=>Of,symbol:()=>R0,transformer:()=>Y0,tuple:()=>H0,undefined:()=>C0,union:()=>L0,unknown:()=>N0,util:()=>H,void:()=>D0});var xc=v(()=>{Mo();vc();xf();ai();Mf();Po()});var fe=v(()=>{xc();xc()});var Sc,Ec=v(()=>{"use strict";fe();Sc=h.object({id:h.string().min(1),title:h.string().min(1).max(200),type:h.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:h.enum(["community","curated"]),lesson_class:h.enum(["general","architecture"]).default("general"),quality_tier:h.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:h.object({source:h.enum(["memory","vault","claude-md"]),source_id:h.string().min(1),migrated_at:h.string(),migrated_from_workspace:h.string().optional()}).optional(),context:h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),summary:h.string().min(1).max(500),problem:h.string().optional(),solution:h.string().optional(),gotchas:h.array(h.string()).default([]),template_body:h.string().min(1).optional(),target_file:h.string().min(1).optional(),submitted_by:h.string().optional(),evidence:h.string().optional(),last_validated_at:h.string().optional(),tool_versions:h.record(h.string(),h.string()).optional(),upvotes:h.number().int().nonnegative().default(0),version:h.number().int().min(1).default(1),changed_at:h.string().optional(),changelog:h.string().max(500).optional(),revision_of:h.string().optional(),org_id:h.string().uuid().optional(),org_name:h.string().optional(),scope:h.literal("private").optional(),body:h.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:h.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:h.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var sT,$f=v(()=>{"use strict";fe();Ec();sT=Sc.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:h.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:h.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:h.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:h.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var Lf,Ff,jf,Hf,Tc,Uf,Bf,Gf,aT,Kf=v(()=>{"use strict";fe();Lf=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Ff=h.enum(Lf),jf=["new_to_ai_agents","new_to_this_client","experienced"],Hf=h.enum(jf),Tc=[{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"}],Uf=Tc.map(e=>e.header),Bf=h.object({experience_level:h.array(Hf).default([]),stack_filters:h.array(h.string()).default([])}).default({experience_level:[],stack_filters:[]}),Gf=h.object({id:h.string().min(1),client:Ff,title:h.string().min(1),last_updated:h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:Bf,version:h.number().int().min(1).default(1),changelog:h.string().max(500).optional()}),aT=Gf.extend({body:h.string().min(1)})});var Vf,Uo,zf,Bo,cT,lT,qf,Jf,Yf,Xf,Go,dT,uT,Wf,pT,Zf,fT,Qf=v(()=>{"use strict";fe();Vf=["operating_procedure","code_review","communication_style"],Uo=h.enum(Vf),zf=["info","recommended","required"],Bo=h.enum(zf),cT=["optional","default_on","mandatory"],lT=h.enum(cT),qf=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Jf=h.enum(qf),Yf=["verify","contribute","mixed"],Xf=h.enum(Yf),Go=h.object({clients:h.array(Jf).default([]),stacks:h.array(h.string()).default([]),intents:h.array(Xf).default([])}).default({clients:[],stacks:[],intents:[]}),dT=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,uT=64,Wf=200,pT=h.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Zf=h.object({id:h.string().min(5).max(uT).regex(dT,"id must match conv_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),scope:Uo,version:h.number().int().min(1),changed_at:pT,changelog:h.string().max(500).optional(),applies_to:Go,severity:Bo.default("recommended"),disableability:lT.default("default_on"),summary:h.string().min(1).max(Wf,`summary must be \u2264 ${Wf} chars (rendered as one line in init-push)`),review_gate:h.object({enabled:h.boolean(),min_matched_symbols:h.number().int().min(1).max(8).default(2),hard:h.boolean().default(!1)}).optional(),gateway_gate:h.object({enabled:h.boolean(),deny_tools:h.array(h.string().min(1).max(128)).min(1).max(16),servers:h.array(h.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),fT=Zf.extend({body:h.string().min(1)})});var Dt=v(()=>{"use strict";Ec();$f();Kf();Qf()});var Rc,Ko,Cc,em,tm,nm,mT,rm=v(()=>{"use strict";fe();Rc=h.object({type:h.literal("text"),md:h.string().min(1).max(2e4)}),Ko=h.number().min(0).max(1).optional(),Cc=h.object({type:h.literal("media"),kind:h.enum(["image","video"]),url:h.string().url().max(2048),alt:h.string().max(500).optional(),caption:h.string().max(500).optional(),fog:h.object({top:Ko,right:Ko,bottom:Ko,left:Ko}).optional()}),em=h.object({label:h.string().min(1).max(40),color:h.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),tm=h.object({type:h.literal("accordion"),title:h.string().min(1).max(200),subtag:em.optional(),blocks:h.array(h.discriminatedUnion("type",[Rc,Cc])).max(50)}),nm=h.discriminatedUnion("type",[Rc,Cc,tm]),mT=h.array(nm).max(100)});var im,hT,om,sm,gT,yT,_T,am=v(()=>{"use strict";fe();im=["free","solo_pro","team","enterprise"],hT=h.enum(im),om=["solo_pro","team","enterprise"],sm=h.enum(om),gT=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),yT=h.object({user_id:h.string().uuid(),tier:sm,reason:h.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:gT.nullable().optional(),auto_revoke_on_stripe:h.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"}),_T=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var cm=v(()=>{"use strict"});var bT,vT,wT,lm=v(()=>{"use strict";fe();bT=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),vT=h.object({org_id:h.string().uuid(),seats:h.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:h.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:bT.nullable().optional(),auto_revoke_on_stripe:h.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"}),wT=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var dm,kT,um,pm,fm,mm,xT,hm=v(()=>{"use strict";fe();dm=h.enum(["info","important","critical"]),kT=h.enum(["pass","warn","fail"]),um=h.object({type:h.enum(["template","lesson"]),id:h.string().min(1)}),pm=h.object({languages:h.array(h.string()).optional(),tools:h.array(h.string()).optional()}).optional(),fm=h.discriminatedUnion("kind",[h.object({kind:h.literal("file-exists"),path:h.string().min(1)}),h.object({kind:h.literal("any-file-exists"),paths:h.array(h.string().min(1)).min(1)}),h.object({kind:h.literal("any-agent-config")}),h.object({kind:h.literal("file-size-budget"),field:h.enum(["claude_md","readme"]),max_chars:h.number().int().positive()}),h.object({kind:h.literal("readme-section-present"),headers:h.array(h.string().min(1)).min(1)}),h.object({kind:h.literal("adr-dir-present")}),h.object({kind:h.literal("git-present")}),h.object({kind:h.literal("quality-gates-configured"),pass_if_at_least:h.number().int().min(1).max(4).optional(),warn_if_at_least:h.number().int().min(0).max(4).optional()}),h.object({kind:h.literal("storage-risk-safe"),allow_unknown:h.boolean().optional()}),h.object({kind:h.literal("doc-path-discoverability")})]),mm=h.object({id:h.string().min(1),title:h.string().min(1),severity:dm,weight:h.number().int().positive().max(100),applies_when:pm,check:fm,fail_message:h.string().min(1),warn_message:h.string().optional(),remediation:um.optional()}),xT=h.object({version:h.literal(1),checks:h.array(mm).min(1)})});function ET(e){if(!ST.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Wo(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 TT(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var ST,Vo,gm,ym,Ze,Ac,_m,RT,bm=v(()=>{"use strict";fe();ST=/^\d{4}-\d{2}-\d{2}$/;s(ET,"isRealDate");Vo=h.string().refine(ET,{message:"expected a real calendar date as YYYY-MM-DD"}),gm=["exact","prefix"],ym=h.enum(gm),Ze=h.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Ac=[2e5,272e3],_m=h.object({model_pattern:h.string().min(1).max(100),match_kind:ym,valid_from:Vo,valid_to:Vo.nullable().optional(),input:Ze,output:Ze,cache_read:Ze,cache_write_5m:Ze,cache_write_1h:Ze,long_context:h.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:h.number().int().positive().nullable().optional(),source_url:h.string().url().max(500).nullable().optional(),note:h.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=>Wo(e)===0||Wo(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"||Wo(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=>Wo(e)===0||e.context_threshold_tokens==null||Ac.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Ac.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Wo,"aboveRateCount");s(TT,"rowKey");RT=h.object({changelog:h.string().min(1).max(500),as_of:Vo,source_url:h.string().url().max(500),rows:h.array(_m).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,o)=>{let a=TT(i),c=n.get(a);c!==void 0?t.addIssue({code:h.ZodIssueCode.custom,path:["rows",o],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,o)});let r=new Map;e.rows.forEach((i,o)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:o,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((o,a)=>o.r.valid_from.localeCompare(a.r.valid_from));for(let o=0;o<i.length-1;o++){let a=i[o],c=i[o+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:h.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 mr=v(()=>{"use strict"});var ui=v(()=>{"use strict"});var xm=v(()=>{"use strict";ui();mr()});var Sm=v(()=>{"use strict";mr()});var Em=v(()=>{"use strict";Dt();ui();mr()});var Tm=v(()=>{"use strict";ui();mr()});var Rm=v(()=>{"use strict";mr();xm();Sm();Em();Tm();ui()});var VT,zT,Cm,qT,Am,Ic,Im,Nm,Om,Dm,JT,Nc=v(()=>{"use strict";fe();Dt();VT=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,zT=64,Cm=200,qT=1e3,Am=h.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Ic=h.enum(["low","medium","high"]),Im=h.object({owner:h.string().min(1).max(160).optional(),risk_level:Ic.optional(),reviewed_at:Am.optional()}).default({}),Nm=h.object({tags:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),limit:h.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),Om=h.object({lesson_query:Nm,lesson_pins:h.array(h.string()).default([]),lesson_excludes:h.array(h.string()).default([]),convention_ids:h.array(h.string()).default([]),template_ids:h.array(h.string()).default([]),setup_guide_ids:h.array(h.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Dm=h.object({id:h.string().min(6).max(zT).regex(VT,"id must match skill_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),version:h.number().int().min(1),changed_at:Am,tier:h.enum(["community","curated"]).default("curated"),summary:h.string().min(1).max(Cm,`summary must be \u2264 ${Cm} chars (rendered as one line in skill_index)`),description:h.string().max(qT).optional(),applies_to:Go,membership:Om,governance:Im}),JT=Dm.extend({body:h.string().default(""),org_id:h.string().uuid().optional(),org_name:h.string().optional()})});var Pm,Mm,$m,Lm,Fm,jm,YT,Hm,XT,ZT,Um=v(()=>{"use strict";fe();Nc();Pm=h.enum(["maind","agent-skill"]),Mm=h.enum(["ready","needs_attention","blocked"]),$m=h.enum(["info","important","critical"]),Lm=h.enum(["pass","warn","fail"]),Fm=h.enum(["structure","governance","scope","membership","package","references"]),jm=h.object({id:h.string().min(1),title:h.string().min(1),status:Lm,severity:$m,category:Fm,field:h.string().nullable().optional(),message:h.string().min(1),hint:h.string().optional()}),YT=h.object({lesson_ids:h.array(h.string()).optional(),convention_ids:h.array(h.string()).optional(),template_ids:h.array(h.string()).optional(),setup_guide_ids:h.array(h.string()).optional()}).default({}),Hm=h.object({name:h.string().min(1).max(64),description:h.string().min(1).max(1024),license:h.string().optional(),compatibility:h.union([h.string(),h.array(h.string())]).optional(),metadata:h.record(h.string()).default({}),"allowed-tools":h.union([h.string(),h.array(h.string())]).optional()}).passthrough(),XT=h.object({directory_name:h.string().min(1).max(120).optional(),frontmatter:Hm,body:h.string().default(""),file_listing:h.array(h.string()).optional()}),ZT=h.object({format:Pm,subject:h.string().min(1),status:Mm,summary:h.string().min(1),counts:h.object({pass:h.number().int().min(0),warn:h.number().int().min(0),fail:h.number().int().min(0)}),checks:h.array(jm),next_steps:h.array(h.string()),trust_note:h.string().min(1)})});var Oc=v(()=>{"use strict"});var Bm,eR,Gm,Km,Wm,hr,tR,Vm,zm,qm,Jm,Ym,Xm,Zm,Qm,nR,eh,th,nh,Pt,Dc,rh,ih,rR,oh=v(()=>{"use strict";fe();Dt();Oc();Bm=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],eR=h.enum(Bm),Gm=["verdict","advisory"],Km=h.enum(Gm),Wm=["block","warn","note"],hr=h.enum(Wm),tR=h.object({convention_id:h.string().min(1).max(64),convention_version:h.number().int().min(1),severity:Bo,scope:Uo,grade:Km,matched_symbols:h.array(h.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:h.array(h.string().min(1).max(512)).max(64).default([]),summary:h.string().max(2e3),hard:h.boolean().optional()}),Vm=["open","warn","info"],zm=h.enum(Vm),qm=["introduced","pre_existing"],Jm=h.enum(qm),Ym=["full","partial","none"],Xm=h.enum(Ym),Zm=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),rule_id:h.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:zm,baseline:Jm,evidence_hash:h.string().regex(/^[a-f0-9]{64}$/),count:h.number().int().min(1).max(1e5)}),Qm=h.object({version:h.literal(1).default(1),actions:h.object({required:hr.default("block"),recommended:hr.default("warn"),info:hr.default("note")}).default({}),overrides:h.array(h.object({convention_id:h.string().min(1).max(64),action:hr})).max(64).default([]),risk_flag_action:h.enum(["warn","note","ignore"]).default("warn"),detector_overrides:h.array(h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),action:hr,reason:h.string().min(1).max(200)})).max(32).optional()}),nR=Qm.parse({}),eh=["ran","not_applicable","unavailable","ungraded"],th=h.enum(eh),nh=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),state:th}),Pt=1e3,Dc=h.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),rh=h.object({name:h.string().min(1).max(200),qualified_name:h.string().min(1).max(512).optional(),kind:h.string().min(1).max(64).optional(),language:h.string().min(1).max(32).optional(),change:h.enum(["added","modified","co_located"]).optional(),changed_line_count:h.number().int().min(0).max(1e4).optional()}),ih=h.object({base_kind:h.enum(["uncommitted","ref"]),changed_file_count:h.number().int().min(0),stale_file_count:h.number().int().min(0),unindexed_file_count:h.number().int().min(0).optional(),truncated:h.boolean(),hunk_coverage:h.enum(["full","partial","none"]),detector_coverage:Xm}),rR=h.object({changed_symbols:h.array(rh).max(Pt),risk_flags:h.array(h.string().max(64)).max(16),detector_findings:h.array(Zm).max(64),detector_runs:h.array(nh).min(1).max(32),diff_stats:ih,commit_sha:Dc.optional(),base_sha:Dc.optional(),merge_base_sha:Dc.optional(),dirty:h.boolean().optional(),code_index_version:h.string().min(1).max(32).optional()})});var sh,ah,ch,lh,dh,Pc,iR,oR,uh,ph,fh,mh,hh,sR,aR,gh,yh,_h,cR,bh=v(()=>{"use strict";fe();sh=14,ah=14,ch=14,lh=1,dh=365,Pc=h.number().int().min(lh).max(dh),iR=["propose","direct"],oR="propose",uh=["propose","direct"],ph="propose",fh=["propose","direct"],mh="propose",hh=["off","propose","direct"],sR=["member","admin","owner"],aR="member",gh="off",yh="en",_h=h.object({version:h.literal(1).default(1),at_risk_days:Pc.default(sh),stagnation_days:Pc.default(ah),agent_date_mode:h.enum(iR).default(oR),health_manual_ttl_days:Pc.default(ch),agent_event_mode:h.enum(uh).default(ph),agent_update_mode:h.enum(fh).default(mh),agent_pull_mode:h.enum(hh).default(gh),org_wide_authoring_min_role:h.enum(sR).default(aR),planning_language:h.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(yh)}),cR=_h.parse({})});var vh,lR,wh=v(()=>{"use strict";fe();vh=h.object({version:h.literal(1).default(1),org_visibility:h.boolean().default(!1),session_span_visibility:h.boolean().default(!0)}),lR=vh.parse({})});var kh,xh,dR,uR,Sh=v(()=>{"use strict";fe();kh=h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),xh=h.object({id:h.string().uuid(),user_id:h.string().uuid(),project:h.string().max(200).nullable().optional(),title:h.string().min(1).max(200),body:h.string().min(1).max(2e4),context:kh.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:h.string(),updated_at:h.string(),last_recalled_at:h.string().nullable().optional(),recall_count:h.number().int().nonnegative().default(0),graduated_draft_id:h.string().uuid().nullable().optional(),deleted_at:h.string().nullable().optional()}),dR=xh.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:h.number()}),uR=h.object({id:h.string().uuid(),title:h.string(),summary:h.string(),tags:h.array(h.string()).default([])})});var Eh=v(()=>{"use strict"});function zo(e){let t=[],n=null;return e.split(`
3
+ `).forEach((r,i)=>{let o=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(o===""||a>n)return;n=null}if(o===""||o.startsWith("#"))return;let c=fR.exec(r);if(!c)return;let l=c[3]??"";if(pR.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 pR,fR,Th=v(()=>{"use strict";pR=new Set(["|",">","|-",">-","|+",">+"]),fR=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(zo,"plainScalarViolations")});function fi(e,t){let n=s(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),[o,a]=n(t);for(let c=0;c<Math.max(r.length,o.length);c+=1){let l=(r[c]??0)-(o[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 Rh=v(()=>{"use strict";s(fi,"compareSemver")});var mi=v(()=>{"use strict";Dt();rm();Dt();Dt();am();cm();lm();hm();bm();Rm();Dt();Nc();Um();oh();bh();wh();Sh();Eh();Oc();Th();Rh()});function Ch(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
+ `).slice(0,1e3)}var Ah=v(()=>{"use strict";s(Ch,"nodeEmbedText")});var Mc,$c=v(()=>{"use strict";Mc=["function","method","class","interface","enum","type_alias"]});function Ih(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var Nh=v(()=>{"use strict";s(Ih,"cosineSimilarity")});import{execFileSync as mR}from"node:child_process";import{createHash as hR}from"node:crypto";import{readFileSync as gR}from"node:fs";import{posix as je}from"node:path";function Oh(e){let t=hR("sha256"),n=[];try{n=mR("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
+ `).filter(l=>yR.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,i=s(l=>{if(r.has(l))return r.get(l);try{let d=gR(je.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),o=[],a=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=Dh(l,i,0),u=je.dirname(l)==="."?"":je.dirname(l);l.endsWith("tsconfig.json")&&a.set(u,d),d.paths&&o.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=Ph(i(l));if(!d||typeof d.name!="string")continue;let u=je.dirname(l)==="."?"":je.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:o},fingerprint:t.digest("hex")}}function Dh(e,t,n){let r=Ph(t(e));if(!r)return{};let i=je.dirname(e)==="."?"":je.dirname(e),o={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=je.normalize(je.join(i,a.endsWith(".json")?a:a+".json"));o=Dh(d,t,n+1)}let c=r.compilerOptions??{},l={...o};return typeof c.outDir=="string"&&(l.outDir=je.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=je.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 Ph(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(GT(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function GT(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 BT,_h=_(()=>{"use strict";BT=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;o(hh,"loadModuleConfig");o(gh,"compilerFacts");o(yh,"parseJsonc");o(GT,"dropTrailingCommas")});import{posix as Le}from"node:path";function oi(e,t){let n=Le.normalize(e).replace(/^\.\//,""),r=[],i=Ds.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 Ds)r.push(c+l)}if(!i&&!s){for(let c of Ds)r.push(n+c);for(let c of Ds)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function wh(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=wh(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 ai(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=ai(n[i]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?ai(e):null}function ai(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=ai(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of KT)if(n in t){let r=ai(t[n]);if(r)return r}}return null}function WT(e,t){let n=Le.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=Le.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=Le.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(Le.join(s,n.slice(i.length+1)))}return r}var Ds,KT,wc,bh,or,vc=_(()=>{"use strict";Ds=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],KT=["import","default","node","require","types"],wc={kind:"unresolved"},bh={kind:"external"};o(oi,"resolvePathCandidates");or=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=`${Le.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=oi(Le.join(Le.dirname(t),n),this.files);return s?{kind:"file",path:s}:wc}if(n.startsWith("node:"))return bh;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}:wc}return bh}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(s=>s.dir===""||t.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=Le.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=oi(Le.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return wc}}return null}viaPackage(t,n){let r=[],i=wh(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 WT(t,s)){let c=oi(Le.join(t.dir,a),this.files);if(c)return c}return null}};o(wh,"exportTarget");o(ai,"conditionTarget");o(WT,"toSource")});function qe(e){return`${e}#<module>`}function Je(e,t,n){return`${e}#${t}:${n}`}var mn=_(()=>{"use strict";o(qe,"moduleKey");o(Je,"symbolKey")});import{posix as vh}from"node:path";function Sh(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),VT.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Je(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 xh(e,t,n=new or({packages:[],tsconfigs:[]},t.files)){let r=YT(),i=new kc(e,t,n);for(let s of e)s.language==="python"?XT(s.filePath,s.refs,s.imports,t,r.push):i.resolveFile(s,r.push);return r.edges}function JT(e,t,n){return t.startsWith(".")?oi(vh.join(vh.dirname(e),t),n):null}function YT(){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 XT(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=JT(e,s.specifier,r.files);a&&i(s.fromModuleKey,qe(a),"imports")}}function ZT(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return Je(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var VT,kh,zT,qT,kc,Eh=_(()=>{"use strict";mn();vc();VT=new Set(["function","method","class","interface","enum","type_alias"]),kh=["function","class","variable","enum","interface","type_alias"],zT=8,qT=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(Sh,"buildResolutionIndex");o(xh,"resolveCrossFileEdges");o(JT,"resolveImportTarget");o(YT,"edgeCollector");o(XT,"legacyFacts");o(ZT,"classKeyOfMethod");kc=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(qT.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=ZT(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=Je(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=Je(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=Je(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>zT)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=kh.indexOf(s.slice(s.lastIndexOf(":")+1));return a<0?kh.length:a},"rank");return{kind:"symbol",key:[...r].sort((s,a)=>i(s)-i(a))[0]}}}});function ar(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 ci(e){return e.toLowerCase().endsWith(".d.ts")}var Ps=_(()=>{"use strict";o(ar,"languageForPath");o(ci,"isSkippablePath")});import{appendFileSync as QT,existsSync as Th,mkdirSync as eR,readFileSync as tR}from"node:fs";import{join as nR}from"node:path";function li(e,t={}){try{if(!Th(e)){if(!t.create)return"skipped";eR(e,{recursive:!0})}let n=nR(e,".gitignore"),r=Th(n)?tR(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=Ms.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let a=r===null?[...rR,...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(_R(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function _R(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 o=r+1;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e[o]==="}"||e[o]==="]")continue}t+=i}return t}var yR,Mh=v(()=>{"use strict";yR=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(Oh,"loadModuleConfig");s(Dh,"compilerFacts");s(Ph,"parseJsonc");s(_R,"dropTrailingCommas")});import{posix as He}from"node:path";function hi(e,t){let n=He.normalize(e).replace(/^\.\//,""),r=[],i=qo.some(c=>n.endsWith(c));i&&r.push(n);let o=/\.d\.(m|c)?ts$/.exec(n);o&&r.push(n.slice(0,-o[0].length)+".ts",n.slice(0,-o[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 qo)r.push(c+l)}if(!i&&!o){for(let c of qo)r.push(n+c);for(let c of qo)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function Lh(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 o=Lh(i,t);if(o)return o}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 gi(n[t]);for(let i of r){let o=i.indexOf("*");if(o<0)continue;let a=i.slice(0,o),c=i.slice(o+1);if(t.startsWith(a)&&t.endsWith(c)){let l=gi(n[i]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?gi(e):null}function gi(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=gi(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of bR)if(n in t){let r=gi(t[n]);if(r)return r}}return null}function vR(e,t){let n=He.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=He.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),o=He.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(He.join(o,n.slice(i.length+1)))}return r}var qo,bR,Lc,$h,gr,Fc=v(()=>{"use strict";qo=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],bR=["import","default","node","require","types"],Lc={kind:"unresolved"},$h={kind:"external"};s(hi,"resolvePathCandidates");gr=class{static{s(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=`${He.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 o=hi(He.join(He.dirname(t),n),this.files);return o?{kind:"file",path:o}:Lc}if(n.startsWith("node:"))return $h;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(o=>n===o.name||n.startsWith(o.name+"/"));if(i){let o=n===i.name?".":"./"+n.slice(i.name.length+1),a=this.viaPackage(i,o);return a?{kind:"file",path:a}:Lc}return $h}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(o=>o.dir===""||t.startsWith(o.dir+"/"));if(!r?.paths)return null;let i=He.join(r.dir,r.baseUrl??".");for(let[o,a]of Object.entries(r.paths)){let c=o.indexOf("*"),l=null;if(c<0)o===n&&(l="");else{let d=o.slice(0,c),u=o.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=hi(He.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return Lc}}return null}viaPackage(t,n){let r=[],i=Lh(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let o of[t.module,t.main,t.types])o&&r.push(o);r.push("index")}else r.push(n);for(let o of r)for(let a of vR(t,o)){let c=hi(He.join(t.dir,a),this.files);if(c)return c}return null}};s(Lh,"exportTarget");s(gi,"conditionTarget");s(vR,"toSource")});function Qe(e){return`${e}#<module>`}function et(e,t,n){return`${e}#${t}:${n}`}var vn=v(()=>{"use strict";s(Qe,"moduleKey");s(et,"symbolKey")});import{posix as Fh}from"node:path";function Hh(e){let t=new Map,n=new Set,r=new Map,i=new Map,o=new Set,a=s((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),o.add(c.nodeKey),wR.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===et(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:o}}function Uh(e,t,n=new gr({packages:[],tsconfigs:[]},t.files)){let r=ER(),i=new jc(e,t,n);for(let o of e)o.language==="python"?TR(o.filePath,o.refs,o.imports,t,r.push):i.resolveFile(o,r.push);return r.edges}function SR(e,t,n){return t.startsWith(".")?hi(Fh.join(Fh.dirname(e),t),n):null}function ER(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let o=`${n} ${r} ${i}`;e.has(o)||(e.add(o),t.push({srcKey:n,dstKey:r,kind:i}))}}}function TR(e,t,n,r,i){for(let o of t){let a=r.nameToKeys.get(o.targetName);!a||a.length!==1||i(o.fromKey,a[0],o.kind)}for(let o of n){let a=SR(e,o.specifier,r.files);a&&i(o.fromModuleKey,Qe(a),"imports")}}function RR(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return et(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var wR,jh,kR,xR,jc,Bh=v(()=>{"use strict";vn();Fc();wR=new Set(["function","method","class","interface","enum","type_alias"]),jh=["function","class","variable","enum","interface","type_alias"],kR=8,xR=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"]);s(Hh,"buildResolutionIndex");s(Uh,"resolveCrossFileEdges");s(SR,"resolveImportTarget");s(ER,"edgeCollector");s(TR,"legacyFacts");s(RR,"classKeyOfMethod");jc=class{static{s(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 o=new Map;for(let a of i.imports)a.localName&&a.importedName&&o.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(i.filePath,o);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(xR.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),o=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=RR(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 o.length===1?o[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),o;if(i<0)o=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);o=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(o?.kind!=="symbol")return null;let a=o.key.endsWith(":class")?[o.key]:[...this.implementers(o.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=et(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let o of this.supertypes(t)){if(!o.endsWith(":class"))continue;let a=o.indexOf("#"),c=et(o.slice(0,a),`${o.slice(a+1,o.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 o=this.resolveRef(r,i);if(o){n.add(o);for(let a of this.supertypes(o))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let o=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=et(o,`${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>kR)return null;this.memo.set(i,null);let o=this.computeExport(t,n,r);return this.memo.set(i,o),o}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 o=this.topLevel(t,n);if(o)return o;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=s(o=>{let a=jh.indexOf(o.slice(o.lastIndexOf(":")+1));return a<0?jh.length:a},"rank");return{kind:"symbol",key:[...r].sort((o,a)=>i(o)-i(a))[0]}}}});function yr(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 yi(e){return e.toLowerCase().endsWith(".d.ts")}var Jo=v(()=>{"use strict";s(yr,"languageForPath");s(yi,"isSkippablePath")});import{appendFileSync as CR,existsSync as Gh,mkdirSync as AR,readFileSync as IR}from"node:fs";import{join as NR}from"node:path";function _i(e,t={}){try{if(!Gh(e)){if(!t.create)return"skipped";AR(e,{recursive:!0})}let n=NR(e,".gitignore"),r=Gh(n)?IR(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),o=Yo.filter(l=>!i.has(l));if(o.length===0)return"unchanged";let a=r===null?[...OR,...o]:o,c=r&&!r.endsWith(`
8
8
  `)?`
9
- `:"";return QT(n,c+a.join(`
9
+ `:"";return CR(n,c+a.join(`
10
10
  `)+`
11
- `),r===null?"created":"appended"}catch{return"skipped"}}var Ms,Sc,rR,$s=_(()=>{"use strict";Ms=["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"],Sc=["# 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).'],rR=Sc;o(li,"ensureMaindLocalIgnore")});import{execFileSync as iR}from"node:child_process";import{createHash as sR}from"node:crypto";import{readFileSync as oR,readdirSync as aR,statSync as cR}from"node:fs";import{posix as Ec,sep as Rh}from"node:path";function C(e,t){try{return iR("git",[...lR,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function dR(e){return Rh==="/"?e:e.split(Rh).join("/")}function Ls(e){let t=[];for(let n of e){let r=dR(n).trim();if(!r||ci(r))continue;let i=ar(r);i&&t.push({path:r,language:i})}return t}function Ch(e){return Ls(e)}function Ih(e){let t=Tt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Ls(t.split(`
12
- `));let n=[];return Nh(e,"",n),Ls(n)}function Nh(e,t,n){let r;try{r=aR(Ec.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Ah.has(i.name)||Ah.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?Nh(e,s,n):i.isFile()&&n.push(s)}}function Tc(e,t){return Rc(e,t)??t}function Rc(e,t){let n=C(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Fs(e,t={}){if(di(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Tc(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=Tt(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=xc((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=Tt(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=xc(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 xc(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Ac(e,t={}){let n=Fs(e,t);return n===null?null:Ls(n.keys())}function Oh(e,t){try{let n=cR(Ec.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function js(e){return sR("sha256").update(e).digest("hex")}function di(e){return Tt(e,["rev-parse","HEAD"])?.trim()??null}function Us(e,t){return Tt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function Cc(e){let t=Tt(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=uR(e);return n.some(i=>r===null||!fR(e,i,r))}function uR(e){let t=Tt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function fR(e,t,n){let r=t[0],i=t[1];if(xc(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=Tt(e,["show",`HEAD:${n}`]);if(f===null)return!1;s=f}else return!1;let a;try{a=oR(Ec.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([...Ms,...Sc]);return d.slice(l.length).split(`
17
- `).map(f=>f.trim()).every(f=>f.length===0||u.has(f))}var Ah,lR,Tt,fe=_(()=>{"use strict";Ps();$s();Ah=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),lR=["-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");Tt=C;o(dR,"toPosix");o(Ls,"classify");o(Ch,"classifyPaths");o(Ih,"discoverSourceFiles");o(Nh,"walk");o(Tc,"resolveDiffBase");o(Rc,"resolveMergeBase");o(Fs,"enumerateChangedPaths");o(xc,"unquote");o(Ac,"changedSourceFiles");o(Oh,"statFile");o(js,"hashContent");o(di,"headCommit");o(Us,"resolveCommitSha");o(Cc,"isWorktreeDirty");o(uR,"toolIgnoreRepoPath");o(fR,"isToolOnlyIgnoreChange")});function Ph(e,t={}){if(C(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Tc(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")>pR?c="none":yR(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 yR(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=gR.exec(l);if(d){if(i++,i>mR){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<hR&&r.addedLines.push(l.slice(1))}c()}var pR,mR,hR,Dh,gR,Mh=_(()=>{"use strict";fe();pR=16*1024*1024,mR=500,hR=4e3,Dh=256*1024,gR=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;o(Ph,"changedHunks");o(yR,"parseUnifiedDiff")});function Nc(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>=Uh&&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 wR(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(_R).filter(t=>t.trim().length>0)}function Fh(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(bR);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function vR(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 Hh(e,t,n={}){let r=wR(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,jh),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,Ic),l=[];for(let u of c){let f=C(e,["log","-n",String(s),$h,"--",u]),p=f===null?[]:Lh(f).map(Fh).filter(h=>h!==null);l.push({path:u,lastCommits:p.slice(0,r),ownership:i?{topAuthors:vR(p),commitsInWindow:p.length}:null})}let d=null;if(n.since){let u=Us(e,n.since),f=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],p=C(e,["log",...f,"-n",String(Hs+1),$h,"--name-only","--",...c]),h=[];if(p!==null)for(let g of Lh(p)){let y=g.split(`
20
- `),w=Fh(y[0]??"");if(!w)continue;let v=y.slice(1).filter(k=>k.trim().length>0).length;h.push({sha:w.sha,dateIso:w.dateIso,authorName:w.authorName,subject:w.subject,filesTouched:v})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,Hs),truncated:h.length>Hs}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:a.length>Ic}}var _R,bR,jh,Ic,Hs,$h,Uh,Oc=_(()=>{"use strict";fe();_R="",bR="\0",jh=200,Ic=50,Hs=100,$h="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",Uh=10;o(Nc,"aggregateHistoryContext");o(wR,"clamp");o(Lh,"splitRecords");o(Fh,"parseHistoryRecord");o(vR,"aggregateOwnership");o(Hh,"readFileHistory")});import{execFileSync as kR}from"node:child_process";import{readdirSync as SR,statSync as Bh}from"node:fs";import{isAbsolute as xR,join as Dc,relative as ER,resolve as TR}from"node:path";function AR(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function CR(e,t){try{let n=kR("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 IR(e){let t;try{t=SR(e)}catch{return null}for(let n of t.filter(AR))try{let r=Bh(Dc(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function NR(e){try{return Bh(e).isDirectory()}catch{return!1}}function OR(e,t){let n=ER(e,t);return!n||n.startsWith("..")?t:n}function Pc(e){let t=RR.filter(c=>NR(Dc(e,c))),n=CR(e,"core.hooksPath"),r=n?xR(n)?n:TR(e,n):Dc(e,".git","hooks"),i=OR(e,r),s=IR(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 Mc(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 RR,$c=_(()=>{"use strict";RR=[".githooks",".husky"];o(AR,"isRealHook");o(CR,"gitConfig");o(IR,"hasExecutableHook");o(NR,"isDir");o(OR,"displayPath");o(Pc,"resolveHookState");o(Mc,"describeHookState")});import{posix as Gh}from"node:path";function cr(e){let t=DR.exec(e);return t?t[1]:null}function at(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function hn(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=Gh.basename(s),c=cr(a);if(c===null)continue;let l=Gh.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)=>at(c.version,l.version))})).sort((s,a)=>s.dir.localeCompare(a.dir))}function ui(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 DR,fi=_(()=>{"use strict";fe();DR=/^(\d+)_.+\.sql$/;o(cr,"parseMigrationVersion");o(at,"compareVersions");o(hn,"discoverSupabaseProjects");o(ui,"resolveDefaultBranch")});import{execFileSync as PR}from"node:child_process";import{existsSync as ue,readFileSync as Rt,readdirSync as Bs,statSync as Fc}from"node:fs";import{posix as U}from"node:path";function FR(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(ue(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&&Uc(n,s))){let c=jR(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=U.dirname(r)}return null}function jR(e,t){let n=[];for(let r of $R){let i;try{i=Bs(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=Fc(c),u=Fc(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>LR)continue;Rt(c).equals(Rt(l))||n.push(a)}catch{continue}}}return n.sort()}function Yh(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 ${Hc}.`})}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=UR(e.hooks);return a&&t.push(a),HR(t)}function UR(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:Mc(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 HR(e){return[...e].sort((t,n)=>Kh[t.status]-Kh[n.status]||t.id.localeCompare(n.id))}function Xh(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function ct(e){let t=e?.trim();return t||null}function BR(e){let t=ct(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 GR(e){let t=ct(C(e,["rev-parse","--git-dir"]));if(!t)return null;let n=U.isAbsolute(t)?t:U.join(e,t);return ue(U.join(n,"rebase-merge"))||ue(U.join(n,"rebase-apply"))?"rebase":ue(U.join(n,"MERGE_HEAD"))?"merge":ue(U.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function KR(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 WR(e){let t=U.join(e,Hc);if(!ue(t))return[];try{return Rt(t,"utf8").split(`
22
- `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function VR(e){try{return hn(e).map(t=>U.join(U.dirname(t.dir),"config.toml"))}catch{return[]}}function zR(e){let t=C(e,["ls-files","-z","--",...MR]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=Jh[U.basename(r)];if(i===void 0)continue;let s=U.dirname(r);if(!qR(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 qR(e,t){return t==="."?!0:jc(e,t)}function jc(e,t){if(ue(U.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Rt(U.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Zh(e,t={}){if(ct(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=ct(C(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,a=BR(e),c=ct(C(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let M=ct(C(e,["rev-parse","HEAD"])),B=ct(C(e,["rev-parse","@{u}"]));l=M!=null&&B!=null?M===B:null,d=C(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,f=null;if(a){let M=ct(C(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(M){let[B,P]=M.split(/\s+/).map(F=>Number.parseInt(F,10));Number.isFinite(B)&&(f=B),Number.isFinite(P)&&(u=P)}}let h=(C(e,["status","--porcelain"])??"").split(`
23
- `).filter(M=>M.trim().length>0).length,g=GR(e),y=ct(C(e,["rev-parse","--show-toplevel"]))??e,w=KR(C(e,["worktree","list","--porcelain"])??""),v=w[0]?.path??null,k=v!=null&&Uc(v,y),x=Math.max(0,w.length-1),T=null;if(v&&!Uc(v,y)){let M=o(P=>ue(U.join(v,P))&&!ue(U.join(y,P)),"here"),B=[...qh,...VR(y),...WR(y),...t.probePaths??[]];T={mainWorktreePath:v,currentWorktreePath:y,missing:[...new Set(B.filter(M))],missingDeps:zR(y).filter(P=>M(P.dir))}}let b=FR(y,e),S=t.includeRelease===!1?null:tA(e,s),N=[];return a&&(N=(C(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
24
- `).map(B=>B.trim()).filter(B=>B.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:x,worktreeParity:T,toolCopyDrift:b,stalePackageBuilds:Qh(y),release:S,unmergedMigrations:N,hooks:Pc(e)}}function Uc(e,t){let n=o(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function XR(e){let t=new Set;jc(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Vh;){let i=n.pop();if(i===void 0)break;if(i.depth>=YR)continue;let s;try{s=Bs(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>=Vh)break;jc(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function ZR(e){let t=[];try{let n=U.join(e,"pnpm-workspace.yaml");if(ue(n)){let r=!1;for(let i of Rt(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(ue(r)){let i=JSON.parse(Rt(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 QR(e){let t=[];for(let n of XR(e)){let r=n==="."?e:U.join(e,n),i=o(s=>n==="."?s:U.join(n,s),"prefix");for(let s of ZR(r)){if(t.length>=Lc)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let a=s.slice(0,-2),c=U.join(r,a);if(!ue(c))continue;for(let l of Bs(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(U.join(a,l.name))),t.length>=Lc)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,Lc)}function zh(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Wh;){let i=r.pop();if(i===void 0)break;let s;try{s=Bs(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=Fc(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Wh)break}}}return t}function eA(e,t){let n=new Set;for(let r of t)try{let i=U.join(e,r,"package.json");if(!ue(i))continue;let s=JSON.parse(Rt(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 Qh(e){let t=[],n=QR(e),r=eA(e,n);for(let i of n)try{let s=U.join(e,i,"package.json");if(!ue(s))continue;let a=JSON.parse(Rt(s,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=o(v=>{if(typeof v!="string")return null;let k=v.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(!ue(p)||!ue(h))continue;let g=zh(p),y=zh(h);if(g===null||y===null)continue;let w=g-y;w>JR&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(w),impact:f})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function tA(e,t){if(!t)return null;let n=nA(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 nA(e,t){try{return PR("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function pi(e,t={}){let n=await Zh(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Yh(n),i=Xh(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var qh,Hc,Jh,MR,$R,LR,Kh,JR,Lc,Wh,YR,Vh,Bc=_(()=>{"use strict";$c();fe();fi();qh=["supabase/config.toml","supabase/.temp",".env"],Hc=".maind/worktree-requirements",Jh={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},MR=Object.keys(Jh).flatMap(e=>[e,"*/"+e]),$R=["scripts"],LR=512*1024;o(FR,"gatherToolCopyDrift");o(jR,"compareToolDirs");o(Yh,"computeDivergence");o(UR,"computeHookFinding");Kh={open:0,warn:1,info:2,passed:3};o(HR,"sortFindings");o(Xh,"isHealthy");o(ct,"trimOrNull");o(BR,"resolveDefaultBranch");o(GR,"detectInProgressOp");o(KR,"parseWorktrees");o(WR,"readWorktreeRequirements");o(VR,"discoverSupabaseConfigProbes");o(zR,"discoverDependencyDirs");o(qR,"isWorkspaceRoot");o(jc,"hasWorkspaceMarkers");o(Zh,"gatherRepoHealthFacts");o(Uc,"samePath");JR=2e3,Lc=64,Wh=4e3,YR=3,Vh=400;o(XR,"findWorkspaceRoots");o(ZR,"workspacePatternsAt");o(QR,"listWorkspacePackageDirs");o(zh,"newestMtimeUnder");o(eA,"consumedWorkspaceNames");o(Qh,"gatherStalePackageBuilds");o(tA,"gatherReleaseFact");o(nA,"runGh");o(pi,"checkDivergence")});import{existsSync as Gc,readdirSync as eg}from"node:fs";import{posix as Ye}from"node:path";function Wc(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Kc)}function ng(e,t={}){let n=t.minFiles??Vc;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??tg)}function dr(e){return`${e.dir}#${e.prefix}`}function mi(e){let t=rA.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function rg(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=dr(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}${zc(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 ig(e){return!e.some(t=>t.status==="open")}function zc(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 qc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function sg(e,t){let n=qc(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=mi(Ye.basename(n));if(!i)return r;let s=`${Ye.dirname(n)}#${i.prefix}`,a=e.namespaces.find(u=>dr(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:zc(c.keys(),i.number)}}function Gs(e){let t=e?.trim();return t||null}function lr(e){return e?e.split(`
26
- `).filter(Boolean):[]}function iA(e){let t=Gs(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 og(e,t={}){let n=t.minFiles??Vc,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=Ye.dirname(a),l=mi(Ye.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=>ng(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)=>dr(a).localeCompare(dr(c)))}async function Jc(e,t={}){let n=[];if(Gs(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=og(e,t),s=new Map(i.map(h=>[dr(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=o((h,g,y)=>{let w=Ye.dirname(h),v=mi(Ye.basename(h));if(!v)return;let k=`${w}#${v.prefix}`;if(!s.has(k))return;let x=c.get(k)??new Map,T=x.get(v.number)??[];T.push({kind:g,where:y,path:h}),x.set(v.number,T),c.set(k,x)},"record"),d=o((h,g,y)=>{if(a.length===0)return;let w=C(e,["ls-tree","-r","--name-only",h,"--",...a]);if(w===null){n.push(`could not read ${y}`);return}for(let v of lr(w))l(v,g,y)},"scanTree");for(let h of a){let g=Ye.join(e,h);if(Gc(g))try{for(let y of eg(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let u=iA(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=Gs(C(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of lr(C(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==h&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let h=Gs(C(e,["rev-parse","--show-toplevel"]));for(let g of lr(C(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!Gc(y)))for(let w of a){let v=Ye.join(y,w);if(Gc(v))try{for(let k of eg(v))l(`${w}/${k}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${w} 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(Kc):p=lr(h);let g=C(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(p=[...p,...lr(g)]);let y=C(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(p=[...p,...lr(y)])}return{isRepo:!0,defaultBranch:u,baseRef:f,namespaces:i,sightingsByNamespace:c,addedPaths:p,skipped:n}}async function gn(e,t={}){let n=await Jc(e,t),r=rg(n);return{ok:ig(r),findings:r,facts:n}}async function yn(e,t,n={}){let r=qc(t);if(!mi(Ye.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Jc(e,{...n,dirs:n.dirs??[Ye.dirname(r)]});return sg(i,r)}var Kc,rA,Vc,tg,hi=_(()=>{"use strict";fe();Kc="could not diff against the base ref \u2014 everything reported as info";o(Wc,"isNumberCollisionsGraded");rA=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Vc=3,tg=.8;o(ng,"isCounterNamespace");o(dr,"namespaceKey");o(mi,"parseNumbered");o(rg,"computeNumberCollisions");o(ig,"isCollisionFree");o(zc,"suggestNextNumber");o(qc,"normaliseRepoPath");o(sg,"checkProposedNumber");o(Gs,"trimOrNull");o(lr,"lines");o(iA,"resolveDefaultBranch");o(og,"detectNamespaces");o(Jc,"gatherNumberCollisionFacts");o(gn,"checkNumberCollisions");o(yn,"checkNumberForPath")});import{execFileSync as sA}from"node:child_process";import{createHash as oA}from"node:crypto";function Yc(e){return oA("sha256").update(e).digest("hex")}function aA(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 cA(e){let t=aA(e);return t?Yc(t):null}function dA(e){return typeof e=="string"&&lA.test(e)}function ag(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(dA(t))return t;let n;try{n=sA("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?cA(n):null}var lA,Xc=_(()=>{"use strict";o(Yc,"sha256Hex");o(aA,"normalizeRemoteUrl");o(cA,"projectKeyFromRemote");lA=/^[a-f0-9]{64}$/;o(dA,"isProjectKey");o(ag,"computeProjectKey")});function tl(e){return`spec.${e}`}function ur(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 uA(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 cg(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(uA)}function yi(e){return Yc(JSON.stringify(cg(e)))}var gi,Zc,Qc,el,nl=_(()=>{"use strict";Xc();gi={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"]}},Zc="number.collision",Qc="theme.dead_class",el="acl.missing_revoke";o(tl,"specDriftRuleId");o(ur,"gradeEngineStatus");o(uA,"codePointCompare");o(cg,"normalizeEvidenceForHash");o(yi,"hashDetectorEvidence")});import{existsSync as fA,readFileSync as lg}from"node:fs";import{posix as pA}from"node:path";function Vs(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 zs(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 _i(e){return e==='"'||e==="'"||e==="`"}function qs(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Ks(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(_i(s)){i=Vs(e,i);continue}if(qs(e,i)){i=zs(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function mA(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(qs(e,t)){t=zs(e,t);continue}break}return e.slice(t)}function fr(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(_i(s)){i=Vs(e,i);continue}if(qs(e,i)){i=zs(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=>mA(s).trim()).filter(s=>s.length>0)}function pg(e){let t=Vs(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
28
- `:i==="r"?"\r":i==="t"?" ":i)}function hA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function il(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${hA(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(_i(a)){i=Vs(e,i);continue}if(qs(e,i)){i=zs(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 Ks(e,i);if(a===";")return null;i++}return null}function sl(e){let t={};if(!e.startsWith("{"))return t;for(let n of fr(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();_i(s[0]??"")&&(t[i]=pg(s))}return t}function gA(e,t){if(!e.startsWith("{"))return null;for(let n of fr(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 mg(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function hg(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function gg(e,t){let n=il(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=hg(),i=[],s=0;for(let a of fr(n.slice(1,-1))){if(!a.startsWith("{")){s++;continue}let c=sl(a),l=c[t.key_field];if(!l){s++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:mg(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 yg(e,t){let n=il(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=hg(),i=[],s=0,a=o((c,l,d)=>{let u=t.levels[l],f=l===t.levels.length-1;for(let p of fr(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!p.startsWith("{")){s++;continue}let y=sl(p);for(let[w,v]of Object.entries(u.fields??{}))h[w]=y[String(v)]??"";if(!f&&typeof u.children=="string"){let w=gA(p,u.children);g=w&&w.startsWith("[")?Ks(w,0):null}}else{if(!p.startsWith("[")){s++;continue}let y=fr(p.slice(1,-1));for(let[w,v]of Object.entries(u.fields??{})){let k=y[Number(v)];h[w]=k!==void 0&&_i(k[0]??"")?pg(k):""}if(!f&&typeof u.children=="number"){let w=y[u.children];g=w!==void 0&&w.startsWith("[")?Ks(w,0):null}}if(f){let y=h[t.key_field];if(!y){s++;continue}let w=(t.partition_by??[]).map(v=>h[v]??"");i.push({key:y,fields:mg(h,t.fields),orderPath:w,ordinal:r(w)});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 dg(e,t){return t.extractor==="object-array"?gg(e,t):yg(e,t)}function _g(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 bg(e,t,n){return`spec.drift:${e}#${t}:${n}`}function yA(e){return e.orderPath.join(" / ")||"(flat)"}function wg(e,t,n,r){let i=[],s=o((d,u,f,p,h,g)=>{i.push({id:bg(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 ${yA(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(_g(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 _A(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 ug(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 vg(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 x=g==null?h.spec.path:h.impl.path;f.push(ug(h.id,`Declared file could not be read: ${x}`)),p.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=dg(g,h.spec),v=dg(y,h.impl);if(w.error||v.error){f.push(ug(h.id,w.error??v.error??"unknown")),p.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=w.dropped>0||v.dropped>0;p.push({id:h.id,measured:!0,specRecords:w.records.length,implRecords:v.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:`${w.dropped} specification and ${v.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(...wg(h,w.records,v.records,e.files)),f.push(..._A(h,{spec:w.records.length,impl:v.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(bg(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)=>fg[u.status]-fg[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 rl(e){let t=e?.trim();return t||null}function Js(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 bA(e){let t=rl(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 wA(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 kg(e,t={}){let n=o((g,y)=>pA.join(g,y),"join"),r=t.manifestPath??Ws,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(rl(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let a=n(e,r);if(!fA(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}=Js(lg(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 wA(c))try{d.set(g,lg(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:bA(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=rl(C(e,["merge-base",y,"HEAD"])),!p)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let w of d.keys())h.set(w,C(e,["show",`${p}:${w}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:p,files:u,skipped:i}}async function _n(e,t={}){let n=await kg(e,t);return{...vg(n,t),facts:n}}function ol(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Ws,fg,bi=_(()=>{"use strict";fe();Ws=".maind/spec-contracts.json";o(Vs,"endOfString");o(zs,"skipComment");o(_i,"isQuote");o(qs,"isCommentStart");o(Ks,"sliceBalanced");o(mA,"stripLeadingTrivia");o(fr,"splitTopLevel");o(pg,"readStringLiteral");o(hA,"escapeRe");o(il,"findSymbolArray");o(sl,"parseObjectFields");o(gA,"objectFieldRaw");o(mg,"pickFields");o(hg,"makeOrdinals");o(gg,"extractObjectArray");o(yg,"extractNestedList");o(dg,"extractRecords");o(_g,"isGrounded");o(bg,"findingId");o(yA,"partitionOf");o(wg,"compareContract");o(_A,"checkAssertions");o(ug,"unreadable");fg={open:0,warn:1,info:2,passed:3};o(vg,"computeSpecDrift");o(rl,"trimOrNull");o(Js,"parseManifest");o(bA,"resolveDefaultBranch");o(wA,"declaredPaths");o(kg,"gatherSpecDriftFacts");o(_n,"checkSpecDrift");o(ol,"isSpecDriftGraded")});import{execFileSync as vA}from"node:child_process";import{existsSync as kA,readFileSync as SA}from"node:fs";import{join as xA}from"node:path";function wi(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":EA.test(i)?"never-published":"released"})}return t}function xg(e){let t=new Map;for(let n of wi(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 Eg(e,t){let n=xg(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of wi(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 Tg(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=Eg(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 Sg(e,t){try{return vA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function TA(e,t={}){let n=Sg(["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=xA(e,a);return{path:a,head:kA(c)?SA(c,"utf8"):null,base:i===null?null:Sg(["show",`${i}:${a}`],e)}});return{isRepo:!0,baseRef:i,files:s}}function al(e,t={}){return Tg(TA(e,t))}var EA,Ys=_(()=>{"use strict";EA=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;o(wi,"parseVersionHeadings");o(xg,"findDuplicateHeadings");o(Eg,"classifyIntroduced");o(Tg,"computeChangelogDuplicates");o(Sg,"git");o(TA,"gatherChangelogFacts");o(al,"checkChangelogDuplicates")});import{execFileSync as RA}from"node:child_process";import{existsSync as AA,readFileSync as Rg}from"node:fs";import{dirname as Ag,join as Cg}from"node:path";function Ng(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(ii);for(let a of s){if(r.has(a)||ii(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(ii))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 Ig(e){let t=wi(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 cl(e,t){try{return RA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function Og(e,t=null){let n=cl(["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(Rg(Cg(e,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let a=Ag(i)==="."?"":Ag(i),c=Cg(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=AA(c)?Ig(Rg(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,f=t===null?null:cl(["show",`${t}:${u}`],e),p=t===null?null:f===null?[]:Ig(f).documented;r.push({dir:a,name:s.name,version:s.version,documented:l,documentedBase:p,neverPublished:d})}return r}async function CA(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 Dg(e,t={}){if(cl(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=Og(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??CA,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 ll(e,t={}){return Ng(await Dg(e,t))}var dl=_(()=>{"use strict";si();Ys();o(Ng,"computeReleaseClaims");o(Ig,"claimsOf");o(cl,"git");o(Og,"discoverPackages");o(CA,"packument");o(Dg,"gatherReleaseClaimsFacts");o(ll,"checkReleaseClaims")});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 fl(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===$g){n=!0;continue}t.push(r)}return t.join(`
33
- `)}function Pg(e){return e.split(`
34
- `).map(t=>t.trim()).filter(t=>t.length>0)}function Fg(e,t){let n=new Map;for(let s of Pg(t??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of Pg(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 jg(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=Fg(fl(n.head),n.base===null?null:fl(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 ul(e,t){try{return IA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function Ug(e,t={}){let n=ul(["ls-files","-z","--",...Mg],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&ul(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=DA(e,a);return{path:a,head:NA(c)?OA(c,"utf8"):null,base:r===null?null:ul(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:s}}function pl(e,t={}){return jg(Ug(e,t))}var Mg,$g,Lg,ml=_(()=>{"use strict";Mg=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],$g="<!-- maind:conventions v1 begin -->",Lg="<!-- maind:conventions v1 end -->";o(fl,"stripManagedConventionsBlock");o(Pg,"contentLines");o(Fg,"proseDelta");o(jg,"computeAgentDocProse");o(ul,"git");o(Ug,"gatherAgentDocProseFacts");o(pl,"checkAgentDocProse")});var Hg,Bg,hl=_(()=>{"use strict";Hg=[".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"],Bg=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 PA}from"node:child_process";import{existsSync as MA,readFileSync as $A}from"node:fs";import{join as LA}from"node:path";function Kg(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?[]:Os(n.base).map(i=>i.value));for(let i of Os(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 Gg(e,t){try{return PA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function Wg(e,t={}){let n=Gg(["ls-files","-z","--",...Hg],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=LA(e,s);return{path:s,content:MA(a)?$A(a,"utf8"):null,base:i===null?null:Gg(["show",`${i}:${s}`],e)}})}}function gl(e,t={}){return Kg(Wg(e,t))}var yl=_(()=>{"use strict";si();hl();o(Kg,"computeWorkflowYaml");o(Gg,"git");o(Wg,"gatherWorkflowYamlFacts");o(gl,"checkWorkflowYaml")});import{readFileSync as FA}from"node:fs";import{join as jA,posix as UA}from"node:path";function Vg(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 Fe(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 lt(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 HA(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&&!lt(a[1]).map(p=>Fe(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||!lt(c[1]).map(f=>Fe(f)?.name??"").filter(Boolean).includes("public"))return null;let d=lt(s).map(f=>f.replace(/^GROUP\s+/i,"").trim()).map(f=>Fe(f)?.name??"").filter(f=>f.length>0&&f!=="public");if(d.length===0)return null;let u=[];for(let f of lt(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:[...vi]};p[2]!=="("&&vi.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function zg(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(BA.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!lt(l[1]).map(p=>Fe(p)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let f=a.replace(/^TABLE\s+/i,""),p=lt(f).map(h=>Fe(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(p.length===0)return null;c=p}let d=lt(s).map(f=>f.replace(/^GROUP\s+/i,"").trim()).map(f=>Fe(f)?.name??"").filter(f=>f.length>0&&f!=="public"),u=[];for(let f of lt(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:[...vi]};!g&&vi.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function bl(e){let t=new Map,n=[...e].sort((i,s)=>at(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=Vg(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=HA(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=Fe(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 lt(f)){let h=Fe(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=Fe(u[1]),p=Fe(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=zg(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 w=t.get(y);if(w&&(h&&(w.anonAddressed=!0),g))for(let v of f.writePrivs)w.authWritesRevoked.add(v)}continue}}}return t}function _l(e){let t=[];for(let[n,r]of bl(e)){let i=[];r.anonAddressed||i.push("anon"),vi.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 qg(e){let t=_l(e.files),n=new Map;if(e.baseFiles!==null)for(let r of _l(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 Jg(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function vl(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Xs)||t.endsWith(wl))}function KA(e,t){try{let n=FA(e,"utf8");return n.length>t?null:n}catch{return null}}function WA(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} ${Xs}`),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=UA.basename(u),p=cr(f);if(p===null)continue;let h=C(e,["show",`${r}:${u}`]);if(h===null)return i.push(`could not read ${u} at ${r} ${wl}`),null;l.push({name:f,version:p,content:h})}return l}function bn(e,t={}){let n=t.maxFileBytes??GA,r=[],i=hn(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=ui(e);a=p?`origin/${p}`:null,a===null&&r.push(`no default branch resolvable ${Xs}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let p of i){let h=[];for(let w of p.files){let v=KA(jA(e,w.path),n);if(v===null){r.push(`could not read ${w.path} \u2014 excluded from the fold`);continue}h.push({ref:w,content:v})}let g=h.map(({ref:w,content:v})=>({name:w.name,version:w.version,content:v})),y=a===null?null:WA(e,p.dir,h,a,r);c.push(...qg({dir:p.dir,files:g,baseFiles:y})),l.push({dir:p.dir,migrationCount:g.length,tableCount:bl(g).size})}let d=l.reduce((p,h)=>p+h.migrationCount,0),u=Jg(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 vi,BA,GA,Xs,wl,Zs=_(()=>{"use strict";fe();fi();o(Vg,"stripSql");o(Fe,"normalizeQualifiedIdent");o(lt,"splitTopLevel");vi=["INSERT","UPDATE","DELETE"];o(HA,"parseDefaultAclTables");BA=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(zg,"parseTableRevoke");o(bl,"foldTableAcl");o(_l,"evaluateTableAcl");o(qg,"computeTableAclFindings");o(Jg,"deriveTableAclVerdict");GA=5e6,Xs="\u2014 findings reported ungraded (open)",wl="\u2014 baseline degraded";o(vl,"isTableAclGraded");o(KA,"safeRead");o(WA,"baseFilesFor");o(bn,"checkTableAclLint")});import{readFileSync as VA}from"node:fs";import{join as kl}from"node:path";function xl(e){return e.verdict!=="no_opinion"&&e.graded}function El(e){let t=new Set;for(let n of e.matchAll(zA))t.add(n[1]);return t}function Tl(e){return new Set([...e].map(t=>t.split("-")[0]))}function ty(e){return e.split(`
11
+ `),r===null?"created":"appended"}catch{return"skipped"}}var Yo,Hc,OR,Xo=v(()=>{"use strict";Yo=["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"],Hc=["# 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).'],OR=Hc;s(_i,"ensureMaindLocalIgnore")});import{execFileSync as DR}from"node:child_process";import{createHash as PR}from"node:crypto";import{readFileSync as MR,readdirSync as $R,statSync as LR}from"node:fs";import{posix as Bc,sep as Kh}from"node:path";function A(e,t){try{return DR("git",[...FR,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function jR(e){return Kh==="/"?e:e.split(Kh).join("/")}function Zo(e){let t=[];for(let n of e){let r=jR(n).trim();if(!r||yi(r))continue;let i=yr(r);i&&t.push({path:r,language:i})}return t}function Vh(e){return Zo(e)}function zh(e){let t=Mt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Zo(t.split(`
12
+ `));let n=[];return qh(e,"",n),Zo(n)}function qh(e,t,n){let r;try{r=$R(Bc.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Wh.has(i.name)||Wh.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?qh(e,o,n):i.isFile()&&n.push(o)}}function Gc(e,t){return Kc(e,t)??t}function Kc(e,t){let n=A(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Qo(e,t={}){if(bi(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Gc(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 o=Mt(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of o.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=Mt(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=Uc(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 Uc(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Wc(e,t={}){let n=Qo(e,t);return n===null?null:Zo(n.keys())}function Jh(e,t){try{let n=LR(Bc.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function es(e){return PR("sha256").update(e).digest("hex")}function bi(e){return Mt(e,["rev-parse","HEAD"])?.trim()??null}function ts(e,t){return Mt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function Vc(e){let t=Mt(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=HR(e);return n.some(i=>r===null||!UR(e,i,r))}function HR(e){let t=Mt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function UR(e,t,n){let r=t[0],i=t[1];if(Uc(t.slice(3))!==n)return!1;let o;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))o="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let p=Mt(e,["show",`HEAD:${n}`]);if(p===null)return!1;o=p}else return!1;let a;try{a=MR(Bc.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=s(p=>p.replace(/\r\n/g,`
16
+ `),"norm"),l=c(o),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...Yo,...Hc]);return d.slice(l.length).split(`
17
+ `).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var Wh,FR,Mt,_e=v(()=>{"use strict";Jo();Xo();Wh=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),FR=["-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"];s(A,"runGit");Mt=A;s(jR,"toPosix");s(Zo,"classify");s(Vh,"classifyPaths");s(zh,"discoverSourceFiles");s(qh,"walk");s(Gc,"resolveDiffBase");s(Kc,"resolveMergeBase");s(Qo,"enumerateChangedPaths");s(Uc,"unquote");s(Wc,"changedSourceFiles");s(Jh,"statFile");s(es,"hashContent");s(bi,"headCommit");s(ts,"resolveCommitSha");s(Vc,"isWorktreeDirty");s(HR,"toolIgnoreRepoPath");s(UR,"isToolOnlyIgnoreChange")});function Xh(e,t={}){if(A(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Gc(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 o=A(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(o,"utf8")>BR?c="none":VR(o,a,()=>{c="partial"}),n){let l=A(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 VR(e,t,n){let r=null,i=0,o=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
19
+ `)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!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":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=WR.exec(l);if(d){if(i++,i>GR){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<KR&&r.addedLines.push(l.slice(1))}c()}var BR,GR,KR,Yh,WR,Zh=v(()=>{"use strict";_e();BR=16*1024*1024,GR=500,KR=4e3,Yh=256*1024,WR=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Xh,"changedHunks");s(VR,"parseUnifiedDiff")});function qc(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=rg&&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>o&&(o=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:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}function JR(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function eg(e){return e.split(zR).filter(t=>t.trim().length>0)}function tg(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(qR);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function YR(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 ig(e,t,n={}){let r=JR(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,ng),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,zc),l=[];for(let u of c){let p=A(e,["log","-n",String(o),Qh,"--",u]),f=p===null?[]:eg(p).map(tg).filter(m=>m!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:i?{topAuthors:YR(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=ts(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=A(e,["log",...p,"-n",String(ns+1),Qh,"--name-only","--",...c]),m=[];if(f!==null)for(let g of eg(f)){let y=g.split(`
20
+ `),_=tg(y[0]??"");if(!_)continue;let b=y.slice(1).filter(k=>k.trim().length>0).length;m.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,ns),truncated:m.length>ns}}return{history:l,regression:d,ownershipWindowCommits:o,pathsTruncated:a.length>zc}}var zR,qR,ng,zc,ns,Qh,rg,Jc=v(()=>{"use strict";_e();zR="",qR="\0",ng=200,zc=50,ns=100,Qh="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",rg=10;s(qc,"aggregateHistoryContext");s(JR,"clamp");s(eg,"splitRecords");s(tg,"parseHistoryRecord");s(YR,"aggregateOwnership");s(ig,"readFileHistory")});import{execFileSync as XR}from"node:child_process";import{readdirSync as ZR,statSync as og}from"node:fs";import{isAbsolute as QR,join as Yc,relative as eC,resolve as tC}from"node:path";function rC(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function iC(e,t){try{let n=XR("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 oC(e){let t;try{t=ZR(e)}catch{return null}for(let n of t.filter(rC))try{let r=og(Yc(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function sC(e){try{return og(e).isDirectory()}catch{return!1}}function aC(e,t){let n=eC(e,t);return!n||n.startsWith("..")?t:n}function Xc(e){let t=nC.filter(c=>sC(Yc(e,c))),n=iC(e,"core.hooksPath"),r=n?QR(n)?n:tC(e,n):Yc(e,".git","hooks"),i=aC(e,r),o=oC(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===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 Zc(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 nC,Qc=v(()=>{"use strict";nC=[".githooks",".husky"];s(rC,"isRealHook");s(iC,"gitConfig");s(oC,"hasExecutableHook");s(sC,"isDir");s(aC,"displayPath");s(Xc,"resolveHookState");s(Zc,"describeHookState")});import{posix as sg}from"node:path";function _r(e){let t=cC.exec(e);return t?t[1]:null}function gt(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function wn(e,t){let n=A(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=sg.basename(o),c=_r(a);if(c===null)continue;let l=sg.dirname(o),d=i.get(l)??[];d.push({path:o,name:a,version:c}),i.set(l,d)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>gt(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function vi(e){let t=A(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(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var cC,wi=v(()=>{"use strict";_e();cC=/^(\d+)_.+\.sql$/;s(_r,"parseMigrationVersion");s(gt,"compareVersions");s(wn,"discoverSupabaseProjects");s(vi,"resolveDefaultBranch")});import{execFileSync as lC}from"node:child_process";import{existsSync as me,readFileSync as $t,readdirSync as rs,statSync as tl}from"node:fs";import{posix as U}from"node:path";function fC(e,t){let n=(()=>{let i=A(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(me(U.join(r,".git"))){let o=(()=>{let c=A(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&rl(n,o))){let c=mC(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=U.dirname(r)}return null}function mC(e,t){let n=[];for(let r of uC){let i;try{i=rs(U.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=U.join(e,a),l=U.join(t,a);try{let d=tl(c),u=tl(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>pC)continue;$t(c).equals($t(l))||n.push(a)}catch{continue}}}return n.sort()}function fg(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 o=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(o){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(!o&&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 ${il}.`})}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=s(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=hC(e.hooks);return a&&t.push(a),gC(t)}function hC(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:Zc(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 gC(e){return[...e].sort((t,n)=>ag[t.status]-ag[n.status]||t.id.localeCompare(n.id))}function mg(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function yt(e){let t=e?.trim();return t||null}function yC(e){let t=yt(A(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(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function _C(e){let t=yt(A(e,["rev-parse","--git-dir"]));if(!t)return null;let n=U.isAbsolute(t)?t:U.join(e,t);return me(U.join(n,"rebase-merge"))||me(U.join(n,"rebase-apply"))?"rebase":me(U.join(n,"MERGE_HEAD"))?"merge":me(U.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function bC(e){let t=[],n=null,r=s(()=>{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 vC(e){let t=U.join(e,il);if(!me(t))return[];try{return $t(t,"utf8").split(`
22
+ `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function wC(e){try{return wn(e).map(t=>U.join(U.dirname(t.dir),"config.toml"))}catch{return[]}}function kC(e){let t=A(e,["ls-files","-z","--",...dC]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=pg[U.basename(r)];if(i===void 0)continue;let o=U.dirname(r);if(!xC(e,o))continue;let a=o==="."?"node_modules":U.join(o,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function xC(e,t){return t==="."?!0:nl(e,t)}function nl(e,t){if(me(U.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse($t(U.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function hg(e,t={}){if(yt(A(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=yt(A(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=yC(e),c=yt(A(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let L=yt(A(e,["rev-parse","HEAD"])),B=yt(A(e,["rev-parse","@{u}"]));l=L!=null&&B!=null?L===B:null,d=A(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(a){let L=yt(A(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(L){let[B,P]=L.split(/\s+/).map(j=>Number.parseInt(j,10));Number.isFinite(B)&&(p=B),Number.isFinite(P)&&(u=P)}}let m=(A(e,["status","--porcelain"])??"").split(`
23
+ `).filter(L=>L.trim().length>0).length,g=_C(e),y=yt(A(e,["rev-parse","--show-toplevel"]))??e,_=bC(A(e,["worktree","list","--porcelain"])??""),b=_[0]?.path??null,k=b!=null&&rl(b,y),S=Math.max(0,_.length-1),T=null;if(b&&!rl(b,y)){let L=s(P=>me(U.join(b,P))&&!me(U.join(y,P)),"here"),B=[...ug,...wC(y),...vC(y),...t.probePaths??[]];T={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(B.filter(L))],missingDeps:kC(y).filter(P=>L(P.dir))}}let w=fC(y,e),x=t.includeRelease===!1?null:IC(e,o),N=[];return a&&(N=(A(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
24
+ `).map(B=>B.trim()).filter(B=>B.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:m,detachedHead:i,inProgressOp:g,isSharedMainTree:k,otherWorktrees:S,worktreeParity:T,toolCopyDrift:w,stalePackageBuilds:gg(y),release:x,unmergedMigrations:N,hooks:Xc(e)}}function rl(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function TC(e){let t=new Set;nl(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<lg;){let i=n.pop();if(i===void 0)break;if(i.depth>=EC)continue;let o;try{o=rs(U.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of o){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>=lg)break;nl(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function RC(e){let t=[];try{let n=U.join(e,"pnpm-workspace.yaml");if(me(n)){let r=!1;for(let i of $t(n,"utf8").split(`
25
+ `)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=U.join(e,"package.json");if(me(r)){let i=JSON.parse($t(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function CC(e){let t=[];for(let n of TC(e)){let r=n==="."?e:U.join(e,n),i=s(o=>n==="."?o:U.join(n,o),"prefix");for(let o of RC(r)){if(t.length>=el)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=U.join(r,a);if(!me(c))continue;for(let l of rs(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(U.join(a,l.name))),t.length>=el)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,el)}function dg(e){let t=null,n=0,r=[e];for(;r.length>0&&n<cg;){let i=r.pop();if(i===void 0)break;let o;try{o=rs(i,{withFileTypes:!0})}catch{continue}for(let a of o){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=tl(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=cg)break}}}return t}function AC(e,t){let n=new Set;for(let r of t)try{let i=U.join(e,r,"package.json");if(!me(i))continue;let o=JSON.parse($t(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[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 gg(e){let t=[],n=CC(e),r=AC(e,n);for(let i of n)try{let o=U.join(e,i,"package.json");if(!me(o))continue;let a=JSON.parse($t(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let k=b.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 p=l!==null&&d!==null?"both":l!==null?"types":"runtime",f=U.join(e,i,"src"),m=U.join(e,i,u);if(!me(f)||!me(m))continue;let g=dg(f),y=dg(m);if(g===null||y===null)continue;let _=g-y;_>SC&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function IC(e,t){if(!t)return null;let n=NC(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(o=>o.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function NC(e,t){try{return lC("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function ki(e,t={}){let n=await hg(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=fg(n),i=mg(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var ug,il,pg,dC,uC,pC,ag,SC,el,cg,EC,lg,ol=v(()=>{"use strict";Qc();_e();wi();ug=["supabase/config.toml","supabase/.temp",".env"],il=".maind/worktree-requirements",pg={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},dC=Object.keys(pg).flatMap(e=>[e,"*/"+e]),uC=["scripts"],pC=512*1024;s(fC,"gatherToolCopyDrift");s(mC,"compareToolDirs");s(fg,"computeDivergence");s(hC,"computeHookFinding");ag={open:0,warn:1,info:2,passed:3};s(gC,"sortFindings");s(mg,"isHealthy");s(yt,"trimOrNull");s(yC,"resolveDefaultBranch");s(_C,"detectInProgressOp");s(bC,"parseWorktrees");s(vC,"readWorktreeRequirements");s(wC,"discoverSupabaseConfigProbes");s(kC,"discoverDependencyDirs");s(xC,"isWorkspaceRoot");s(nl,"hasWorkspaceMarkers");s(hg,"gatherRepoHealthFacts");s(rl,"samePath");SC=2e3,el=64,cg=4e3,EC=3,lg=400;s(TC,"findWorkspaceRoots");s(RC,"workspacePatternsAt");s(CC,"listWorkspacePackageDirs");s(dg,"newestMtimeUnder");s(AC,"consumedWorkspaceNames");s(gg,"gatherStalePackageBuilds");s(IC,"gatherReleaseFact");s(NC,"runGh");s(ki,"checkDivergence")});import{existsSync as sl,readdirSync as yg}from"node:fs";import{posix as tt}from"node:path";function cl(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(al)}function bg(e,t={}){let n=t.minFiles??ll;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??_g)}function vr(e){return`${e.dir}#${e.prefix}`}function xi(e){let t=OC.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function vg(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=vr(i),a=e.sightingsByNamespace.get(o);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),m=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${i.prefix}${dl(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:${o}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} 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,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}function wg(e){return!e.some(t=>t.status==="open")}function dl(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 ul(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function kg(e,t){let n=ul(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=xi(tt.basename(n));if(!i)return r;let o=`${tt.dirname(n)}#${i.prefix}`,a=e.namespaces.find(u=>vr(u)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??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:dl(c.keys(),i.number)}}function is(e){let t=e?.trim();return t||null}function br(e){return e?e.split(`
26
+ `).filter(Boolean):[]}function DC(e){let t=is(A(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(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function xg(e,t={}){let n=t.minFiles??ll,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=A(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=tt.dirname(a),l=xi(tt.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=o.get(d);u?u.numbers.push(l.number):o.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>bg(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)=>vr(a).localeCompare(vr(c)))}async function pl(e,t={}){let n=[];if(is(A(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=xg(e,t),o=new Map(i.map(m=>[vr(m),m])),a=[...new Set(i.map(m=>m.dir))],c=new Map,l=s((m,g,y)=>{let _=tt.dirname(m),b=xi(tt.basename(m));if(!b)return;let k=`${_}#${b.prefix}`;if(!o.has(k))return;let S=c.get(k)??new Map,T=S.get(b.number)??[];T.push({kind:g,where:y,path:m}),S.set(b.number,T),c.set(k,S)},"record"),d=s((m,g,y)=>{if(a.length===0)return;let _=A(e,["ls-tree","-r","--name-only",m,"--",...a]);if(_===null){n.push(`could not read ${y}`);return}for(let b of br(_))l(b,g,y)},"scanTree");for(let m of a){let g=tt.join(e,m);if(sl(g))try{for(let y of yg(g))l(`${m}/${y}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let u=DC(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 m=is(A(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of br(A(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==m&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let m=is(A(e,["rev-parse","--show-toplevel"]));for(let g of br(A(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===m||!sl(y)))for(let _ of a){let b=tt.join(y,_);if(sl(b))try{for(let k of yg(b))l(`${_}/${k}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${_} in ${y}`)}}}}let f=[];if(p&&a.length>0){let m=A(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);m===null?n.push(al):f=br(m);let g=A(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(f=[...f,...br(g)]);let y=A(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(f=[...f,...br(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:f,skipped:n}}async function kn(e,t={}){let n=await pl(e,t),r=vg(n);return{ok:wg(r),findings:r,facts:n}}async function xn(e,t,n={}){let r=ul(t);if(!xi(tt.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await pl(e,{...n,dirs:n.dirs??[tt.dirname(r)]});return kg(i,r)}var al,OC,ll,_g,Si=v(()=>{"use strict";_e();al="could not diff against the base ref \u2014 everything reported as info";s(cl,"isNumberCollisionsGraded");OC=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,ll=3,_g=.8;s(bg,"isCounterNamespace");s(vr,"namespaceKey");s(xi,"parseNumbered");s(vg,"computeNumberCollisions");s(wg,"isCollisionFree");s(dl,"suggestNextNumber");s(ul,"normaliseRepoPath");s(kg,"checkProposedNumber");s(is,"trimOrNull");s(br,"lines");s(DC,"resolveDefaultBranch");s(xg,"detectNamespaces");s(pl,"gatherNumberCollisionFacts");s(kn,"checkNumberCollisions");s(xn,"checkNumberForPath")});import{execFileSync as PC}from"node:child_process";import{createHash as MC}from"node:crypto";function fl(e){return MC("sha256").update(e).digest("hex")}function $C(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 LC(e){let t=$C(e);return t?fl(t):null}function jC(e){return typeof e=="string"&&FC.test(e)}function Sg(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(jC(t))return t;let n;try{n=PC("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?LC(n):null}var FC,ml=v(()=>{"use strict";s(fl,"sha256Hex");s($C,"normalizeRemoteUrl");s(LC,"projectKeyFromRemote");FC=/^[a-f0-9]{64}$/;s(jC,"isProjectKey");s(Sg,"computeProjectKey")});function _l(e){return`spec.${e}`}function wr(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 HC(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Eg(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(HC)}function Ti(e){return fl(JSON.stringify(Eg(e)))}var Ei,hl,gl,yl,bl=v(()=>{"use strict";ml();Ei={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"]}},hl="number.collision",gl="theme.dead_class",yl="acl.missing_revoke";s(_l,"specDriftRuleId");s(wr,"gradeEngineStatus");s(HC,"codePointCompare");s(Eg,"normalizeEvidenceForHash");s(Ti,"hashDetectorEvidence")});import{existsSync as UC,readFileSync as Tg}from"node:fs";import{posix as BC}from"node:path";function as(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 cs(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 Ri(e){return e==='"'||e==="'"||e==="`"}function ls(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 o=e[i];if(Ri(o)){i=as(e,i);continue}if(ls(e,i)){i=cs(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function GC(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(ls(e,t)){t=cs(e,t);continue}break}return e.slice(t)}function kr(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(Ri(o)){i=as(e,i);continue}if(ls(e,i)){i=cs(e,i);continue}o==="["||o==="{"||o==="("?n++:o==="]"||o==="}"||o===")"?n--:o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(o=>GC(o).trim()).filter(o=>o.length>0)}function Ig(e){let t=as(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
28
+ `:i==="r"?"\r":i==="t"?" ":i)}function KC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wl(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${KC(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let a=e[i];if(Ri(a)){i=as(e,i);continue}if(ls(e,i)){i=cs(e,i);continue}if(!o){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(a===";")return null;i++;continue}if(a==="[")return os(e,i);if(a===";")return null;i++}return null}function kl(e){let t={};if(!e.startsWith("{"))return t;for(let n of kr(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],o=r[4].trim();Ri(o[0]??"")&&(t[i]=Ig(o))}return t}function WC(e,t){if(!e.startsWith("{"))return null;for(let n of kr(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 Ng(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Og(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Dg(e,t){let n=wl(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Og(),i=[],o=0;for(let a of kr(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=kl(a),l=c[t.key_field];if(!l){o++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:Ng(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Pg(e,t){let n=wl(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=Og(),i=[],o=0,a=s((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of kr(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){o++;continue}let y=kl(f);for(let[_,b]of Object.entries(u.fields??{}))m[_]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let _=WC(f,u.children);g=_&&_.startsWith("[")?os(_,0):null}}else{if(!f.startsWith("[")){o++;continue}let y=kr(f.slice(1,-1));for(let[_,b]of Object.entries(u.fields??{})){let k=y[Number(b)];m[_]=k!==void 0&&Ri(k[0]??"")?Ig(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?os(_,0):null}}if(p){let y=m[t.key_field];if(!y){o++;continue}let _=(t.partition_by??[]).map(b=>m[b]??"");i.push({key:y,fields:Ng(m,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,m)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Rg(e,t){return t.extractor==="object-array"?Dg(e,t):Pg(e,t)}function Mg(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 $g(e,t,n){return`spec.drift:${e}#${t}:${n}`}function VC(e){return e.orderPath.join(" / ")||"(flat)"}function Lg(e,t,n,r){let i=[],o=s((d,u,p,f,m,g)=>{i.push({id:$g(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:m,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){o("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${VC(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]??"",m=u.fields[p]??"";f!==m&&o("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${m||"\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),m=new Set(f),g=p.filter(y=>m.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";o("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)||o("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(Mg(d,e.grounding,r))continue;let u=a.has(d);o("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 zC(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.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 Cg(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 Fg(e,t={}){let n=s(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=s(u=>{let p=[],f=[];for(let m of r){let g=u.get(m.spec.path),y=u.get(m.impl.path);if(g==null||y==null){let S=g==null?m.spec.path:m.impl.path;p.push(Cg(m.id,`Declared file could not be read: ${S}`)),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=Rg(g,m.spec),b=Rg(y,m.impl);if(_.error||b.error){p.push(Cg(m.id,_.error??b.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=_.dropped>0||b.dropped>0;f.push({id:m.id,measured:!0,specRecords:_.records.length,implRecords:b.records.length,partial:k}),k&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${_.dropped} specification and ${b.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(...Lg(m,_.records,b.records,e.files)),p.push(...zC(m,{spec:_.records.length,impl:b.records.length},u))}return{findings:p,contracts:f}},"runOnce"),o=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($g(u.id,p.dimension,p.key),p);let l=o.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)=>Ag[u.status]-Ag[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:o.contracts}}function vl(e){let t=e?.trim();return t||null}function ds(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=s(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=s(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 o=s(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 o(`${u}: not an object`);if(!d)return o(`${u}: \`id\` is missing`);if(!r(l.reason))return o(`${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 o(`${u}: \`${p}\` is missing`);let m=r(f.extractor);if(!m)return o(`${u}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return o(`${u}: unknown \`${p}.extractor\` "${m}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${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 o(`${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 qC(e){let t=vl(A(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(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function JC(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 jg(e,t={}){let n=s((g,y)=>BC.join(g,y),"join"),r=t.manifestPath??ss,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(vl(A(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!UC(a))return{...o,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}=ds(Tg(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let d=new Map;for(let g of JC(c))try{d.set(g,Tg(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=A(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,m=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:qC(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=vl(A(e,["merge-base",y,"HEAD"])),!f)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())m.set(_,A(e,["show",`${f}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:f,files:u,skipped:i}}async function Sn(e,t={}){let n=await jg(e,t);return{...Fg(n,t),facts:n}}function xl(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var ss,Ag,Ci=v(()=>{"use strict";_e();ss=".maind/spec-contracts.json";s(as,"endOfString");s(cs,"skipComment");s(Ri,"isQuote");s(ls,"isCommentStart");s(os,"sliceBalanced");s(GC,"stripLeadingTrivia");s(kr,"splitTopLevel");s(Ig,"readStringLiteral");s(KC,"escapeRe");s(wl,"findSymbolArray");s(kl,"parseObjectFields");s(WC,"objectFieldRaw");s(Ng,"pickFields");s(Og,"makeOrdinals");s(Dg,"extractObjectArray");s(Pg,"extractNestedList");s(Rg,"extractRecords");s(Mg,"isGrounded");s($g,"findingId");s(VC,"partitionOf");s(Lg,"compareContract");s(zC,"checkAssertions");s(Cg,"unreadable");Ag={open:0,warn:1,info:2,passed:3};s(Fg,"computeSpecDrift");s(vl,"trimOrNull");s(ds,"parseManifest");s(qC,"resolveDefaultBranch");s(JC,"declaredPaths");s(jg,"gatherSpecDriftFacts");s(Sn,"checkSpecDrift");s(xl,"isSpecDriftGraded")});import{execFileSync as YC}from"node:child_process";import{existsSync as XC,readFileSync as ZC}from"node:fs";import{join as QC}from"node:path";function Ai(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 o=/(\d+\.\d+\.\d+)/.exec(i);o&&t.push({version:o[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":eA.test(i)?"never-published":"released"})}return t}function Ug(e){let t=new Map;for(let n of Ai(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 Bg(e,t){let n=Ug(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of Ai(t))r.set(a.version,(r.get(a.version)??0)+1);let i=[],o=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?i:o).push({...a,countBefore:c})}return{introduced:i,preExisting:o,baseResolved:!0}}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 CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let i=Bg(r.head,e.baseRef===null?null:r.base);for(let o of i.introduced)t.push({path:r.path,version:o.version,level:"open",count:o.count,countBefore:o.countBefore,lines:o.lines,title:`${r.path}: version ${o.version} has ${o.count} headings (was ${o.countBefore})`});for(let o of i.preExisting)t.push({path:r.path,version:o.version,level:"info",count:o.count,countBefore:o.countBefore,lines:o.lines,title:`${r.path}: version ${o.version} already had ${o.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function Hg(e,t){try{return YC("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function tA(e,t={}){let n=Hg(["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,o=r.map(a=>{let c=QC(e,a);return{path:a,head:XC(c)?ZC(c,"utf8"):null,base:i===null?null:Hg(["show",`${i}:${a}`],e)}});return{isRepo:!0,baseRef:i,files:o}}function Sl(e,t={}){return Gg(tA(e,t))}var eA,us=v(()=>{"use strict";eA=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;s(Ai,"parseVersionHeadings");s(Ug,"findDuplicateHeadings");s(Bg,"classifyIntroduced");s(Gg,"computeChangelogDuplicates");s(Hg,"git");s(tA,"gatherChangelogFacts");s(Sl,"checkChangelogDuplicates")});import{execFileSync as nA}from"node:child_process";import{existsSync as rA,readFileSync as Kg}from"node:fs";import{dirname as Wg,join as Vg}from"node:path";function qg(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),o=[...n.documented].sort(fi);for(let a of o){if(r.has(a)||fi(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(fi))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 zg(e){let t=Ai(e),n=[...new Set(t.filter(o=>o.shape!=="never-published").map(o=>o.version))],r=new Set(n),i=[...new Set(t.filter(o=>o.shape==="never-published"&&!r.has(o.version)).map(o=>o.version))];return{documented:n,neverPublished:i}}function El(e,t){try{return nA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function Jg(e,t=null){let n=El(["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 o;try{o=JSON.parse(Kg(Vg(e,i),"utf8"))}catch{continue}if(o.private===!0||typeof o.name!="string"||typeof o.version!="string")continue;let a=Wg(i)==="."?"":Wg(i),c=Vg(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=rA(c)?zg(Kg(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:El(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:zg(p).documented;r.push({dir:a,name:o.name,version:o.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function iA(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 Yg(e,t={}){if(El(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=Jg(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??iA,i={};for(let o of n)try{i[o.name]=await r(o.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${o.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:i,registryReachable:!0,registryError:null}}async function Tl(e,t={}){return qg(await Yg(e,t))}var Rl=v(()=>{"use strict";mi();us();s(qg,"computeReleaseClaims");s(zg,"claimsOf");s(El,"git");s(Jg,"discoverPackages");s(iA,"packument");s(Yg,"gatherReleaseClaimsFacts");s(Tl,"checkReleaseClaims")});import{execFileSync as oA}from"node:child_process";import{existsSync as sA,readFileSync as aA}from"node:fs";import{join as cA}from"node:path";function Al(e){let t=[],n=!1;for(let r of e.split(`
32
+ `)){let i=r.trim();if(n){i===ey&&(n=!1);continue}if(i===Qg){n=!0;continue}t.push(r)}return t.join(`
33
+ `)}function Xg(e){return e.split(`
34
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function ty(e,t){let n=new Map;for(let o of Xg(t??""))n.set(o,(n.get(o)??0)+1);let r=[];for(let o of Xg(e)){let a=n.get(o)??0;a>0?n.set(o,a-1):r.push(o)}let i=0;for(let o of n.values())i+=o;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function ny(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=ty(Al(n.head),n.base===null?null:Al(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 Cl(e,t){try{return oA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function ry(e,t={}){let n=Cl(["ls-files","-z","--",...Zg],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Cl(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,o=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=cA(e,a);return{path:a,head:sA(c)?aA(c,"utf8"):null,base:r===null?null:Cl(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:o}}function Il(e,t={}){return ny(ry(e,t))}var Zg,Qg,ey,Nl=v(()=>{"use strict";Zg=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],Qg="<!-- maind:conventions v1 begin -->",ey="<!-- maind:conventions v1 end -->";s(Al,"stripManagedConventionsBlock");s(Xg,"contentLines");s(ty,"proseDelta");s(ny,"computeAgentDocProse");s(Cl,"git");s(ry,"gatherAgentDocProseFacts");s(Il,"checkAgentDocProse")});var iy,oy,Ol=v(()=>{"use strict";iy=[".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"],oy=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 lA}from"node:child_process";import{existsSync as dA,readFileSync as uA}from"node:fs";import{join as pA}from"node:path";function ay(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?[]:zo(n.base).map(i=>i.value));for(let i of zo(n.content)){let o=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 ${o}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function sy(e,t){try{return lA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function cy(e,t={}){let n=sy(["ls-files","-z","--",...iy],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(o=>{let a=pA(e,o);return{path:o,content:dA(a)?uA(a,"utf8"):null,base:i===null?null:sy(["show",`${i}:${o}`],e)}})}}function Dl(e,t={}){return ay(cy(e,t))}var Pl=v(()=>{"use strict";mi();Ol();s(ay,"computeWorkflowYaml");s(sy,"git");s(cy,"gatherWorkflowYamlFacts");s(Dl,"checkWorkflowYaml")});import{readFileSync as fA}from"node:fs";import{join as mA,posix as hA}from"node:path";function ly(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],o=e[n+1];if(i==="-"&&o==="-"){for(;n<r&&e[n]!==`
35
+ `;)n++;continue}if(i==="/"&&o==="*"){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")&&o==="'"&&(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 Ue(e){let t=[],n="",r=!1,i=!1,o=s(()=>{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){o();continue}n+=l}o();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 _t(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 gA(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,o]=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&&!_t(a[1]).map(f=>Ue(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||!_t(c[1]).map(p=>Ue(p)?.name??"").filter(Boolean).includes("public"))return null;let d=_t(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Ue(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of _t(i)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...Ii]};f[2]!=="("&&Ii.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function dy(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,o]=t;if(n)return null;let a=i.trim();if(yA.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!_t(l[1]).map(f=>Ue(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=_t(p).map(m=>Ue(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(f.length===0)return null;c=f}let d=_t(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Ue(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of _t(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase(),g=f[2]==="(";if(m==="ALL")return{tables:c,roles:d,writePrivs:[...Ii]};!g&&Ii.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function $l(e){let t=new Map,n=[...e].sort((i,o)=>gt(i.version,o.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let o=ly(i.content);for(let a of o.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=gA(c);if(!p)continue;let f=p.roles.includes("anon"),m=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),m)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(f&&(r.anonAddressed=!1),m)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=Ue(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 _t(p)){let m=Ue(f);m&&m.schema==="public"&&t.delete(m.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=Ue(u[1]),f=Ue(u[2]);if(p&&f&&p.schema==="public"){let m=t.get(p.name);m&&(t.delete(p.name),t.set(f.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=dy(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,m=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!m&&!g)continue;for(let y of f){let _=t.get(y);if(_&&(m&&(_.anonAddressed=!0),g))for(let b of p.writePrivs)_.authWritesRevoked.add(b)}continue}}}return t}function Ml(e){let t=[];for(let[n,r]of $l(e)){let i=[];r.anonAddressed||i.push("anon"),Ii.every(o=>r.authWritesRevoked.has(o))||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 uy(e){let t=Ml(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Ml(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 py(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Fl(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(ps)||t.endsWith(Ll))}function bA(e,t){try{let n=fA(e,"utf8");return n.length>t?null:n}catch{return null}}function vA(e,t,n,r,i){let o=A(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(o===null)return i.push(`could not diff ${t} against ${r} ${ps}`),null;let a=new Set,c=[];for(let u of o.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=hA.basename(u),f=_r(p);if(f===null)continue;let m=A(e,["show",`${r}:${u}`]);if(m===null)return i.push(`could not read ${u} at ${r} ${Ll}`),null;l.push({name:p,version:f,content:m})}return l}function En(e,t={}){let n=t.maxFileBytes??_A,r=[],i=wn(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let o=t.includeBaseline!==!1,a=null;if(o)if(t.baseRef)a=t.baseRef;else{let f=vi(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 m=[];for(let _ of f.files){let b=bA(mA(e,_.path),n);if(b===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}m.push({ref:_,content:b})}let g=m.map(({ref:_,content:b})=>({name:_.name,version:_.version,content:b})),y=a===null?null:vA(e,f.dir,m,a,r);c.push(...uy({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:$l(g).size})}let d=l.reduce((f,m)=>f+m.migrationCount,0),u=py(d,c.length),p={open:0,info:1};return c.sort((f,m)=>p[f.status]-p[m.status]||f.id.localeCompare(m.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var Ii,yA,_A,ps,Ll,fs=v(()=>{"use strict";_e();wi();s(ly,"stripSql");s(Ue,"normalizeQualifiedIdent");s(_t,"splitTopLevel");Ii=["INSERT","UPDATE","DELETE"];s(gA,"parseDefaultAclTables");yA=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(dy,"parseTableRevoke");s($l,"foldTableAcl");s(Ml,"evaluateTableAcl");s(uy,"computeTableAclFindings");s(py,"deriveTableAclVerdict");_A=5e6,ps="\u2014 findings reported ungraded (open)",Ll="\u2014 baseline degraded";s(Fl,"isTableAclGraded");s(bA,"safeRead");s(vA,"baseFilesFor");s(En,"checkTableAclLint")});import{readFileSync as wA}from"node:fs";import{join as jl}from"node:path";function Ul(e){return e.verdict!=="no_opinion"&&e.graded}function Bl(e){let t=new Set;for(let n of e.matchAll(kA))t.add(n[1]);return t}function Gl(e){return new Set([...e].map(t=>t.split("-")[0]))}function _y(e){return e.split(`
37
37
  `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
38
- `)}function Rl(e){let t=Tl(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=ty(i),a=new Set;for(let c of s.matchAll(qA)){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 Yg(e){return`${e.file} ${e.klass}`}function JA(e,t){let n=t===null?null:new Set(t.map(Yg));return e.map(r=>({...r,status:n!==null&&n.has(Yg(r))?"info":"open"}))}function ny(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Al(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Zg(e,t){let n=C(e,["ls-files","--",...t]);return n===null?[]:n.split(`
39
- `).filter(Boolean)}function wn(e,t={}){let n=t.maxFileBytes??YA,r=new Set;for(let u of Zg(e,["*.css"])){let f=Sl(kl(e,u),n);if(f!==null)for(let p of El(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=>Xg.map(f=>`${u.replace(/\/+$/,"")}/**/${f}`)):Xg,s=[];for(let u of Zg(e,i)){if(!Al(u))continue;let f=Sl(kl(e,u),n);f!==null&&s.push({path:u,content:f})}let a=Rl({tokens:r,sources:s}),c=t.includeBaseline===!1?null:XA(e,i,n,t.baseRef),l=JA(a,c?.findings??null),d=ny(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:Tl(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function XA(e,t,n,r){let i=r??QA(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}`]):Sl(kl(e,f),n),"atBase"),d=new Set;for(let f of Qg(e,s,["*.css"])){let p=l(f);if(p!==null)for(let h of El(p))d.add(h)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let f of Qg(e,s,t)){if(!Al(f))continue;let p=l(f);p===null||p.length>n||u.push({path:f,content:p})}return{findings:Rl({tokens:d,sources:u}),mergeBase:s}}function Qg(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=>ZA(i,s)))}function ZA(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 QA(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 Sl(e,t){try{let n=VA(e,"utf8");return n.length>t?null:n}catch{return null}}var ey,zA,qA,Xg,YA,Qs=_(()=>{"use strict";fe();o(xl,"isThemeClassDriftGraded");ey=["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"],zA=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,qA=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+ey.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(El,"extractTokens");o(Tl,"deriveNamespaces");o(ty,"stripCommentLines");o(Rl,"evaluateThemeClasses");o(Yg,"findingKey");o(JA,"gradeAgainstBaseline");o(ny,"deriveThemeClassVerdict");Xg=["*.ts","*.tsx","*.js","*.jsx"],YA=15e5;o(Al,"isScannableSource");o(Zg,"listTracked");o(wn,"checkThemeClassDrift");o(XA,"baselineFindings");o(Qg,"listTrackedAt");o(ZA,"matchesSourcePattern");o(QA,"resolveBaseRef");o(Sl,"safeRead")});function Cl(e){return gi[e].version}function ut(e,t,n,r){return{detector_id:e,detector_version:Cl(e),state:t,finding_count:n,...r?{reason:r}:{}}}function V(e,t,n){return{summary:ut(e,t,0,n),findings:[]}}function cy(e){return e==="open"||e==="warn"||e==="info"}function eC(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(!Wc(n))return V(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!cy(s.status))continue;let{level:a,baseline:c}=ur(s.status);i.push({detector_id:t,rule_id:Zc,level:a,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:ut(t,"ran",i.length),findings:i}}function tC(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(!ol(n))return V(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!cy(i.status))continue;let{level:s,baseline:a}=ur(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:tl(i.dimension),level:s,baseline:a,evidence:[i.id],title:i.title})}return{summary:ut(t,"ran",r.length),findings:r}}function nC(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(!xl(n))return V(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=ur(i.status);r.push({detector_id:t,rule_id:Qc,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:ut(t,"ran",r.length),findings:r}}function rC(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(!vl(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}=ur(i.status);r.push({detector_id:t,rule_id:el,level:s,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:ut(t,"ran",r.length),findings:r}}function iC(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:ut(t,"ran",r.length),findings:r}}function sC(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:ut(t,"ran",r.length),findings:r}}function oC(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:ut(t,"ran",r.length),findings:r}}function aC(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:ut(t,"ran",r.length),findings:r}}function Il(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||eo[e.level]-eo[t.level]||iy[e.baseline]-iy[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function sy(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function cC(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=yi(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:Cl(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,eo[i.level]<eo[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:Cl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:yi(i.evidence),count:i.count});return r.sort(Il)}function lC(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 Re(e){let t={det_number_collisions:eC(e.number),det_spec_drift:tC(e.spec),det_theme_class_drift:nC(e.theme),det_table_acl_lint:rC(e.acl),det_changelog_duplicates:iC(e.changelog),det_workflow_yaml:sC(e.workflow),det_release_claims:oC(e.release),det_agent_doc_prose:aC(e.agentDoc)},n=ry.map(l=>t[l].summary),r=ry.flatMap(l=>t[l].findings),i=cC(r),s=[...i].sort((l,d)=>sy(l)-sy(d)||Il(l,d)).slice(0,oy).sort(Il),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:yi(l.evidence),title:l.title}));return{findings:s,coverage:lC(n,a),engines:n,local:c,truncated:a}}function dt(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 Ol(e){return e instanceof Error?e.message:String(e)}async function At(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Ol(t)}}}async function Dl(e,t={}){let n={...ay,...t.engines};try{if(!ly(e))return Re(dt("not a git work tree"));let r=await dy(e,n,t.baseRef),i=await Nl(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Re({...r,number:i})}catch(r){return Re(dt(`detector adapter failed: ${Ol(r)}`))}}async function Pl(e,t={}){let n={...ay,...t.engines};try{if(!ly(e)){let a=Re(dt("not a git work tree"));return{commit:a,local:a}}let r=await dy(e,n,t.baseRef),i=await Nl(e,n,t.baseRef,"commit"),s=await Nl(e,n,t.baseRef,"local");return{commit:Re({...r,number:i}),local:Re({...r,number:s})}}catch(r){let i=Re(dt(`detector adapter failed: ${Ol(r)}`));return{commit:i,local:i}}}function ly(e){return C(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function dy(e,t,n){let r=n?{baseRef:n}:{};return{spec:await At(()=>t.spec(e,r)),theme:await At(()=>t.theme(e,r)),acl:await At(()=>t.acl(e,r)),changelog:await At(()=>t.changelog(e,r)),workflow:await At(()=>t.workflow(e,r)),release:await At(()=>t.release(e,r)),agentDoc:await At(()=>t.agentDoc(e,r))}}function Nl(e,t,n,r,i){let s=r==="local";return At(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var oy,ay,ry,eo,iy,Ml=_(()=>{"use strict";fe();nl();hi();bi();dl();ml();yl();Ys();Zs();Qs();oy=64,ay={number:o((e,t)=>gn(e,t),"number"),spec:o((e,t)=>_n(e,t),"spec"),theme:o((e,t)=>wn(e,t),"theme"),acl:o((e,t)=>bn(e,t),"acl"),changelog:o((e,t)=>al(e,t),"changelog"),workflow:o((e,t)=>gl(e,t),"workflow"),release:o((e,t)=>ll(e,t),"release"),agentDoc:o((e,t)=>pl(e,t),"agentDoc")},ry=["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(Cl,"versionOf");o(ut,"summary");o(V,"noFindings");o(cy,"isFindingStatus");o(eC,"adaptNumber");o(tC,"adaptSpec");o(nC,"adaptTheme");o(rC,"adaptAcl");o(iC,"adaptChangelog");o(sC,"adaptWorkflow");o(oC,"adaptRelease");o(aC,"adaptAgentDoc");eo={open:0,warn:1,info:2},iy={introduced:0,pre_existing:1};o(Il,"compareWire");o(sy,"capPriority");o(cC,"buildWire");o(lC,"deriveCoverage");o(Re,"adaptDetectorReports");o(dt,"unavailableDetectorReports");o(Ol,"errorText");o(At,"attempt");o(Dl,"runRepoHealthDetectors");o(Pl,"runRepoHealthDetectorScopes");o(ly,"insideWorkTree");o(dy,"runSharedEngines");o(Nl,"runNumberEngine")});var uy,$l=_(()=>{"use strict";hl();uy=[{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:Bg},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function fy(e){let t=new Set;for(let[n,r]of e.paths)for(let i of uy){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=dC(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function dC(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
42
- `):t.readUntracked(e)}var py=_(()=>{"use strict";$l();o(fy,"scanRiskFlags");o(dC,"contentForPath")});var Ct,Ll,It,pr,ki,mr,Fl,to,no,ro,jl,my,hr=_(()=>{"use strict";Ct="3",Ll=`
38
+ `)}function Kl(e){let t=Gl(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=_y(i),a=new Set;for(let c of o.matchAll(xA)){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 fy(e){return`${e.file} ${e.klass}`}function SA(e,t){let n=t===null?null:new Set(t.map(fy));return e.map(r=>({...r,status:n!==null&&n.has(fy(r))?"info":"open"}))}function by(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Wl(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function hy(e,t){let n=A(e,["ls-files","--",...t]);return n===null?[]:n.split(`
39
+ `).filter(Boolean)}function Tn(e,t={}){let n=t.maxFileBytes??EA,r=new Set;for(let u of hy(e,["*.css"])){let p=Hl(jl(e,u),n);if(p!==null)for(let f of Bl(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=>my.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):my,o=[];for(let u of hy(e,i)){if(!Wl(u))continue;let p=Hl(jl(e,u),n);p!==null&&o.push({path:u,content:p})}let a=Kl({tokens:r,sources:o}),c=t.includeBaseline===!1?null:TA(e,i,n,t.baseRef),l=SA(a,c?.findings??null),d=by(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:Gl(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function TA(e,t,n,r){let i=r??CA(e);if(i===null)return null;let o=A(e,["merge-base",i,"HEAD"])?.trim();if(!o)return null;let a=A(e,["diff","--name-only","--no-renames",o]);if(a===null)return null;let c=new Set(a.split(`
40
+ `).filter(Boolean)),l=s(p=>c.has(p)?A(e,["show",`${o}:${p}`]):Hl(jl(e,p),n),"atBase"),d=new Set;for(let p of gy(e,o,["*.css"])){let f=l(p);if(f!==null)for(let m of Bl(f))d.add(m)}if(d.size===0)return{findings:[],mergeBase:o};let u=[];for(let p of gy(e,o,t)){if(!Wl(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:Kl({tokens:d,sources:u}),mergeBase:o}}function gy(e,t,n){let r=A(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
41
+ `).filter(i=>i.length>0&&n.some(o=>RA(i,o)))}function RA(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 o=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?o.endsWith(r.slice(1)):o===r}function CA(e){let t=A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>A(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Hl(e,t){try{let n=wA(e,"utf8");return n.length>t?null:n}catch{return null}}var yy,kA,xA,my,EA,ms=v(()=>{"use strict";_e();s(Ul,"isThemeClassDriftGraded");yy=["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"],kA=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,xA=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+yy.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Bl,"extractTokens");s(Gl,"deriveNamespaces");s(_y,"stripCommentLines");s(Kl,"evaluateThemeClasses");s(fy,"findingKey");s(SA,"gradeAgainstBaseline");s(by,"deriveThemeClassVerdict");my=["*.ts","*.tsx","*.js","*.jsx"],EA=15e5;s(Wl,"isScannableSource");s(hy,"listTracked");s(Tn,"checkThemeClassDrift");s(TA,"baselineFindings");s(gy,"listTrackedAt");s(RA,"matchesSourcePattern");s(CA,"resolveBaseRef");s(Hl,"safeRead")});function Vl(e){return Ei[e].version}function vt(e,t,n,r){return{detector_id:e,detector_version:Vl(e),state:t,finding_count:n,...r?{reason:r}:{}}}function V(e,t,n){return{summary:vt(e,t,0,n),findings:[]}}function Ey(e){return e==="open"||e==="warn"||e==="info"}function AA(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(!cl(n))return V(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!Ey(o.status))continue;let{level:a,baseline:c}=wr(o.status);i.push({detector_id:t,rule_id:hl,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:vt(t,"ran",i.length),findings:i}}function IA(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(!xl(n))return V(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Ey(i.status))continue;let{level:o,baseline:a}=wr(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:_l(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:vt(t,"ran",r.length),findings:r}}function NA(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:o,baseline:a}=wr(i.status);r.push({detector_id:t,rule_id:gl,level:o,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:vt(t,"ran",r.length),findings:r}}function OA(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(!Fl(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:o,baseline:a}=wr(i.status);r.push({detector_id:t,rule_id:yl,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:vt(t,"ran",r.length),findings:r}}function DA(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:vt(t,"ran",r.length),findings:r}}function PA(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:vt(t,"ran",r.length),findings:r}}function MA(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:vt(t,"ran",r.length),findings:r}}function $A(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:vt(t,"ran",r.length),findings:r}}function zl(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||hs[e.level]-hs[t.level]||wy[e.baseline]-wy[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function ky(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function LA(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Ti(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${o}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:Vl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:o,count:1})}else{let o=`${i.detector_id}|${i.rule_id}`,a=n.get(o);a?(a.evidence.push(...i.evidence),a.count+=1,hs[i.level]<hs[a.level]&&(a.level=i.level)):n.set(o,{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:Vl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Ti(i.evidence),count:i.count});return r.sort(zl)}function FA(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 Oe(e){let t={det_number_collisions:AA(e.number),det_spec_drift:IA(e.spec),det_theme_class_drift:NA(e.theme),det_table_acl_lint:OA(e.acl),det_changelog_duplicates:DA(e.changelog),det_workflow_yaml:PA(e.workflow),det_release_claims:MA(e.release),det_agent_doc_prose:$A(e.agentDoc)},n=vy.map(l=>t[l].summary),r=vy.flatMap(l=>t[l].findings),i=LA(r),o=[...i].sort((l,d)=>ky(l)-ky(d)||zl(l,d)).slice(0,xy).sort(zl),a=i.length-o.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Ti(l.evidence),title:l.title}));return{findings:o,coverage:FA(n,a),engines:n,local:c,truncated:a}}function bt(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 Jl(e){return e instanceof Error?e.message:String(e)}async function Lt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Jl(t)}}}async function Yl(e,t={}){let n={...Sy,...t.engines};try{if(!Ty(e))return Oe(bt("not a git work tree"));let r=await Ry(e,n,t.baseRef),i=await ql(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Oe({...r,number:i})}catch(r){return Oe(bt(`detector adapter failed: ${Jl(r)}`))}}async function Xl(e,t={}){let n={...Sy,...t.engines};try{if(!Ty(e)){let a=Oe(bt("not a git work tree"));return{commit:a,local:a}}let r=await Ry(e,n,t.baseRef),i=await ql(e,n,t.baseRef,"commit"),o=await ql(e,n,t.baseRef,"local");return{commit:Oe({...r,number:i}),local:Oe({...r,number:o})}}catch(r){let i=Oe(bt(`detector adapter failed: ${Jl(r)}`));return{commit:i,local:i}}}function Ty(e){return A(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function Ry(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Lt(()=>t.spec(e,r)),theme:await Lt(()=>t.theme(e,r)),acl:await Lt(()=>t.acl(e,r)),changelog:await Lt(()=>t.changelog(e,r)),workflow:await Lt(()=>t.workflow(e,r)),release:await Lt(()=>t.release(e,r)),agentDoc:await Lt(()=>t.agentDoc(e,r))}}function ql(e,t,n,r,i){let o=r==="local";return Lt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:o,includeWorktrees:i??o}))}var xy,Sy,vy,hs,wy,Zl=v(()=>{"use strict";_e();bl();Si();Ci();Rl();Nl();Pl();us();fs();ms();xy=64,Sy={number:s((e,t)=>kn(e,t),"number"),spec:s((e,t)=>Sn(e,t),"spec"),theme:s((e,t)=>Tn(e,t),"theme"),acl:s((e,t)=>En(e,t),"acl"),changelog:s((e,t)=>Sl(e,t),"changelog"),workflow:s((e,t)=>Dl(e,t),"workflow"),release:s((e,t)=>Tl(e,t),"release"),agentDoc:s((e,t)=>Il(e,t),"agentDoc")},vy=["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"];s(Vl,"versionOf");s(vt,"summary");s(V,"noFindings");s(Ey,"isFindingStatus");s(AA,"adaptNumber");s(IA,"adaptSpec");s(NA,"adaptTheme");s(OA,"adaptAcl");s(DA,"adaptChangelog");s(PA,"adaptWorkflow");s(MA,"adaptRelease");s($A,"adaptAgentDoc");hs={open:0,warn:1,info:2},wy={introduced:0,pre_existing:1};s(zl,"compareWire");s(ky,"capPriority");s(LA,"buildWire");s(FA,"deriveCoverage");s(Oe,"adaptDetectorReports");s(bt,"unavailableDetectorReports");s(Jl,"errorText");s(Lt,"attempt");s(Yl,"runRepoHealthDetectors");s(Xl,"runRepoHealthDetectorScopes");s(Ty,"insideWorkTree");s(Ry,"runSharedEngines");s(ql,"runNumberEngine")});var Cy,Ql=v(()=>{"use strict";Ol();Cy=[{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:oy},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function Ay(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Cy){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=jA(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function jA(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
42
+ `):t.readUntracked(e)}var Iy=v(()=>{"use strict";Ql();s(Ay,"scanRiskFlags");s(jA,"contentForPath")});var Ft,ed,jt,xr,Ni,Sr,td,gs,ys,_s,nd,Ny,Er=v(()=>{"use strict";Ft="3",ed=`
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
- `,It="schema_version",pr="last_index_commit",ki="last_indexed_at",mr="edges_dirty",Fl="resolve_config_fp",to="embed_recipe_version",no="embed_model",ro="embed_dim",jl="last_synced_at",my="last_synced_commit"});function Ul(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 hy(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of Ul(e.name))t.add(i);for(let i of Ul(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function gy(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 Ul(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Hl=_(()=>{"use strict";o(Ul,"splitIdentifier");o(hy,"buildSearchText");o(gy,"toFtsMatchQuery")});import{readFileSync as yy}from"node:fs";import{posix as _y}from"node:path";function by(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 vn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function wy(e){return e==="added"?0:e==="modified"?1:2}function uC(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 Si,Bl=_(()=>{"use strict";si();fh();bc();mh();_h();vc();Eh();fe();Mh();Oc();Bc();hi();Ml();bi();py();hr();Hl();Si=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(It),i=await this.store.countFiles()>0;(t.full||i&&r!==Ct)&&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 v=Ac(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(v===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");a=v}else a=Ih(this.repoRoot);let c=new Set(a.map(v=>v.path)),l=new Map(s.map(v=>[v.path,v])),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(mr,"1"))},"markEdgesDirty");for(let v of s)c.has(v.path)||(await p(),await this.store.deleteFile(v.path),u.filesDeleted++);let h=0;for(let v of a){h++;let k=Oh(this.repoRoot,v.path);if(!k){u.filesSkipped++;continue}let x=l.get(v.path);if(x&&x.mtimeMs===k.mtimeMs&&x.size===k.size){u.filesSkipped++;continue}let T=this.readRepoFile(v.path);if(T===null){u.filesSkipped++;continue}let b=js(T);if(x&&x.contentHash===b){await this.store.upsertFile({...x,mtimeMs:k.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let S=await this.parser.parse(v.path,T,v.language),N=new Map;for(let B of S.nodes)N.set(B.nodeKey,hy(B));let M={path:v.path,language:v.language,contentHash:b,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await p(),await this.store.replaceFileNodes(M,S.nodes,N,{contains:S.edges,refs:S.refs,imports:S.imports,exports:S.exports}),u.filesParsed++,t.onProgress?.({path:v.path,done:h,total:a.length})}let g=hh(this.repoRoot),y=await this.store.getMeta(Fl)!==g.fingerprint;if(f||y||await this.store.getMeta(mr)==="1"){let v=Sh(await this.store.getNameIndex()),k=new or(g.config,v.files),x=xh(await this.store.getAllFacts(),v,k);await this.store.replaceCrossFileEdges(x),await this.store.setMeta(Fl,g.fingerprint),await this.store.setMeta(mr,"0")}if(this.embedder&&t.embed){let v=await this.store.getNodesByKinds([..._c]),k=await this.store.getEmbeddingContentHashes(),x=[];for(let b of v){let S=uh(b),N=js(`${this.embedder.recipeVersion}\0${S}`);k.get(b.nodeKey)!==N&&x.push({nodeKey:b.nodeKey,text:S,hash:N})}let T=64;for(let b=0;b<x.length;b+=T){let S=x.slice(b,b+T),N=await this.embedder.embedDocuments(S.map(B=>B.text));await this.store.upsertEmbeddings(S.map((B,P)=>({nodeKey:B.nodeKey,dim:this.embedder.dim,vec:N[P],contentHash:B.hash})));let M=Math.min(b+T,x.length);t.onProgress?.({path:"embedding symbols",done:M,total:x.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(to,this.embedder.recipeVersion),await this.store.setMeta(no,this.embedder.model),await this.store.setMeta(ro,String(this.embedder.dim))}await this.store.setMeta(It,Ct),await this.store.setMeta(ki,String(n));let w=di(this.repoRoot);return w&&await this.store.setMeta(pr,w),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(ki);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(pr),schemaVersion:await this.store.getMeta(It),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=vn(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({...by(c),score:a.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=vn(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:ph(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({...by(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=vn(n.maxDepth,3,5),s=vn(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 w=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(w))continue;if(l.add(w),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let v=r==="out"?y.dstKey:y.srcKey;d.has(v)||(d.add(v),p.push(v))}}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=yy(_y.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(vn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Ac(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=vn(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=Fs(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(di(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Hh(this.repoRoot,n,t)}async checkDivergence(t={}){return pi(this.repoRoot,t)}async checkNumberCollisions(t={}){return gn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return yn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return _n(this.repoRoot,t)}async reviewDetectors(t={}){return Dl(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Pl(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Fs(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Ph(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",a=fy({paths:n,hunks:i,readUntracked:o(p=>this.readRepoFileHead(p,Dh),"readUntracked")}),c=Ch(n.keys()),l=vn(t.limit,64,t.attest?Et: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),w=g!==null&&y!==null&&js(y)!==g.contentHash;w&&(f++,s==="full"&&(s="partial"));let v=n.get(p.path)??"modified",k=i.get(p.path);for(let x of h)d.push(uC(x,v,k,w))}return d.sort((p,h)=>wy(p.change)-wy(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:di(this.repoRoot),dirty:Cc(this.repoRoot),baseSha:t.since?Us(this.repoRoot,t.since):null,mergeBaseSha:t.since?Rc(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 yy(_y.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(by,"toHit");o(vn,"clampLimit");o(wy,"changeRank");o(uC,"classifyReviewSymbol")});var vy=_(()=>{"use strict";fe()});var fC,UW,ky=_(()=>{"use strict";fe();fC=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],UW=new RegExp(fC.join("|"),"g")});import{existsSync as Gl,readdirSync as pC,readFileSync as mC}from"node:fs";import{spawnSync as hC}from"node:child_process";import{dirname as gC,join as io,posix as Kl}from"node:path";function xy(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 ${Wl} 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 ${Wl} 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(at);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(at),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(at),h=e.remote.versions.filter(g=>!s.has(g)).sort(at);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 Ey(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Ry(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 Sy(e,t,n){let r=e(t,yC,n);return r.ok===!1?Ry(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
132
- `).map(i=>i.trim()).filter(Boolean)}}function Ay(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 _C(e){let t=C(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=gC(t);return n===e?null:n}function bC(e,t,n){let r=Kl.dirname(t),s=[{path:io(e,r,"config.toml"),source:"worktree"}],a=_C(e);a&&s.push({path:io(a,r,"config.toml"),source:"main_worktree"});for(let c of s)if(Gl(c.path))try{let l=Ay(mC(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 wC(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||!Gl(a))continue;let c=io(a,t);if(Gl(c))try{for(let l of pC(c)){let d=cr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function Vl(e,t={}){let n=t.runPsql??Ty,r=t.timeoutMs??15e3,i=[],s=hn(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=bC(e,f.dir,i),h=p.source==="missing"?null:Sy(n,`postgresql://postgres:postgres@127.0.0.1:${p.port}/postgres`,r),g=t.remoteDbUrl!==void 0?Sy(n,t.remoteDbUrl,r):null,y=xy({dir:f.dir,projectRoot:io(e,Kl.dirname(Kl.dirname(f.dir))),fileVersions:f.files.map(w=>w.version),config:p,ledger:h,siblingVersions:wC(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=Ey(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 Wl,Ty,yC,Cy=_(()=>{"use strict";fe();fi();Wl=54322;o(xy,"evaluateLedgerProject");o(Ey,"deriveLedgerVerdict");Ty=o((e,t,n)=>{let r=hC("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"),yC="select version from supabase_migrations.schema_migrations order by version";o(Ry,"classifyLedgerError");o(Sy,"readLedger");o(Ay,"parseDbPort");o(_C,"mainWorktreeRoot");o(bC,"resolveConfig");o(wC,"gatherSiblingVersions");o(Vl,"checkMigrationLedgerDrift")});function Ae(e){return typeof e=="string"?e:String(e??"")}function xi(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function zl(e){return{nodeKey:Ae(e.node_key),kind:Ae(e.kind),name:Ae(e.name),qualifiedName:Ae(e.qualified_name),filePath:Ae(e.file_path),startLine:xi(e.start_line),endLine:xi(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function Oy(e){return{path:Ae(e.path),language:Ae(e.language),contentHash:Ae(e.content_hash),mtimeMs:xi(e.mtime_ms),size:xi(e.size),indexedAt:xi(e.indexed_at)}}function ql(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(Nt.meta).get(i);return s===void 0?null:Ae(s.value)},"metaValue");return{meta(){let i=r(It),s=r(ki);return{schemaVersion:i,schemaCurrent:i===Ct,edgesDirty:r(mr)==="1",lastIndexedAt:s===null?null:Number(s)}},file(i){let s=n(Nt.file).get(i);return s===void 0?null:Oy(s)},files(i){let s=new Map;for(let a of new Set(i)){let c=n(Nt.file).get(a);c!==void 0&&s.set(a,Oy(c))}return s},symbolsInFile(i,s=vC){return n(Nt.symbolsInFile).all(i,s).map(zl)},symbolsNamed(i,s=kC){let a=new Map;for(let c of new Set(i)){let l=n(Nt.symbolsNamed).all(c,s);l.length>0&&a.set(c,l.map(zl))}return a},callersOfFile(i,s=SC){return n(Nt.callersOfFile).all(i,i,s).map(c=>({calleeKey:Ae(c.callee_key),kind:Ae(c.edge_kind),caller:zl(c)}))},importersOf(i,s=xC){let a=n(Nt.importersOf).all(qe(i),s),c=[];for(let l of a){let d=Ae(l.src_key),u=d.endsWith(Ny)?d.slice(0,-Ny.length):d;u!==i&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function Ei(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var Iy,Nt,vC,kC,SC,xC,Ny,Jl=_(()=>{"use strict";mn();hr();Iy="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",Nt={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 ${Iy} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${Iy} 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 ?"},vC=400,kC=8,SC=600,xC=200,Ny="#<module>";o(Ae,"str");o(xi,"num");o(zl,"toSymbol");o(Oy,"toFileRow");o(ql,"createIndexReader");o(Ei,"isFileCurrent")});var Yl,Xl=_(()=>{"use strict";Yl="0.2.0"});function Zl(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:Et,attest:!0}}function Ql(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>so||a!==void 0&&a.length>oo){n+=1;continue}r.push({name:s.name,...a!==void 0?{qualified_name:a}:{},...s.kind&&s.kind.length<=Py?{kind:s.kind}:{},...s.language&&s.language.length<=My?{language:s.language}:{},change:s.change,changed_line_count:Math.min(Math.max(0,s.changedLineCount),$y)})}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:Yl},dropped:n}}function ed(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 td(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 ${Et} (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 nd(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===Dy&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===Dy?{kind:"invalid_params",code:n,detail:r,issues:EC(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function EC(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 rd(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 so,oo,Py,My,$y,Dy,TC,Ly=_(()=>{"use strict";si();Xl();so=200,oo=512,Py=64,My=32,$y=1e4;o(Zl,"attestReviewOptions");o(Ql,"buildAttestPayload");o(ed,"attestPersistDecision");o(td,"attestCoverageNote");Dy=-32602;o(nd,"classifyMcpErrorText");o(EC,"parseIssues");o(rd,"isLegacyAttestRejection");TC=`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 Ot=_(()=>{"use strict";ip();Bl();Oc();$l();fe();Ys();yl();dl();ml();Bc();vy();ky();$c();hi();Qs();bi();fi();Zs();Cy();nl();Ml();hi();bi();Qs();Zs();Ps();bc();hr();Jl();$s();Xl();Ly()});import{execFileSync as RC}from"node:child_process";import{createHash as AC}from"node:crypto";import{mkdirSync as CC,readFileSync as IC,renameSync as NC,writeFileSync as OC}from"node:fs";import{dirname as Fy,join as jy}from"node:path";function ft(e=process.cwd()){try{let t=RC("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 gr(e){return AC("sha256").update(e).digest("hex").slice(0,16)}function ao(e){return jy(e,DC)}function Uy(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Hy(e,t,n,r=new Date().toISOString()){try{if(!Uy(n))return;let i={version:id,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},s=ao(e);CC(Fy(s),{recursive:!0}),li(Fy(s));let a=`${s}.${process.pid}.tmp`;OC(a,JSON.stringify(i,null,2),"utf8"),NC(a,s)}catch{}}function co(e,t){try{let n=IC(ao(e),"utf8"),r=JSON.parse(n);return r.version!==id||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Uy(r.result)?null:{version:id,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function By(e,t,n=new Date){let r=PC(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 PC(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${MC(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function MC(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 id,DC,Dt=_(()=>{"use strict";Ot();id=1,DC=jy(".maind","conventions-cache.json");o(ft,"resolveRepoRoot");o(gr,"keyFingerprint");o(ao,"cachePath");o(Uy,"hasInstructions");o(Hy,"writeConventionsCache");o(co,"readConventionsCache");o(By,"buildCachedInitializeResponse");o(PC,"fallbackMarker");o(MC,"relativeAge")});import{existsSync as po,mkdirSync as VC,readFileSync as Wy,writeFileSync as ld,chmodSync as Vy}from"node:fs";import{homedir as zC,hostname as qC,platform as cd,release as JC}from"node:os";import{randomUUID as YC}from"node:crypto";import{join as kn}from"node:path";function je(){let e=zC(),t=process.env;if(cd()==="darwin")return kn(e,"Library","Application Support","maind");if(cd()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:kn(e,"AppData","Roaming");return kn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:kn(e,".config");return kn(n,"maind")}function zy(e){po(e)||VC(e,{recursive:!0,mode:448})}function re(){let e=je();zy(e);let t=kn(e,XC);if(po(t)){let r=Wy(t,"utf8").trim();if(eI(r))return r}let n=YC();ld(t,n+`
136
- `,{encoding:"utf8",mode:384});try{Vy(t,384)}catch{}return n}function eI(e){return QC.test(e)}function dd(){return kn(je(),ZC)}function Sn(e){let t=je();zy(t);let n=dd();ld(n,e+`
137
- `,{encoding:"utf8",mode:384});try{Vy(n,384)}catch{}}function q(){let e=dd();if(!po(e))return null;let t=Wy(e,"utf8").trim();return t.length>0?t:null}function Ri(){let e=dd();po(e)&&ld(e,"",{encoding:"utf8",mode:384})}function qy(){try{return`mcp-bridge-${qC()}`}catch{return"mcp-bridge"}}function mo(e){return{os:`${cd()} ${JC()}`,ide:"mcp-bridge",ext_version:e,device_id:re()}}var XC,ZC,QC,ie=_(()=>{"use strict";o(je,"configDir");o(zy,"ensureDir");XC="device-id",ZC="api-key";o(re,"ensureDeviceId");QC=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(eI,"isUuid");o(dd,"apiKeyPath");o(Sn,"writeApiKey");o(q,"readApiKey");o(Ri,"clearApiKey");o(qy,"bridgeLabel");o(mo,"clientMeta")});function Ai(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:tI}function _r(e){return`${Ai()}/${e.replace(/^\/+/,"")}`}var tI,br=_(()=>{"use strict";tI="https://fn.maind.dev/functions/v1";o(Ai,"functionsOrigin");o(_r,"functionsUrl")});import{mkdirSync as cI,readFileSync as lI,renameSync as dI,writeFileSync as uI}from"node:fs";import{join as fI}from"node:path";function Yy(e=je()){return fI(e,mI)}function gI(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,hI)}function xn(e,t,n){try{let r=n.dir??je();cI(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:gI(t),bridge_version:n.version},s=Yy(r),a=`${s}.${process.pid}.tmp`;uI(a,JSON.stringify(i)+`
138
- `,{encoding:"utf8",mode:384}),dI(a,s)}catch{}}function Xy(e=je()){try{let t=JSON.parse(lI(Yy(e),"utf8"));return t.v!==1||typeof t.at!="string"||!pI.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 pI,mI,hI,ud=_(()=>{"use strict";ie();pI=["ok","paired","auth_failed","not_paired"],mI="connection-state.json",hI=200;o(Yy,"connectionStatePath");o(gI,"redactDetail");o(xn,"writeConnectionState");o(Xy,"readConnectionState")});var G,Ue=_(()=>{"use strict";G="0.93.0"});import{execFileSync as Zy}from"node:child_process";import{createHash as yI}from"node:crypto";function _I(e){return yI("sha256").update(e).digest("hex")}function bI(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 vr(e){let t=bI(e);return t?_I(t):null}function Y(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&wI.test(e))return e;let t;try{t=Zy("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?vr(t):null}function Pt(e){let t;try{t=Zy("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?vr(t):null}var wI,ge=_(()=>{"use strict";o(_I,"sha256Hex");o(bI,"normalizeRemoteUrl");o(vr,"projectKeyFromRemote");wI=/^[a-f0-9]{64}$/;o(Y,"computeProjectKey");o(Pt,"projectKeyForRepo")});import vI from"node:path";import{fileURLToPath as kI}from"node:url";function SI(e,t=vI.sep){return e.split(t).includes("_npx")}function ye(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",e_,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):SI(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 _e(){try{let e=kI(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Xe(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Qy(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Qy(n)).join(" ")}function kr(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(e_)}function ho(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Qy(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var e_,Mt=_(()=>{"use strict";e_="@maind-dev/mcp-bridge";o(SI,"isEphemeralEntry");o(ye,"resolveBridgeLaunch");o(_e,"currentBridgeEntry");o(Xe,"launchToShellCommand");o(kr,"isNpxForm");o(ho,"isLegacyHookForm");o(Qy,"shellQuote")});import*as H from"node:path";function n_(e){let t=e.launch??ye({entryPath:_e(),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 EI(e){switch(e.platform){case"darwin":return H.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??H.join(e.homeDir,".config");return H.join(t,"Claude","claude_desktop_config.json")}}}function pd(e,t){switch(e.platform){case"darwin":return H.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(n,t)}default:{let n=e.xdgConfigHome??H.join(e.homeDir,".config");return H.join(n,t)}}}function TI(e){return H.join(pd(e,"Code"),"User")}function yo(e,t,n=[]){return{kind:"foreign-entries",dir:pd(e,t),ours:["User",...n]}}function Ci(e){return{evidence:[yo(e,"Cursor"),{kind:"foreign-entries",dir:H.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function r_(e){if(e.platform==="win32"){let t=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(t,"devin")}return H.join(e.xdgConfigHome??H.join(e.homeDir,".config"),"devin")}function RI(e){return H.join(r_(e),"mcp_config.json")}function i_(e){return H.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function t_(e){let t=[yo(e,"Devin",["mcp_config.json"]),{kind:"dir",path:H.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:r_(e),ours:["mcp_config.json"]}),t.push(yo(e,"Windsurf"),{kind:"foreign-entries",dir:H.dirname(i_(e)),ours:["mcp_config.json"]}),{evidence:t,skipDetail:"Devin Desktop (formerly Windsurf) not found (no Devin or Windsurf app data, nothing of theirs in ~/.devin, Devin's config dir or ~/.codeium/windsurf)"}}function s_(e){return e.clineDataDir?e.clineDataDir:H.join(e.clineDir??H.join(e.homeDir,".cline"),"data")}function CI(e){return e.clineMcpSettingsPath??H.join(s_(e),"settings","cline_mcp_settings.json")}function II(e){return{evidence:[{kind:"foreign-entries",dir:s_(e),ours:["settings"]},...AI.map(t=>({kind:"dir",path:H.join(pd(e,t),"User","globalStorage","saoudrizwan.claude-dev")}))],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline storage in any editor)"}}function o_(e){return e.continueGlobalDir??H.join(e.homeDir,".continue")}function NI(e){return H.join(o_(e),"mcpServers","maind.json")}function OI(e){return{evidence:[{kind:"foreign-entries",dir:o_(e),ours:["mcpServers"]}],skipDetail:"Continue not found (nothing of Continue's in ~/.continue)"}}function DI(e){return H.join(TI(e),"mcp.json")}function Ii(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:H.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:H.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:EI(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:H.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Ci(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:RI(e),kind:"json",presence:t_(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:i_(e),kind:"json",presence:t_(e),refreshOnly:{skipDetail:"no maind entry here to keep current \u2014 Devin Desktop's own file is the windsurf row"}},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:DI(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{evidence:[yo(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:CI(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:II(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:NI(e),kind:"json",presence:OI(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:H.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function a_(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function c_(e){return e.jsonShape??xI}function Ni(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:fd(e.env.XDG_CONFIG_HOME),appData:fd(e.env.APPDATA),clineDir:go(e.env.CLINE_DIR),clineDataDir:go(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:go(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:go(e.env.CONTINUE_GLOBAL_DIR)}}function fd(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function go(e){let t=fd(e);return t!==null&&H.isAbsolute(t)?t:null}var xI,AI,md,En=_(()=>{"use strict";Mt();xI={serversKey:"mcpServers"};o(n_,"buildMaindServerEntry");o(EI,"claudeDesktopConfigPath");o(pd,"editorAppDataDir");o(TI,"vsCodeUserDir");o(yo,"editorRan");o(Ci,"cursorPresence");o(r_,"devinConfigDir");o(RI,"devinMcpConfigPath");o(i_,"windsurfLegacyMcpConfigPath");o(t_,"devinDesktopPresence");AI=["Code","Code - Insiders","Cursor","VSCodium","Windsurf","Devin","AgentComposer"];o(s_,"clineDataDir");o(CI,"clineMcpSettingsPath");o(II,"clinePresence");o(o_,"continueGlobalDir");o(NI,"continueMcpConfigPath");o(OI,"continuePresence");o(DI,"vsCodeUserMcpPath");o(Ii,"getClientTargets");o(a_,"filterTargetsByFamily");o(c_,"jsonShapeOf");md=[...new Set(Ii({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];o(Ni,"makeDefaultContext");o(fd,"nonEmpty");o(go,"absoluteOrNull")});import*as u_ from"node:fs/promises";import*as $t from"node:path";import*as f_ from"node:readline";async function p_(e){let t=$t.resolve(e),n=t;for(;;){if(await m_(n))return n;let r=$t.dirname(n);if(r===n)return t;n=r}}async function bo(e){let n=$t.resolve(e),r=[];for(;;){await m_(n)&&r.push(n);let i=$t.dirname(n);if(i===n)break;n=i}return r}async function m_(e){for(let t of MI)try{return await u_.access($t.join(e,t)),!0}catch{}return!1}async function h_(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
130
+ `,jt="schema_version",xr="last_index_commit",Ni="last_indexed_at",Sr="edges_dirty",td="resolve_config_fp",gs="embed_recipe_version",ys="embed_model",_s="embed_dim",nd="last_synced_at",Ny="last_synced_commit"});function rd(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 Oy(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of rd(e.name))t.add(i);for(let i of rd(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Dy(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 rd(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var id=v(()=>{"use strict";s(rd,"splitIdentifier");s(Oy,"buildSearchText");s(Dy,"toFtsMatchQuery")});import{readFileSync as Py}from"node:fs";import{posix as My}from"node:path";function $y(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 Rn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function Ly(e){return e==="added"?0:e==="modified"?1:2}function HA(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 o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Oi,od=v(()=>{"use strict";mi();Ah();$c();Nh();Mh();Fc();Bh();_e();Zh();Jc();ol();Si();Zl();Ci();Iy();Er();id();Oi=class{static{s(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(jt),i=await this.store.countFiles()>0;(t.full||i&&r!==Ft)&&await this.wipe();let o=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(o.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 b=Wc(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(b===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");a=b}else a=zh(this.repoRoot);let c=new Set(a.map(b=>b.path)),l=new Map(o.map(b=>[b.path,b])),d=o.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=s(async()=>{p||(p=!0,await this.store.setMeta(Sr,"1"))},"markEdgesDirty");for(let b of o)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of a){m++;let k=Jh(this.repoRoot,b.path);if(!k){u.filesSkipped++;continue}let S=l.get(b.path);if(S&&S.mtimeMs===k.mtimeMs&&S.size===k.size){u.filesSkipped++;continue}let T=this.readRepoFile(b.path);if(T===null){u.filesSkipped++;continue}let w=es(T);if(S&&S.contentHash===w){await this.store.upsertFile({...S,mtimeMs:k.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let x=await this.parser.parse(b.path,T,b.language),N=new Map;for(let B of x.nodes)N.set(B.nodeKey,Oy(B));let L={path:b.path,language:b.language,contentHash:w,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await f(),await this.store.replaceFileNodes(L,x.nodes,N,{contains:x.edges,refs:x.refs,imports:x.imports,exports:x.exports}),u.filesParsed++,t.onProgress?.({path:b.path,done:m,total:a.length})}let g=Oh(this.repoRoot),y=await this.store.getMeta(td)!==g.fingerprint;if(p||y||await this.store.getMeta(Sr)==="1"){let b=Hh(await this.store.getNameIndex()),k=new gr(g.config,b.files),S=Uh(await this.store.getAllFacts(),b,k);await this.store.replaceCrossFileEdges(S),await this.store.setMeta(td,g.fingerprint),await this.store.setMeta(Sr,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...Mc]),k=await this.store.getEmbeddingContentHashes(),S=[];for(let w of b){let x=Ch(w),N=es(`${this.embedder.recipeVersion}\0${x}`);k.get(w.nodeKey)!==N&&S.push({nodeKey:w.nodeKey,text:x,hash:N})}let T=64;for(let w=0;w<S.length;w+=T){let x=S.slice(w,w+T),N=await this.embedder.embedDocuments(x.map(B=>B.text));await this.store.upsertEmbeddings(x.map((B,P)=>({nodeKey:B.nodeKey,dim:this.embedder.dim,vec:N[P],contentHash:B.hash})));let L=Math.min(w+T,S.length);t.onProgress?.({path:"embedding symbols",done:L,total:S.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(gs,this.embedder.recipeVersion),await this.store.setMeta(ys,this.embedder.model),await this.store.setMeta(_s,String(this.embedder.dim))}await this.store.setMeta(jt,Ft),await this.store.setMeta(Ni,String(n));let _=bi(this.repoRoot);return _&&await this.store.setMeta(xr,_),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 o of n)r[o.language]=o.count;let i=await this.store.getMeta(Ni);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(xr),schemaVersion:await this.store.getMeta(jt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Rn(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...$y(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Rn(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Ih(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({...$y(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Rn(n.maxDepth,3,5),o=Rn(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 m of u){let g=await this.store.neighbors(m,r,a,o);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=o)return c;let b=r==="out"?y.dstKey:y.srcKey;d.has(b)||(d.add(b),f.push(b))}}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=Py(My.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 o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(Rn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Wc(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Rn(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Qo(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(bi(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return ig(this.repoRoot,n,t)}async checkDivergence(t={}){return ki(this.repoRoot,t)}async checkNumberCollisions(t={}){return kn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return xn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Sn(this.repoRoot,t)}async reviewDetectors(t={}){return Yl(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Xl(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Qo(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Xh(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Ay({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,Yh),"readUntracked")}),c=Vh(n.keys()),l=Rn(t.limit,64,t.attest?Pt:200),d=[],u=0,p=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;u++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),_=g!==null&&y!==null&&es(y)!==g.contentHash;_&&(p++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",k=i.get(f.path);for(let S of m)d.push(HA(S,b,k,_))}return d.sort((f,m)=>Ly(f.change)-Ly(m.change)||(f.filePath<m.filePath?-1:f.filePath>m.filePath?1:0)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:bi(this.repoRoot),dirty:Vc(this.repoRoot),baseSha:t.since?ts(this.repoRoot,t.since):null,mergeBaseSha:t.since?Kc(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 Py(My.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};s($y,"toHit");s(Rn,"clampLimit");s(Ly,"changeRank");s(HA,"classifyReviewSymbol")});var Fy=v(()=>{"use strict";_e()});var UA,X2,jy=v(()=>{"use strict";_e();UA=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],X2=new RegExp(UA.join("|"),"g")});import{existsSync as sd,readdirSync as BA,readFileSync as GA}from"node:fs";import{spawnSync as KA}from"node:child_process";import{dirname as WA,join as bs,posix as ad}from"node:path";function Uy(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 ${cd} 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 ${cd} 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),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(gt);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=>!o.has(p)).sort(gt),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}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(gt),m=e.remote.versions.filter(g=>!o.has(g)).sort(gt);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}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.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:m})}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 By(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Ky(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 Hy(e,t,n){let r=e(t,VA,n);return r.ok===!1?Ky(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
132
+ `).map(i=>i.trim()).filter(Boolean)}}function Wy(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 zA(e){let t=A(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=WA(t);return n===e?null:n}function qA(e,t,n){let r=ad.dirname(t),o=[{path:bs(e,r,"config.toml"),source:"worktree"}],a=zA(e);a&&o.push({path:bs(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(sd(c.path))try{let l=Wy(GA(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 JA(e,t){let n=new Map,r=A(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=A(e,["rev-parse","--show-toplevel"])?.trim();for(let o of r.split(`
133
+ `)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!sd(a))continue;let c=bs(a,t);if(sd(c))try{for(let l of BA(c)){let d=_r(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function ld(e,t={}){let n=t.runPsql??Gy,r=t.timeoutMs??15e3,i=[],o=wn(e,t.dirs);if(o.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 o){let f=qA(e,p.dir,i),m=f.source==="missing"?null:Hy(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?Hy(n,t.remoteDbUrl,r):null,y=Uy({dir:p.dir,projectRoot:bs(e,ad.dirname(ad.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:JA(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=By(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 cd,Gy,VA,Vy=v(()=>{"use strict";_e();wi();cd=54322;s(Uy,"evaluateLedgerProject");s(By,"deriveLedgerVerdict");Gy=s((e,t,n)=>{let r=KA("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"),VA="select version from supabase_migrations.schema_migrations order by version";s(Ky,"classifyLedgerError");s(Hy,"readLedger");s(Wy,"parseDbPort");s(zA,"mainWorktreeRoot");s(qA,"resolveConfig");s(JA,"gatherSiblingVersions");s(ld,"checkMigrationLedgerDrift")});function De(e){return typeof e=="string"?e:String(e??"")}function Di(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function dd(e){return{nodeKey:De(e.node_key),kind:De(e.kind),name:De(e.name),qualifiedName:De(e.qualified_name),filePath:De(e.file_path),startLine:Di(e.start_line),endLine:Di(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function Jy(e){return{path:De(e.path),language:De(e.language),contentHash:De(e.content_hash),mtimeMs:Di(e.mtime_ms),size:Di(e.size),indexedAt:Di(e.indexed_at)}}function ud(e){let t=new Map,n=s(i=>{let o=t.get(i);return o===void 0&&(o=e.prepare(i),t.set(i,o)),o},"stmt"),r=s(i=>{let o=n(Ht.meta).get(i);return o===void 0?null:De(o.value)},"metaValue");return{meta(){let i=r(jt),o=r(Ni);return{schemaVersion:i,schemaCurrent:i===Ft,edgesDirty:r(Sr)==="1",lastIndexedAt:o===null?null:Number(o)}},file(i){let o=n(Ht.file).get(i);return o===void 0?null:Jy(o)},files(i){let o=new Map;for(let a of new Set(i)){let c=n(Ht.file).get(a);c!==void 0&&o.set(a,Jy(c))}return o},symbolsInFile(i,o=YA){return n(Ht.symbolsInFile).all(i,o).map(dd)},symbolsNamed(i,o=XA){let a=new Map;for(let c of new Set(i)){let l=n(Ht.symbolsNamed).all(c,o);l.length>0&&a.set(c,l.map(dd))}return a},callersOfFile(i,o=ZA){return n(Ht.callersOfFile).all(i,i,o).map(c=>({calleeKey:De(c.callee_key),kind:De(c.edge_kind),caller:dd(c)}))},importersOf(i,o=QA){let a=n(Ht.importersOf).all(Qe(i),o),c=[];for(let l of a){let d=De(l.src_key),u=d.endsWith(qy)?d.slice(0,-qy.length):d;u!==i&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function Pi(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var zy,Ht,YA,XA,ZA,QA,qy,pd=v(()=>{"use strict";vn();Er();zy="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",Ht={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 ${zy} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${zy} 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 ?"},YA=400,XA=8,ZA=600,QA=200,qy="#<module>";s(De,"str");s(Di,"num");s(dd,"toSymbol");s(Jy,"toFileRow");s(ud,"createIndexReader");s(Pi,"isFileCurrent")});var fd,md=v(()=>{"use strict";fd="0.2.0"});function hd(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:Pt,attest:!0}}function gd(e,t){let n=0,r=[];for(let o of e.symbols){let a=o.qualifiedName?o.qualifiedName:void 0;if(o.name.length===0||o.name.length>vs||a!==void 0&&a.length>ws){n+=1;continue}r.push({name:o.name,...a!==void 0?{qualified_name:a}:{},...o.kind&&o.kind.length<=Xy?{kind:o.kind}:{},...o.language&&o.language.length<=Zy?{language:o.language}:{},change:o.change,changed_line_count:Math.min(Math.max(0,o.changedLineCount),Qy)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(o=>({detector_id:o.detector_id,detector_version:o.detector_version,state:o.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:fd},dropped:n}}function yd(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 _d(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 o=e.changedFiles-e.indexedFiles;return o>0&&i.push(`${o} 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 ${Pt} (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 bd(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===Yy&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===Yy?{kind:"invalid_params",code:n,detail:r,issues:eI(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function eI(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 vd(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 vs,ws,Xy,Zy,Qy,Yy,tI,e_=v(()=>{"use strict";mi();md();vs=200,ws=512,Xy=64,Zy=32,Qy=1e4;s(hd,"attestReviewOptions");s(gd,"buildAttestPayload");s(yd,"attestPersistDecision");s(_d,"attestCoverageNote");Yy=-32602;s(bd,"classifyMcpErrorText");s(eI,"parseIssues");s(vd,"isLegacyAttestRejection");tI=`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 Ut=v(()=>{"use strict";wf();od();Jc();Ql();_e();us();Pl();Rl();Nl();ol();Fy();jy();Qc();Si();ms();Ci();wi();fs();Vy();bl();Zl();Si();Ci();ms();fs();Jo();$c();Er();pd();Xo();md();e_()});import{execFileSync as nI}from"node:child_process";import{createHash as rI}from"node:crypto";import{mkdirSync as iI,readFileSync as oI,renameSync as sI,writeFileSync as aI}from"node:fs";import{dirname as t_,join as n_}from"node:path";function wt(e=process.cwd()){try{let t=nI("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 Tr(e){return rI("sha256").update(e).digest("hex").slice(0,16)}function ks(e){return n_(e,cI)}function r_(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function i_(e,t,n,r=new Date().toISOString()){try{if(!r_(n))return;let i={version:wd,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=ks(e);iI(t_(o),{recursive:!0}),_i(t_(o));let a=`${o}.${process.pid}.tmp`;aI(a,JSON.stringify(i,null,2),"utf8"),sI(a,o)}catch{}}function xs(e,t){try{let n=oI(ks(e),"utf8"),r=JSON.parse(n);return r.version!==wd||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!r_(r.result)?null:{version:wd,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function o_(e,t,n=new Date){let r=lI(t.cached_at,n),i=t.result.instructions??"",o={...t.result,instructions:`${r}
134
+
135
+ ${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function lI(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${dI(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function dI(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 o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let a=Math.floor(o/24);return`${a} day${a===1?"":"s"} ago`}var wd,cI,Bt=v(()=>{"use strict";Ut();wd=1,cI=n_(".maind","conventions-cache.json");s(wt,"resolveRepoRoot");s(Tr,"keyFingerprint");s(ks,"cachePath");s(r_,"hasInstructions");s(i_,"writeConventionsCache");s(xs,"readConventionsCache");s(o_,"buildCachedInitializeResponse");s(lI,"fallbackMarker");s(dI,"relativeAge")});import{existsSync as Rs,mkdirSync as wI,readFileSync as c_,writeFileSync as Td,chmodSync as l_}from"node:fs";import{homedir as kI,hostname as xI,platform as Ed,release as SI}from"node:os";import{randomUUID as EI}from"node:crypto";import{join as Cn}from"node:path";function Be(){let e=kI(),t=process.env;if(Ed()==="darwin")return Cn(e,"Library","Application Support","maind");if(Ed()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Cn(e,"AppData","Roaming");return Cn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Cn(e,".config");return Cn(n,"maind")}function d_(e){Rs(e)||wI(e,{recursive:!0,mode:448})}function oe(){let e=Be();d_(e);let t=Cn(e,TI);if(Rs(t)){let r=c_(t,"utf8").trim();if(AI(r))return r}let n=EI();Td(t,n+`
136
+ `,{encoding:"utf8",mode:384});try{l_(t,384)}catch{}return n}function AI(e){return CI.test(e)}function Rd(){return Cn(Be(),RI)}function An(e){let t=Be();d_(t);let n=Rd();Td(n,e+`
137
+ `,{encoding:"utf8",mode:384});try{l_(n,384)}catch{}}function J(){let e=Rd();if(!Rs(e))return null;let t=c_(e,"utf8").trim();return t.length>0?t:null}function $i(){let e=Rd();Rs(e)&&Td(e,"",{encoding:"utf8",mode:384})}function u_(){try{return`mcp-bridge-${xI()}`}catch{return"mcp-bridge"}}function Cs(e){return{os:`${Ed()} ${SI()}`,ide:"mcp-bridge",ext_version:e,device_id:oe()}}var TI,RI,CI,se=v(()=>{"use strict";s(Be,"configDir");s(d_,"ensureDir");TI="device-id",RI="api-key";s(oe,"ensureDeviceId");CI=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(AI,"isUuid");s(Rd,"apiKeyPath");s(An,"writeApiKey");s(J,"readApiKey");s($i,"clearApiKey");s(u_,"bridgeLabel");s(Cs,"clientMeta")});function Li(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:II}function Cr(e){return`${Li()}/${e.replace(/^\/+/,"")}`}var II,Ar=v(()=>{"use strict";II="https://fn.maind.dev/functions/v1";s(Li,"functionsOrigin");s(Cr,"functionsUrl")});import{mkdirSync as LI,readFileSync as FI,renameSync as jI,writeFileSync as HI}from"node:fs";import{join as UI}from"node:path";function f_(e=Be()){return UI(e,GI)}function WI(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,KI)}function In(e,t,n){try{let r=n.dir??Be();LI(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:WI(t),bridge_version:n.version},o=f_(r),a=`${o}.${process.pid}.tmp`;HI(a,JSON.stringify(i)+`
138
+ `,{encoding:"utf8",mode:384}),jI(a,o)}catch{}}function m_(e=Be()){try{let t=JSON.parse(FI(f_(e),"utf8"));return t.v!==1||typeof t.at!="string"||!BI.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 BI,GI,KI,Cd=v(()=>{"use strict";se();BI=["ok","paired","auth_failed","not_paired"],GI="connection-state.json",KI=200;s(f_,"connectionStatePath");s(WI,"redactDetail");s(In,"writeConnectionState");s(m_,"readConnectionState")});var K,Ge=v(()=>{"use strict";K="0.95.0"});import{execFileSync as h_}from"node:child_process";import{createHash as VI}from"node:crypto";function zI(e){return VI("sha256").update(e).digest("hex")}function qI(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 Nr(e){let t=qI(e);return t?zI(t):null}function Y(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&JI.test(e))return e;let t;try{t=h_("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Nr(t):null}function nt(e){let t;try{t=h_("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Nr(t):null}var JI,we=v(()=>{"use strict";s(zI,"sha256Hex");s(qI,"normalizeRemoteUrl");s(Nr,"projectKeyFromRemote");JI=/^[a-f0-9]{64}$/;s(Y,"computeProjectKey");s(nt,"projectKeyForRepo")});import YI from"node:path";import{fileURLToPath as XI}from"node:url";function ZI(e,t=YI.sep){return e.split(t).includes("_npx")}function ke(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",y_,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):ZI(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 he(){try{let e=XI(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function rt(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${g_(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:g_(n)).join(" ")}function Or(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(y_)}function As(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function g_(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var y_,Gt=v(()=>{"use strict";y_="@maind-dev/mcp-bridge";s(ZI,"isEphemeralEntry");s(ke,"resolveBridgeLaunch");s(he,"currentBridgeEntry");s(rt,"launchToShellCommand");s(Or,"isNpxForm");s(As,"isLegacyHookForm");s(g_,"shellQuote")});import*as $ from"node:path";function v_(e){let t=e.launch??ke({entryPath:he(),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 k_(e){return Ds(e,"Claude")}function eN(e){return $.join(k_(e),w_)}function Ds(e,t){switch(e.platform){case"darwin":return $.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??$.join(e.homeDir,"AppData","Roaming");return $.join(n,t)}default:{let n=e.xdgConfigHome??$.join(e.homeDir,".config");return $.join(n,t)}}}function tN(e){return $.join(Ds(e,"Code"),"User")}function Ns(e,t,n=[]){return{kind:"foreign-entries",dir:Ds(e,t),ours:["User",...n]}}function __(e){return e.localAppData??$.join(e.homeDir,"AppData","Local")}function rN(e){let t=[{kind:"foreign-entries",dir:k_(e),ours:[w_]}];return e.platform==="darwin"?t.push({kind:"dir",path:$.join("/Applications","Claude.app")},{kind:"dir",path:$.join(e.homeDir,"Applications","Claude.app")}):e.platform==="win32"&&t.push({kind:"dir",path:$.join(__(e),"AnthropicClaude")},{kind:"dir",path:$.join(__(e),"Packages",nN)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Nn(e){return{evidence:[Ns(e,"Cursor"),{kind:"foreign-entries",dir:$.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function x_(e){if(e.platform==="win32"){let t=e.appData??$.join(e.homeDir,"AppData","Roaming");return $.join(t,"devin")}return $.join(e.xdgConfigHome??$.join(e.homeDir,".config"),"devin")}function iN(e){return $.join(x_(e),"mcp_config.json")}function S_(e){return $.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function Os(e){let t=[Ns(e,"Devin",["mcp_config.json"]),{kind:"dir",path:$.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:x_(e),ours:["mcp_config.json"]}),t.push(Ns(e,"Windsurf"),{kind:"foreign-entries",dir:$.dirname(S_(e)),ours:["mcp_config.json"]}),{evidence:t,skipDetail:"Devin Desktop (formerly Windsurf) not found (no Devin or Windsurf app data, nothing of theirs in ~/.devin, Devin's config dir or ~/.codeium/windsurf)"}}function lN(e){return e===null?null:cN.exec(e)?.[1]??null}function T_(e,t){let n=E_.map(r=>$.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push($.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of aN)for(let i of["/Applications",$.join(e.homeDir,"Applications")])n.push($.join(i,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function R_(e){return e.clineDataDir?e.clineDataDir:$.join(e.clineDir??$.join(e.homeDir,".cline"),"data")}function dN(e){return e.clineMcpSettingsPath??$.join(R_(e),"settings","cline_mcp_settings.json")}function uN(e){return{evidence:[{kind:"foreign-entries",dir:R_(e),ours:["settings"]},...oN.map(t=>({kind:"dir",path:$.join(Ds(e,t),"User","globalStorage",b_)})),...T_(e,b_)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function C_(e){return e.continueGlobalDir??$.join(e.homeDir,".continue")}function pN(e){return $.join(C_(e),"mcpServers","maind.json")}function fN(e){return{evidence:[{kind:"foreign-entries",dir:C_(e),ours:["mcpServers"]},...T_(e,sN)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function A_(e){return e.codexHome??$.join(e.homeDir,".codex")}function mN(e){return $.join(A_(e),"config.toml")}function hN(e){let t=A_(e),n=$.join(e.homeDir,".codex"),r=[{kind:"foreign-entries",dir:t,ours:["config.toml"]}];return t!==n&&r.push({kind:"foreign-entries",dir:n,ours:["config.toml"]}),{evidence:r,skipDetail:t===n?"Codex not found (nothing of Codex's in ~/.codex)":"Codex not found (nothing of Codex's in $CODEX_HOME or ~/.codex)"}}function gN(e){return $.join(tN(e),"mcp.json")}function ji(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:$.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:$.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:eN(e),kind:"json",presence:rN(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:$.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Nn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:iN(e),kind:"json",presence:Os(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:S_(e),kind:"json",presence:Os(e),refreshOnly:{skipDetail:"no maind entry here to keep current \u2014 Devin Desktop's own file is the windsurf row"}},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:gN(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{evidence:[Ns(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:dN(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:uN(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:pN(e),kind:"json",presence:fN(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:mN(e),kind:"toml",presence:hN(e)}]}function I_(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function N_(e){return e.jsonShape??QI}function Hi(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Is(e.env.XDG_CONFIG_HOME),appData:Is(e.env.APPDATA),localAppData:Is(e.env.LOCALAPPDATA),clineDir:Fi(e.env.CLINE_DIR),clineDataDir:Fi(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:Fi(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:Fi(e.env.CONTINUE_GLOBAL_DIR),codexHome:Fi(e.env.CODEX_HOME),bundleAppRoot:lN(e.bridgeEntry??null)}}function Is(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Fi(e){let t=Is(e);return t!==null&&$.isAbsolute(t)?t:null}var QI,w_,nN,E_,oN,b_,sN,aN,cN,Ad,On=v(()=>{"use strict";Gt();QI={serversKey:"mcpServers"};s(v_,"buildMaindServerEntry");w_="claude_desktop_config.json";s(k_,"claudeDesktopAppDataDir");s(eN,"claudeDesktopConfigPath");s(Ds,"editorAppDataDir");s(tN,"vsCodeUserDir");s(Ns,"editorRan");s(__,"localAppDataDir");nN="Claude_pzs8sxrjxfjjc";s(rN,"claudeDesktopPresence");s(Nn,"cursorPresence");s(x_,"devinConfigDir");s(iN,"devinMcpConfigPath");s(S_,"windsurfLegacyMcpConfigPath");s(Os,"devinDesktopPresence");E_=[{appData:"Code",dataFolder:".vscode"},{appData:"Code - Insiders",dataFolder:".vscode-insiders"},{appData:"Cursor",dataFolder:".cursor"},{appData:"VSCodium",dataFolder:".vscode-oss"},{appData:"Windsurf",dataFolder:".windsurf"},{appData:"Devin",dataFolder:".devin"},{appData:"AgentComposer",dataFolder:".agentcomposer"}],oN=E_.map(e=>e.appData),b_="saoudrizwan.claude-dev",sN="continue.continue",aN=["AgentComposer"],cN=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(lN,"bundleAppRootOf");s(T_,"agentExtensionEvidence");s(R_,"clineDataDir");s(dN,"clineMcpSettingsPath");s(uN,"clinePresence");s(C_,"continueGlobalDir");s(pN,"continueMcpConfigPath");s(fN,"continuePresence");s(A_,"codexHomeDir");s(mN,"codexConfigPath");s(hN,"codexPresence");s(gN,"vsCodeUserMcpPath");s(ji,"getClientTargets");s(I_,"filterTargetsByFamily");s(N_,"jsonShapeOf");Ad=[...new Set(ji({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(Hi,"makeDefaultContext");s(Is,"nonEmpty");s(Fi,"absoluteOrNull")});import*as P_ from"node:fs/promises";import*as Kt from"node:path";import*as M_ from"node:readline";async function $_(e){let t=Kt.resolve(e),n=t;for(;;){if(await L_(n))return n;let r=Kt.dirname(n);if(r===n)return t;n=r}}async function Ms(e){let n=Kt.resolve(e),r=[];for(;;){await L_(n)&&r.push(n);let i=Kt.dirname(n);if(i===n)break;n=i}return r}async function L_(e){for(let t of _N)try{return await P_.access(Kt.join(e,t)),!0}catch{}return!1}async function F_(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
- `),e.forEach((s,a)=>{process.stdout.write(` [${a+1}] ${s}
140
+ `),e.forEach((o,a)=>{process.stdout.write(` [${a+1}] ${o}
141
141
  `)}),process.stdout.write(`
142
- Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=f_.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 MI,gd=_(()=>{"use strict";MI=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];o(p_,"detectProjectRoot");o(bo,"findAllProjectRoots");o(m_,"hasAnyMarker");o(h_,"disambiguateProjectRoot")});import{existsSync as $I,readdirSync as LI}from"node:fs";import*as se from"node:fs/promises";import*as wo from"node:path";async function X(e){try{return await se.readFile(e,"utf8")}catch(t){if(FI(t))return null;throw t}}async function yd(e){await se.mkdir(e,{recursive:!0})}async function z(e,t,n){let r=wo.dirname(e);await yd(r);let i=wo.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await se.writeFile(i,t,{encoding:"utf8",mode:n});try{await se.rename(i,e)}catch(s){if(jI(s))try{await se.copyFile(i,e),await se.unlink(i).catch(()=>{}),n!==void 0&&await se.chmod(e,n).catch(()=>{});return}catch(a){throw await se.unlink(i).catch(()=>{}),a}throw await se.unlink(i).catch(()=>{}),s}}async function g_(e,t){let n=await X(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function FI(e){return y_(e)&&e.code==="ENOENT"}function jI(e){return!y_(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function y_(e){return typeof e=="object"&&e!==null&&"code"in e}var Sr,be=_(()=>{"use strict";Sr={exists:o(e=>$I(e),"exists"),readdir:o(e=>{try{return LI(e)}catch{return null}},"readdir")};o(X,"readFileSafe");o(yd,"ensureDir");o(z,"atomicWriteFile");o(g_,"hasLinePrefix");o(FI,"isNoEnt");o(jI,"isWindowsRenameFailure");o(y_,"isNodeError")});function UI(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function HI(e,t){if(e.kind==="dir")return t.exists(e.path);let n=t.readdir(e.dir);return n===null?!1:n.some(r=>!UI(r)&&!e.ours.includes(r))}function vo(e,t){return e.evidence.some(n=>HI(n,t))}function __(e,t){return vo(Ci(e),t)}function b_(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||vo(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 ko=_(()=>{"use strict";En();o(UI,"isNoise");o(HI,"evidenceHolds");o(vo,"clientPresent");o(__,"cursorInstalled");o(b_,"presenceSkipRow")});function nN(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 rN(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=M_.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(o=>{n.question("",a=>o(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 _N,Nd=v(()=>{"use strict";_N=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];s($_,"detectProjectRoot");s(Ms,"findAllProjectRoots");s(L_,"hasAnyMarker");s(F_,"disambiguateProjectRoot")});import{existsSync as bN,readdirSync as vN}from"node:fs";import*as ae from"node:fs/promises";import*as $s from"node:path";async function X(e){try{return await ae.readFile(e,"utf8")}catch(t){if(wN(t))return null;throw t}}async function Od(e){await ae.mkdir(e,{recursive:!0})}async function z(e,t,n){let r=$s.dirname(e);await Od(r);let i=$s.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await ae.writeFile(i,t,{encoding:"utf8",mode:n});try{await ae.rename(i,e)}catch(o){if(kN(o))try{await ae.copyFile(i,e),await ae.unlink(i).catch(()=>{}),n!==void 0&&await ae.chmod(e,n).catch(()=>{});return}catch(a){throw await ae.unlink(i).catch(()=>{}),a}throw await ae.unlink(i).catch(()=>{}),o}}async function j_(e,t){let n=await X(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function wN(e){return H_(e)&&e.code==="ENOENT"}function kN(e){return!H_(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function H_(e){return typeof e=="object"&&e!==null&&"code"in e}var Wt,xe=v(()=>{"use strict";Wt={exists:s(e=>bN(e),"exists"),readdir:s(e=>{try{return vN(e)}catch{return null}},"readdir")};s(X,"readFileSafe");s(Od,"ensureDir");s(z,"atomicWriteFile");s(j_,"hasLinePrefix");s(wN,"isNoEnt");s(kN,"isWindowsRenameFailure");s(H_,"isNodeError")});function xN(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function SN(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(`${r}-`)}function EN(e,t){if(e.kind==="dir")return t.exists(e.path);let n=t.readdir(e.dir);return n===null?!1:e.kind==="extension"?n.some(r=>SN(r,e.id)):n.some(r=>!xN(r)&&!e.ours.includes(r))}function Dr(e,t){return e.evidence.some(n=>EN(n,t))}function U_(e,t){return Dr(Nn(e),t)}function B_(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||Dr(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 Ls=v(()=>{"use strict";On();s(xN,"isNoise");s(SN,"isExtensionFolder");s(EN,"evidenceHolds");s(Dr,"clientPresent");s(U_,"cursorInstalled");s(B_,"presenceSkipRow")});function HN(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 UN(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}\`
@@ -375,7 +375,7 @@ written config.
375
375
 
376
376
  --- Preamble block ---
377
377
 
378
- ${xr}`}function An(e,t,n,r={serversKey:"mcpServers"},i={}){let s=n?`
378
+ ${Pr}`}function Mn(e,t,n,r={serversKey:"mcpServers"},i={}){let o=n?`
379
379
  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?`
380
380
  type: "${r.entryType}",`:"",d=i.keepClientKeys?`const previous = config[serversKey].maind;
381
381
  if (previous && typeof previous === "object") {
@@ -387,7 +387,7 @@ if (!("disabled" in server)) server.disabled = false;`:"";return`#!/usr/bin/env
387
387
  set -euo pipefail
388
388
 
389
389
  CONFIG_FILE="${e}"
390
- MAIND_MCP_URL="${t}"${s}
390
+ MAIND_MCP_URL="${t}"${o}
391
391
 
392
392
  mkdir -p "$(dirname "$CONFIG_FILE")"
393
393
 
@@ -424,7 +424,7 @@ ${d}`:""}
424
424
  config[serversKey].maind = server;
425
425
  fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
426
426
  console.log("WROTE " + file);
427
- NODE`}function iN(e){return`#!/usr/bin/env bash
427
+ NODE`}function BN(e){return`#!/usr/bin/env bash
428
428
  set -euo pipefail
429
429
 
430
430
  CONFIG_FILE="$HOME/.codex/config.toml"
@@ -477,7 +477,7 @@ if (serverCount !== 1 || envCount !== 1) {
477
477
 
478
478
  fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
479
479
  console.log("WROTE " + file);
480
- NODE`}function sN(e=bd){let t=`${e}${tN}`;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, Devin Desktop (formerly Windsurf), Codex, Copilot, Claude Desktop, Cline, Continue), 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, claude-desktop, cursor, windsurf (Devin Desktop, formerly Windsurf \u2014 `devin` works too), copilot, cline, continue, codex.",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:rN(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:`{
480
+ NODE`}function GN(e=Pd){let t=`${e}${jN}`;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, Devin Desktop (formerly Windsurf), Codex, Copilot, Claude Desktop, Cline, Continue), 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, claude-desktop, cursor, windsurf (Devin Desktop, formerly Windsurf \u2014 `devin` works too), copilot, cline, continue, codex.",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:UN(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:`{
481
481
  "mcpServers": {
482
482
  "maind": {
483
483
  "command": "npx",
@@ -488,7 +488,7 @@ NODE`}function sN(e=bd){let t=`${e}${tN}`;return[{id:"bridge-installer",label:"Q
488
488
  }
489
489
  }
490
490
  }
491
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:An(".mcp.json",t,"claude-code")}]},{id:"claude-desktop",label:"Claude Desktop",description:"Browser-pairing desktop 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:"~/Library/Application Support/Claude/claude_desktop_config.json",lang:"json",template:`{
491
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:Mn(".mcp.json",t,"claude-code")}]},{id:"claude-desktop",label:"Claude Desktop",description:"Browser-pairing desktop 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:"~/Library/Application Support/Claude/claude_desktop_config.json",lang:"json",template:`{
492
492
  "mcpServers": {
493
493
  "maind": {
494
494
  "command": "npx",
@@ -499,13 +499,13 @@ NODE`}function sN(e=bd){let t=`${e}${tN}`;return[{id:"bridge-installer",label:"Q
499
499
  }
500
500
  }
501
501
  }
502
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:An("$HOME/Library/Application Support/Claude/claude_desktop_config.json",t,"claude-desktop")}]},{id:"codex",label:"Codex CLI",description:"Browser-pairing Codex 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:"~/.codex/config.toml",lang:"toml",template:`[mcp_servers.maind]
502
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:Mn("$HOME/Library/Application Support/Claude/claude_desktop_config.json",t,"claude-desktop")}]},{id:"codex",label:"Codex CLI",description:"Browser-pairing Codex 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:"~/.codex/config.toml",lang:"toml",template:`[mcp_servers.maind]
503
503
  command = "npx"
504
504
  args = ["-y", "@maind-dev/mcp-bridge"]
505
505
 
506
506
  [mcp_servers.maind.env]
507
507
  MAIND_CLIENT_FAMILY = "codex"
508
- 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:iN(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:`{
508
+ 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:BN(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:`{
509
509
  "servers": {
510
510
  "maind": {
511
511
  "type": "stdio",
@@ -517,7 +517,7 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
517
517
  }
518
518
  }
519
519
  }
520
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:'Idempotent installer for the workspace `.vscode/mcp.json` read by VS Code Copilot. Creates `.vscode/` if needed, writes VS Code\'s `servers` shape with `"type": "stdio"`, replaces only the maind entry, and lets the bridge create a fresh device-bound key via browser pairing on first launch. Plain JSON only \u2014 a file with comments is reported and left untouched.',filename:"install-maind-copilot.sh",lang:"bash",template:An(".vscode/mcp.json",t,"copilot",{serversKey:"servers",entryType:"stdio"})}]},{id:"agent-preamble",label:"Agent preamble files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules, .windsurfrules + optional SessionStart reminder)",description:"Idempotent shell script that creates or extends SIX artefacts: the five agent-preamble files (CLAUDE.md / AGENTS.md / .github/copilot-instructions.md / .cursorrules / .windsurfrules) plus a SessionStart-Reminder file at ~/.claude/maind-session-start-reminder.md (for Claude Code users \u2014 referenced by an optional SessionStart-Hook). Existing installations are detected via grep on the line `## maind MCP integration` (matches both the legacy soft variant and the new hardened variant). The script also emits a copy-paste JSON snippet for merging the SessionStart-Hook into ~/.claude/settings.json \u2014 manual merge step because naive append breaks JSON syntax. Switching between agents later does not require any MCP re-config. Drift-note: the five preamble files carry duplicated content (single source: this snippet's heredoc).",filename:"writes CLAUDE.md + AGENTS.md + .github/copilot-instructions.md + .cursorrules + .windsurfrules + ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
520
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:'Idempotent installer for the workspace `.vscode/mcp.json` read by VS Code Copilot. Creates `.vscode/` if needed, writes VS Code\'s `servers` shape with `"type": "stdio"`, replaces only the maind entry, and lets the bridge create a fresh device-bound key via browser pairing on first launch. Plain JSON only \u2014 a file with comments is reported and left untouched.',filename:"install-maind-copilot.sh",lang:"bash",template:Mn(".vscode/mcp.json",t,"copilot",{serversKey:"servers",entryType:"stdio"})}]},{id:"agent-preamble",label:"Agent preamble files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules, .windsurfrules + optional SessionStart reminder)",description:"Idempotent shell script that creates or extends SIX artefacts: the five agent-preamble files (CLAUDE.md / AGENTS.md / .github/copilot-instructions.md / .cursorrules / .windsurfrules) plus a SessionStart-Reminder file at ~/.claude/maind-session-start-reminder.md (for Claude Code users \u2014 referenced by an optional SessionStart-Hook). Existing installations are detected via grep on the line `## maind MCP integration` (matches both the legacy soft variant and the new hardened variant). The script also emits a copy-paste JSON snippet for merging the SessionStart-Hook into ~/.claude/settings.json \u2014 manual merge step because naive append breaks JSON syntax. Switching between agents later does not require any MCP re-config. Drift-note: the five preamble files carry duplicated content (single source: this snippet's heredoc).",filename:"writes CLAUDE.md + AGENTS.md + .github/copilot-instructions.md + .cursorrules + .windsurfrules + ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
521
521
  # maind agent-preamble installer \u2014 idempotent. Creates or extends:
522
522
  # CLAUDE.md (Claude Code)
523
523
  # AGENTS.md (Codex, Devin Desktop, newer Cursor \u2014 cross-agent standard)
@@ -534,7 +534,7 @@ set -e
534
534
 
535
535
  read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
536
536
 
537
- ${xr}
537
+ ${Pr}
538
538
  MAIND_PREAMBLE_EOF
539
539
 
540
540
  mkdir -p .github
@@ -583,7 +583,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
583
583
  }
584
584
  }
585
585
  }
586
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:An("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Devin Desktop (formerly Windsurf)",description:"Browser-pairing Devin Desktop config \u2014 Devin's own MCP file, which Devin Desktop's agent (Devin Local) and the Devin CLI read: `~/.config/devin/mcp_config.json` on macOS and Linux (`$XDG_CONFIG_HOME/devin/` when set), `%APPDATA%\\devin\\mcp_config.json` on Windows. Add the `maind` entry next to your other servers. 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:"~/.config/devin/mcp_config.json",lang:"json",template:`{
586
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:Mn("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Devin Desktop (formerly Windsurf)",description:"Browser-pairing Devin Desktop config \u2014 Devin's own MCP file, which Devin Desktop's agent (Devin Local) and the Devin CLI read: `~/.config/devin/mcp_config.json` on macOS and Linux (`$XDG_CONFIG_HOME/devin/` when set), `%APPDATA%\\devin\\mcp_config.json` on Windows. Add the `maind` entry next to your other servers. 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:"~/.config/devin/mcp_config.json",lang:"json",template:`{
587
587
  "mcpServers": {
588
588
  "maind": {
589
589
  "command": "npx",
@@ -594,7 +594,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
594
594
  }
595
595
  }
596
596
  }
597
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Devin Desktop's ~/.config/devin/mcp_config.json (macOS and Linux; honours XDG_CONFIG_HOME). It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-devin-desktop.sh",lang:"bash",template:An("${XDG_CONFIG_HOME:-$HOME/.config}/devin/mcp_config.json",t,"windsurf")}]},{id:"cline",label:"Cline",description:"Browser-pairing Cline config \u2014 one file for Cline in every editor (VS Code, Cursor, AgentComposer, \u2026), the Cline CLI and Cline Desktop (Cline 4.x; in Cline: MCP Servers \u2192 Configure \u2192 Configure MCP Servers opens it). Add the `maind` entry next to your other servers. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as Cline. Replace `__STACK__` with your stack slugs.",filename:"~/.cline/data/settings/cline_mcp_settings.json",lang:"json",template:`{
597
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Devin Desktop's ~/.config/devin/mcp_config.json (macOS and Linux; honours XDG_CONFIG_HOME). It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-devin-desktop.sh",lang:"bash",template:Mn("${XDG_CONFIG_HOME:-$HOME/.config}/devin/mcp_config.json",t,"windsurf")}]},{id:"cline",label:"Cline",description:"Browser-pairing Cline config \u2014 one file for Cline in every editor (VS Code, Cursor, AgentComposer, \u2026), the Cline CLI and Cline Desktop (Cline 4.x; in Cline: MCP Servers \u2192 Configure \u2192 Configure MCP Servers opens it). Add the `maind` entry next to your other servers. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as Cline. Replace `__STACK__` with your stack slugs.",filename:"~/.cline/data/settings/cline_mcp_settings.json",lang:"json",template:`{
598
598
  "mcpServers": {
599
599
  "maind": {
600
600
  "command": "npx",
@@ -606,7 +606,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
606
606
  "disabled": false
607
607
  }
608
608
  }
609
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cline/data/settings/cline_mcp_settings.json. It merges the bridge-backed maind server, keeps your other servers and what you set on the entry in Cline (disabled, autoApprove, timeout), and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cline.sh",lang:"bash",template:An("$HOME/.cline/data/settings/cline_mcp_settings.json",t,"cline",{serversKey:"mcpServers"},{keepClientKeys:!0})}]},{id:"continue",label:"Continue",description:"Browser-pairing Continue config as a file of its own: Continue loads every JSON file in `~/.continue/mcpServers/` (and in a workspace's `.continue/mcpServers/`) in this shape, so your `config.yaml` stays as it is. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as Continue. Replace `__STACK__` with your stack slugs.",filename:"~/.continue/mcpServers/maind.json",lang:"json",template:`{
609
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cline/data/settings/cline_mcp_settings.json. It merges the bridge-backed maind server, keeps your other servers and what you set on the entry in Cline (disabled, autoApprove, timeout), and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cline.sh",lang:"bash",template:Mn("$HOME/.cline/data/settings/cline_mcp_settings.json",t,"cline",{serversKey:"mcpServers"},{keepClientKeys:!0})}]},{id:"continue",label:"Continue",description:"Browser-pairing Continue config as a file of its own: Continue loads every JSON file in `~/.continue/mcpServers/` (and in a workspace's `.continue/mcpServers/`) in this shape, so your `config.yaml` stays as it is. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as Continue. Replace `__STACK__` with your stack slugs.",filename:"~/.continue/mcpServers/maind.json",lang:"json",template:`{
610
610
  "mcpServers": {
611
611
  "maind": {
612
612
  "command": "npx",
@@ -617,7 +617,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
617
617
  }
618
618
  }
619
619
  }
620
- }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.continue/mcpServers/maind.json. It creates the folder if needed, merges the bridge-backed maind server, and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-continue.sh",lang:"bash",template:An("$HOME/.continue/mcpServers/maind.json",t,"continue")}]},{id:"langchain-ts",label:"LangChain / LangGraph (TS)",description:"Bridge-backed stdio MCP client. The bridge opens browser pairing, creates a fresh device-bound key, and forwards calls to the stack-aware maind endpoint. Replace `__STACK__` with your stack slugs.",filename:"agent.ts",lang:"ts",template:`import { MultiServerMCPClient } from "@langchain/mcp-adapters";
620
+ }`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.continue/mcpServers/maind.json. It creates the folder if needed, merges the bridge-backed maind server, and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-continue.sh",lang:"bash",template:Mn("$HOME/.continue/mcpServers/maind.json",t,"continue")}]},{id:"langchain-ts",label:"LangChain / LangGraph (TS)",description:"Bridge-backed stdio MCP client. The bridge opens browser pairing, creates a fresh device-bound key, and forwards calls to the stack-aware maind endpoint. Replace `__STACK__` with your stack slugs.",filename:"agent.ts",lang:"ts",template:`import { MultiServerMCPClient } from "@langchain/mcp-adapters";
621
621
 
622
622
  const mcp = new MultiServerMCPClient({
623
623
  maind: {
@@ -638,7 +638,7 @@ const tools = await mcp.getTools();
638
638
  "env": {
639
639
  "MAIND_MCP_URL": "${t}"
640
640
  }
641
- }`}]}var QI,eN,bd,tN,pz,xr,mz,E_=_(()=>{"use strict";QI="__STACK__",eN="__INTENT__",bd="https://mcp.maind.dev/mcp",tN=`?stack=${QI}&intent=${eN}`;o(nN,"buildStackAwareEndpoint");pz=nN(bd,{stack:["nextjs","supabase"],intent:"mixed"}),xr=`## maind MCP integration \u2014 Mandatory consultation
641
+ }`}]}var LN,FN,Pd,jN,Sq,Pr,Eq,q_=v(()=>{"use strict";LN="__STACK__",FN="__INTENT__",Pd="https://mcp.maind.dev/mcp",jN=`?stack=${LN}&intent=${FN}`;s(HN,"buildStackAwareEndpoint");Sq=HN(Pd,{stack:["nextjs","supabase"],intent:"mixed"}),Pr=`## maind MCP integration \u2014 Mandatory consultation
642
642
 
643
643
  This project uses the maind MCP server (mcp.maind.dev/mcp) as
644
644
  authoritative source for vetted coding conventions and lessons. The
@@ -707,44 +707,47 @@ For non-trivial changes, resolve documentation path in this order:
707
707
  If no path is discoverable, provide a guided fallback:
708
708
  \`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
709
709
 
710
- Full tool set + provenance via \`get_conventions\`.`;o(rN,"buildAiPromptBody");o(An,"buildJsonConfigInstaller");o(iN,"buildCodexTomlInstaller");o(sN,"buildSnippetTemplates");mz=sN(bd)});function oN(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 xo(e,t){let n=e.replace(/\r\n/g,`
711
- `).trim(),{text:r}=aN(n,6e3);return[T_,oN(t),r,R_].join(`
712
- `)}function aN(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
713
- `),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(`
714
- `),dropped:n.length-i.length}}i.push(n[a]),s+=c}return{text:i.join(`
715
- `),dropped:0}}function A_(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Eo(e,t){return e.split(/\r?\n/).some(n=>n.startsWith(t))}function To(e,t,n){let r=e.includes(`\r
710
+ Full tool set + provenance via \`get_conventions\`.`;s(UN,"buildAiPromptBody");s(Mn,"buildJsonConfigInstaller");s(BN,"buildCodexTomlInstaller");s(GN,"buildSnippetTemplates");Eq=GN(Pd)});function KN(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 js(e,t){let n=e.replace(/\r\n/g,`
711
+ `).trim(),{text:r}=WN(n,6e3);return[J_,KN(t),r,Y_].join(`
712
+ `)}function WN(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
713
+ `),r=s(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=[],o=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(o+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(`
714
+ `),dropped:n.length-i.length}}i.push(n[a]),o+=c}return{text:i.join(`
715
+ `),dropped:0}}function X_(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Hs(e,t){return e.split(/\r?\n/).some(n=>n.startsWith(t))}function Us(e,t,n){let r=e.includes(`\r
716
716
  `)?`\r
717
717
  `:`
718
- `,i=e.split(r),s=t.split(`
719
- `),a=i.findIndex(g=>g.trim()===T_);if(a>=0){let g=i.findIndex((v,k)=>k>a&&v.trim()===R_);if(g<0)return{next:e,changed:!1,outcome:"damaged"};let y=i.slice(a,g+1);if(cN(y,s))return{next:e,changed:!1,outcome:"unchanged"};let w=[...i.slice(0,a),...s,...i.slice(g+1)].join(r);return{next:w,changed:w!==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 cN(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 T_,R_,wd=_(()=>{"use strict";T_="<!-- maind:conventions v1 begin -->",R_="<!-- maind:conventions v1 end -->";o(oN,"renderConventionsLead");o(xo,"renderConventionsBlock");o(aN,"capAtLineBoundary");o(A_,"countConventions");o(Eo,"hasMaindSection");o(To,"upsertConventionsBlock");o(cN,"sameConventions")});import*as Ze from"node:path";function lN(e){return[{key:"preamble:CLAUDE.md",path:Ze.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Ze.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Ze.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Ze.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Ze.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Ze.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}async function C_(e,t=!1){let n=lN(e),r=[];for(let i of n)r.push(await uN(i,t));return e.conventions!==void 0&&r.push(await dN(e,t)),r}async function dN(e,t){let n=Ze.join(e.projectRoot,"AGENTS.md"),r=o(i=>({target:Er,action:"upsert",status:"skipped",detail:`conventions block: ${i}`}),"skip");try{let s=await X(n)??(t?`${xr}
720
- `:null);if(s===null||!Eo(s,Cn))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=xo(a,{date:new Date().toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??G}),l=To(s,c,Cn);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:Er,action:"upsert",status:"would-merge",detail:`conventions block: would ${d}`}:(await z(n,l.next),{target:Er,action:"upsert",status:"merged",detail:`conventions block: ${d==="insert"?"inserted":"refreshed"}`})}}}catch(i){let s=i instanceof Error?i.message:String(i);return{target:Er,action:"upsert",status:"failed",detail:`conventions block: ${s}`}}}async function uN(e,t){try{if(e.mayNeedParentDir&&!t&&await yd(Ze.dirname(e.path)),await g_(e.path,Cn))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await X(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?`${xr}
721
- `:fN(r)+`${xr}
722
- `;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 fN(e){return e.endsWith(`
718
+ `,i=e.split(r),o=t.split(`
719
+ `),a=i.findIndex(g=>g.trim()===J_);if(a>=0){let g=i.findIndex((b,k)=>k>a&&b.trim()===Y_);if(g<0)return{next:e,changed:!1,outcome:"damaged"};let y=i.slice(a,g+1);if(VN(y,o))return{next:e,changed:!1,outcome:"unchanged"};let _=[...i.slice(0,a),...o,...i.slice(g+1)].join(r);return{next:_,changed:_!==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),m=[...p,"",...o];return l===i.length?m.push(...f.length===0?[""]:f):((f.length===0||f[0].trim()!=="")&&m.push(""),m.push(...f)),{next:m.join(r),changed:!0,outcome:"inserted"}}function VN(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 J_,Y_,Md=v(()=>{"use strict";J_="<!-- maind:conventions v1 begin -->",Y_="<!-- maind:conventions v1 end -->";s(KN,"renderConventionsLead");s(js,"renderConventionsBlock");s(WN,"capAtLineBoundary");s(X_,"countConventions");s(Hs,"hasMaindSection");s(Us,"upsertConventionsBlock");s(VN,"sameConventions")});import*as it from"node:path";function zN(e){return[{key:"preamble:CLAUDE.md",path:it.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:it.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:it.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:it.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:it.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:it.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}async function Z_(e,t=!1){let n=zN(e),r=[];for(let i of n)r.push(await JN(i,t));return e.conventions!==void 0&&r.push(await qN(e,t)),r}async function qN(e,t){let n=it.join(e.projectRoot,"AGENTS.md"),r=s(i=>({target:Mr,action:"upsert",status:"skipped",detail:`conventions block: ${i}`}),"skip");try{let o=await X(n)??(t?`${Pr}
720
+ `:null);if(o===null||!Hs(o,$n))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=js(a,{date:new Date().toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??K}),l=Us(o,c,$n);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:Mr,action:"upsert",status:"would-merge",detail:`conventions block: would ${d}`}:(await z(n,l.next),{target:Mr,action:"upsert",status:"merged",detail:`conventions block: ${d==="insert"?"inserted":"refreshed"}`})}}}catch(i){let o=i instanceof Error?i.message:String(i);return{target:Mr,action:"upsert",status:"failed",detail:`conventions block: ${o}`}}}async function JN(e,t){try{if(e.mayNeedParentDir&&!t&&await Od(it.dirname(e.path)),await j_(e.path,$n))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await X(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?`${Pr}
721
+ `:YN(r)+`${Pr}
722
+ `;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 YN(e){return e.endsWith(`
723
723
 
724
724
  `)?e:e.endsWith(`
725
725
  `)?e+`
726
726
  `:e+`
727
727
 
728
- `}var Cn,Er,vd=_(()=>{"use strict";E_();Ue();wd();be();Cn="## maind MCP integration",Er="preamble:AGENTS.md#conventions";o(lN,"buildPreambleTargets");o(C_,"writePreambleFiles");o(dN,"writeAgentsMdConventionsBlock");o(uN,"writeOnePreambleFile");o(fN,"ensureTrailingBlankLine")});import{existsSync as pN}from"node:fs";import*as I_ from"node:path";function Ie(e,t={},n=Ft){let r=t.fileExists??pN,i=t.expectedCommand??mN,s={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);kd(a)&&(s=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=hN(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(ho(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(kr(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=gN(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 Sd(e){return e.some(t=>t.status!=="ok")}function Ro(e){return e.some(t=>t.remedy==="run-install")}function mN(e){return Xe(ye({entryPath:_e(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function hN(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!kd(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!kd(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function gN(e){for(let t of yN(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return I_.isAbsolute(t)?t:null;return null}function yN(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 kd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qe,Ft,Tr,jt=_(()=>{"use strict";Mt();Qe="on-session-briefing",Ft=[{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:Qe,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."}],Tr=[{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(Ie,"inspectHookWiring");o(Sd,"hasWiringDrift");o(Ro,"needsInstallRun");o(mN,"defaultExpectedCommand");o(hN,"findCommand");o(gN,"extractScriptPath");o(yN,"tokenize");o(kd,"isObject")});import{existsSync as _N,readFileSync as bN}from"node:fs";import{join as wN}from"node:path";function He(){return wN(je(),"config.json")}function Ne(){try{let e=He();if(!_N(e))return null;let t=JSON.parse(bN(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 Ut=_(()=>{"use strict";ie();o(He,"bridgeConfigPath");o(Ne,"readBridgeConfig")});function vN(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===xd?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 Ed(e,t,n=He()){try{let r={},i=await X(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=vN(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)+`
729
- `,384)}catch{}}var xd,Td=_(()=>{"use strict";Ut();be();xd="user declined";o(vN,"nextDeclinedHooks");o(Ed,"recordHookDecisions")});import*as Cd from"node:path";import*as O_ from"node:readline";async function D_(e,t){let n=Cd.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 X(n)}catch(p){return{target:r,action:"merge",status:"failed",detail:`read: ${Rd(p)}`}}let s,a="create";if(i===null||i.trim().length===0)s={};else{a="merge";try{let p=JSON.parse(i);if(!Ad(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: ${Rd(p)}`}}}let c=SN(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??xN)(e.out,`
728
+ `}var $n,Mr,$d=v(()=>{"use strict";q_();Ge();Md();xe();$n="## maind MCP integration",Mr="preamble:AGENTS.md#conventions";s(zN,"buildPreambleTargets");s(Z_,"writePreambleFiles");s(qN,"writeAgentsMdConventionsBlock");s(JN,"writeOnePreambleFile");s(YN,"ensureTrailingBlankLine")});import{existsSync as XN}from"node:fs";import*as Q_ from"node:path";function Te(e,t={},n=st){let r=t.fileExists??XN,i=t.expectedCommand??eO,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ld(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=tO(o,a.event,a.subcommand),d=l===null&&a.supersedes?nO(o,a.event,a.supersedes.pattern):null;if(d!==null&&a.supersedes){let f=a.supersedes.replaceable.test(d);return{...c,status:"superseded",command:d,remedy:f?"run-install":"edit-command",detail:f?`${a.label} still runs \`${d}\` \u2014 plain text, which Cursor rejects (it imports this hook and takes only JSON at session start). \`install --hooks-only\` replaces that entry with '${a.subcommand}', which prints the same text in Claude Code.`:`${a.label} runs your own command on the reminder file (\`${d}\`) \u2014 left as it is; it prints plain text where Cursor takes only JSON. Replace its command with: ${i(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 u=` Replace its command with: ${i(a.subcommand)}`;if(As(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.`+u};if(Or(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.`+u};let p=rO(l);return p!==null&&!r(p)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${p}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function jd(e){return e.some(t=>t.status!=="ok")}function Bs(e){return e.some(t=>t.remedy==="run-install")}function eO(e){return rt(ke({entryPath:he(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function tO(e,t,n){return eb(e,t,r=>r.includes(n))}function nO(e,t,n){return eb(e,t,r=>n.test(r))}function eb(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Ld(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Ld(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function rO(e){for(let t of iO(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Q_.isAbsolute(t)?t:null;return null}function iO(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 Ld(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ot,Fd,Ln,ZN,QN,st,$r,at=v(()=>{"use strict";Gt();ot="on-session-briefing",Fd=".claude/maind-session-start-reminder.md",Ln="on-session-reminder",ZN=/maind-session-start-reminder\.md/,QN=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,st=[{event:"SessionStart",subcommand:Ln,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:ZN,replaceable:QN},consentDescription:"It runs 'maind-mcp-bridge on-session-reminder' when a session starts and adds ~/.claude/maind-session-start-reminder.md \u2014 the maind consultation triggers `install` wrote there \u2014 to the session context: in Claude Code exactly what the `cat` hook it replaces printed; in Cursor, which imports this hook but takes only JSON there, nothing; in Devin Local the same text as JSON context (off with 'devin_hook_output': false in the bridge config). It reads that one file and nothing else; nothing leaves the machine. Where your settings still run `cat` on that file, this replaces that one entry instead of adding a second."},{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:ot,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."}];s(Te,"inspectHookWiring");s(jd,"hasWiringDrift");s(Bs,"needsInstallRun");s(eO,"defaultExpectedCommand");s(tO,"findCommand");s(nO,"findCommandMatching");s(eb,"findFirstCommand");s(rO,"extractScriptPath");s(iO,"tokenize");s(Ld,"isObject")});import{existsSync as oO,readFileSync as sO}from"node:fs";import{join as aO}from"node:path";function Ke(){return aO(Be(),"config.json")}function te(){try{let e=Ke();if(!oO(e))return null;let t=JSON.parse(sO(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")),typeof n.devin_hook_output=="boolean"&&(r.devin_hook_output=n.devin_hook_output),r}catch{return null}}var We=v(()=>{"use strict";se();s(Ke,"bridgeConfigPath");s(te,"readBridgeConfig")});function cO(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===Hd?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 Ud(e,t,n=Ke()){try{let r={},i=await X(n);if(i!==null&&i.trim().length>0){let l=JSON.parse(i);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let o=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=cO(o,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)+`
729
+ `,384)}catch{}}var Hd,Bd=v(()=>{"use strict";We();xe();Hd="user declined";s(cO,"nextDeclinedHooks");s(Ud,"recordHookDecisions")});import*as tb from"node:path";import*as nb from"node:readline";async function lO(e,t){let n=tb.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 X(n)}catch(g){return{target:r,action:"merge",status:"failed",detail:`read: ${Gd(g)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let g=JSON.parse(i);if(!Bi(g))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};o=g}catch(g){return{target:r,action:"merge",status:"failed",detail:`parse: ${Gd(g)}`}}}let c=pO(o,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};let l=t.supersedes?uO(o,t.event,t.supersedes.pattern):null;if(l!==null&&t.supersedes&&!t.supersedes.replaceable.test(l.command))return{target:r,action:"skip",status:"skipped",detail:`your own command already prints this (\`${l.command}\`) \u2014 left as it is; it prints plain text where Cursor takes only JSON. Replace its command with: ${t.command}`};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)`};let g=l!==null?`
730
+ Replace the ${t.event} hook \`${l.command}\` in ${n}?
731
+ ${t.consentDescription}
732
+ [Y/n]: `:`
730
733
  Merge a ${t.event} hook into ${n}?
731
734
  ${t.consentDescription}
732
- [Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:xd}}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)+`
733
- `;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: ${Rd(p)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function P_(e){let t=Cd.join(e.homeDir,N_);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 ${N_} into every new Claude Code session.`})}function kN(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Id(e,t){let n=e.launch??ye({entryPath:_e(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Xe(n);return D_(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:kN(t),skipDetail:o(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return ho(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}`:kr(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 Nd(e){let t=[];for(let n of Ft)t.push(await Id(e,n));return t}function SN(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Ad(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!Ad(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function xN(e,t){e.write(t);let n=O_.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 Ad(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rd(e){return e instanceof Error?e.message:String(e)}var N_,Od=_(()=>{"use strict";be();Mt();jt();Td();N_=".claude/maind-session-start-reminder.md";o(D_,"mergeClaudeHook");o(P_,"mergeSessionStartHook");o(kN,"targetKeyFor");o(Id,"mergeSubcommandHook");o(Nd,"mergeAllSubcommandHooks");o(SN,"findExistingHookCommand");o(xN,"promptYesNo");o(Ad,"isObject");o(Rd,"errMessage")});import{existsSync as RN}from"node:fs";import{dirname as AN,join as L_}from"node:path";function Bt(e,t=RN){let n=e;for(;;){if(t(L_(n,".git")))return n;let r=AN(n);if(r===n)return null;n=r}}var Ht,Ao=_(()=>{"use strict";Ht=L_(".maind","code-index.sqlite");o(Bt,"findRepoRoot")});function Co(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function Kt(e){return e+1}function Io(e){return(e.text.split(`
734
- `,1)[0]??"").trim().slice(0,200)}function BN(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 GN(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=BN(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Ld(e,t,n,r){for(let i of GN(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function Di(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 Gt(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 Gt(t.childForFieldName("name"));case"parenthesized_type":return Gt(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?Gt(n[0]):"#"}default:return"#"}}function WN(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Fd(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 Pi(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=Gt(n.childForFieldName("type"))??Fd(i)??(WN(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=Gt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function Wt(e,t,n,r,i={locals:Pi(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",...KN]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(Di(l.childForFieldName("function")));else if(l.type==="new_expression")a(Di(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(Di(d))}}var KN,No=_(()=>{"use strict";o(Co,"newResult");o(Kt,"line1");o(Io,"signatureOf");o(BN,"calleeName");o(GN,"collectCallTargets");o(Ld,"addCallRefs");o(Di,"calleeRef");KN=["jsx_opening_element","jsx_self_closing_element"];o(Gt,"typeNameOf");o(WN,"isMethodCallResult");o(Fd,"newTypeOf");o(Pi,"collectTypeHints");o(Wt,"addTsRefs")});function q_(e,t){let n=Co();for(let r of e.namedChildren)VN(r,t,n);return n}function J_(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function VN(e,t,n){let r=J_(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??qN(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=Oo(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&&Ld(n,s.nodeKey,a,z_);return}case"class_definition":zN(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=Oo(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 zN(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Oo(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=J_(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,f=Oo(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&&Ld(n,f.nodeKey,p,z_)}}function Oo(e,t,n,r,i){return{nodeKey:Je(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Kt(e.startPosition.row),endLine:Kt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Io(e),doc:null}}function qN(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var z_,Y_=_(()=>{"use strict";mn();No();z_="call";o(q_,"extractPython");o(J_,"unwrapDecorated");o(VN,"handleTopLevel");o(zN,"addClass");o(Oo,"makeNode");o(qN,"firstDottedName")});function Z_(e,t){let n=Co(),r=t.language!=="typescript";for(let i of e.namedChildren)YN(i,t,n,r);return QN(e,t,n),n}function JN(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function YN(e,t,n,r){if(e.type==="export_statement"&&XN(e,t,n,r))return;let i=JN(e),s=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":ZN(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=X_(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=tO(i,t,n,r);s&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":jd(i,t,n,"interface");return;case"type_alias_declaration":jd(i,t,n,"type_alias");return;case"enum_declaration":jd(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&&Wt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";X_(a,t,n,d?"function":"variable",r,c,l)}return}default:Wt(n,t.moduleKey,i,r);return}}function XN(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=Hd(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}):Wt(n,t.moduleKey,c,r),!0):!1}function ZN(e,t,n){let r=Hd(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 QN(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"?Hd(i):null;if(s===null)continue;let c=eO(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 eO(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function X_(e,t,n,r,i,s,a){let l=(s??e.childForFieldName("name"))?.text;if(!l)return null;let d=Do(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;Wt(n,d.nodeKey,u,i,{locals:Pi(e)})}else a&&Wt(n,d.nodeKey,a,i);return d}function jd(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Do(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function tO(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let s=Do(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:Ud(f)})):[{kind:"extends",ref:Ud(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=nO(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&Wt(n,s.nodeKey,g,r,{locals:Pi(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let f=`${i}.${u}`,p=Do(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&&Wt(n,p.nodeKey,h,r,{locals:Pi(d),thisFields:l})}return s}function nO(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=Gt(n.childForFieldName("type"))??Fd(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=Gt(r.childForFieldName("type"));i?.type==="identifier"&&s&&t.set(i.text,s)}return t}function Do(e,t,n,r,i){return{nodeKey:Je(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Kt(e.startPosition.row),endLine:Kt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Io(e),doc:null}}function Ud(e){if(!e)return null;switch(e.type){case"generic_type":return Ud(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 Di(e);default:return null}}function Hd(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var Q_=_(()=>{"use strict";mn();No();o(Z_,"extractTypescript");o(JN,"unwrapExport");o(YN,"handleTopLevel");o(XN,"handleExportForm");o(ZN,"addImport");o(QN,"collectDynamicImports");o(eO,"enclosingDeclarator");o(X_,"addFunctionLike");o(jd,"addSimpleNamed");o(tO,"addClass");o(nO,"classFieldTypes");o(Do,"makeNode");o(Ud,"heritageRef");o(Hd,"stringValue")});import{createRequire as rO}from"node:module";import{join as iO}from"node:path";function nb(e,t){return t?iO(t,eb[e]):rO(import.meta.url).resolve(`tree-sitter-wasms/out/${eb[e]}`)}var eb,tb,rb=_(()=>{"use strict";eb={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},tb="tree-sitter.wasm";o(nb,"grammarPath")});import{join as sO}from"node:path";import Bd from"web-tree-sitter";var oO,Po,ib=_(()=>{"use strict";mn();Ps();Y_();Q_();No();rb();oO=["typescript","tsx","javascript","python"],Po=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=>sO(this.assetDir,t||tb),"locateFile")}:void 0),this.parser=new Bd,this.initialized=!0)}supports(t){return oO.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:Kt(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?q_(a,d):Z_(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(nb(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as aO}from"node:module";function sb(){return Mo("node:sqlite")}function Rr(){if(Mi)return Mi;try{let{DatabaseSync:e}=sb(),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(),Mi={ok:!0}}finally{t.close()}}catch(e){Mi={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Mi}function cO(e){let{DatabaseSync:t}=sb(),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 lO(e){let t=Mo("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 ob(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function $o(e){let t=ob(),n=o(()=>{let{DatabaseSync:i}=Mo("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=Mo("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 Lo(e){let t=ob(),n=o(i=>{let s=i==="node:sqlite"?cO(e):lO(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=Rr();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=Rr();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 Mo,Mi,Fo=_(()=>{"use strict";Mo=aO(import.meta.url);o(sb,"loadBuiltin");Mi=null;o(Rr,"probeBuiltinSqlite");o(cO,"openBuiltin");o(lO,"openBetter");o(ob,"backendOverride");o($o,"openSqliteReadOnly");o(Lo,"openSqliteDatabase")});function mb(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 hb(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:On(a.receiver),receiverType:On(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:On(a.imported_name),localName:On(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:On(a.local_name),specifier:On(a.specifier),importedName:On(a.imported_name)};s(a)?.exports.push(c)}return[...i.values()]}var ab,cb,lb,db,ub,fb,pb,On,gb=_(()=>{"use strict";mn();ab=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],cb="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",lb="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",db="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",ub="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",fb="SELECT file_path, specifier, imported_name, local_name FROM file_imports",pb="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";o(mb,"factRows");On=o(e=>e==null?null:String(e),"str");o(hb,"assembleFacts")});function jo(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 yb,$i,_b=_(()=>{"use strict";Fo();hr();gb();Hl();o(jo,"toNodeRow");yb=400,$i=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Lo(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Ll)}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=mb(t.path,i),u=this.db.prepare(cb);for(let h of d.refs)u.run(...h);let f=this.db.prepare(lb);for(let h of d.imports)f.run(...h);let p=this.db.prepare(db);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 hb(t,this.db.prepare(ub).all(),this.db.prepare(fb).all(),this.db.prepare(pb).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?jo(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(jo)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(jo)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(jo)}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=gy(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
735
+ [Y/n]: `;if(!await(e.prompt??fO)(e.out,g))return{target:r,action:"skip",status:"skipped",detail:Hd}}let d=o.hooks?.[t.event]??[],u;if(l!==null)u=d.map((g,y)=>y!==l.group?g:{...g,hooks:(g.hooks??[]).map((_,b)=>b===l.hook?{..._,command:t.command}:_)});else{let g={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]};u=[...d,g]}let p={...o,hooks:{...o.hooks??{},[t.event]:u}},f=JSON.stringify(p,null,2)+`
736
+ `,m=l===null?"":` (replaced \`${l.command}\`)`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:l===null?n:`${n} (would replace \`${l.command}\`)`};try{await z(n,f,384)}catch(g){return{target:r,action:"merge",status:"failed",detail:`write: ${Gd(g)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n+m}}function dO(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Kd(e,t){let n=e.launch??ke({entryPath:he(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=rt(n);return lO(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:dO(t),supersedes:t.supersedes,skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return As(i)?`${o}, 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}`:Or(i)?`${o}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:o},"skipDetail"),consentDescription:t.consentDescription})}async function Wd(e){let t=[];for(let n of st)t.push(await Kd(e,n));return t}function uO(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i=0;i<r.length;i++){let o=r[i];if(!Bi(o))continue;let a=o.hooks;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=a[c];if(!Bi(l))continue;let d=l.command;if(typeof d=="string"&&n.test(d))return{group:i,hook:c,command:d}}}return null}function pO(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Bi(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Bi(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function fO(e,t){e.write(t);let n=nb.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function Bi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gd(e){return e instanceof Error?e.message:String(e)}var Vd=v(()=>{"use strict";xe();Gt();at();Bd();at();s(lO,"mergeClaudeHook");s(dO,"targetKeyFor");s(Kd,"mergeSubcommandHook");s(Wd,"mergeAllSubcommandHooks");s(uO,"findHookEntry");s(pO,"findExistingHookCommand");s(fO,"promptYesNo");s(Bi,"isObject");s(Gd,"errMessage")});import{existsSync as gO}from"node:fs";import{dirname as yO,join as ob}from"node:path";function qt(e,t=gO){let n=e;for(;;){if(t(ob(n,".git")))return n;let r=yO(n);if(r===n)return null;n=r}}var zt,Gs=v(()=>{"use strict";zt=ob(".maind","code-index.sqlite");s(qt,"findRepoRoot")});function Ks(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function Yt(e){return e+1}function Ws(e){return(e.text.split(`
737
+ `,1)[0]??"").trim().slice(0,200)}function NO(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 OO(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=NO(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Xd(e,t,n,r){for(let i of OO(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function Gi(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 PO(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Zd(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"),o=Jt(n.childForFieldName("type"))??Zd(i)??(PO(i)?"#":null);o&&t.set(r.text,o)}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 Xt(e,t,n,r,i={locals:Ki(n)}){let o=new Set,a=s(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(o.has(d))return;o.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",...DO]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(Gi(l.childForFieldName("function")));else if(l.type==="new_expression")a(Gi(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(Gi(d))}}var DO,Vs=v(()=>{"use strict";s(Ks,"newResult");s(Yt,"line1");s(Ws,"signatureOf");s(NO,"calleeName");s(OO,"collectCallTargets");s(Xd,"addCallRefs");s(Gi,"calleeRef");DO=["jsx_opening_element","jsx_self_closing_element"];s(Jt,"typeNameOf");s(PO,"isMethodCallResult");s(Zd,"newTypeOf");s(Ki,"collectTypeHints");s(Xt,"addTsRefs")});function gb(e,t){let n=Ks();for(let r of e.namedChildren)MO(r,t,n);return n}function yb(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function MO(e,t,n){let r=yb(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??LO(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=zs(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Xd(n,o.nodeKey,a,hb);return}case"class_definition":$O(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=zs(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function $O(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=zs(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.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=yb(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=zs(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&&Xd(n,p.nodeKey,f,hb)}}function zs(e,t,n,r,i){return{nodeKey:et(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Yt(e.startPosition.row),endLine:Yt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Ws(e),doc:null}}function LO(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var hb,_b=v(()=>{"use strict";vn();Vs();hb="call";s(gb,"extractPython");s(yb,"unwrapDecorated");s(MO,"handleTopLevel");s($O,"addClass");s(zs,"makeNode");s(LO,"firstDottedName")});function vb(e,t){let n=Ks(),r=t.language!=="typescript";for(let i of e.namedChildren)jO(i,t,n,r);return BO(e,t,n),n}function FO(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function jO(e,t,n,r){if(e.type==="export_statement"&&HO(e,t,n,r))return;let i=FO(e),o=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":UO(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=bb(i,t,n,"function",r);o&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=KO(i,t,n,r);o&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":Qd(i,t,n,"interface");return;case"type_alias_declaration":Qd(i,t,n,"type_alias");return;case"enum_declaration":Qd(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&&Xt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";bb(a,t,n,d?"function":"variable",r,c,l)}return}default:Xt(n,t.moduleKey,i,r);return}}function HO(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=tu(e.childForFieldName("source")),o=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}),o)for(let l of o.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(o){for(let l of o.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}):Xt(n,t.moduleKey,c,r),!0):!1}function UO(e,t,n){let r=tu(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),o=[],a=s((c,l)=>{o.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)}o.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...o)}function BO(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,o=i?.type==="string"?tu(i):null;if(o===null)continue;let c=GO(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:o,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:o,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:o,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:o})}}function GO(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function bb(e,t,n,r,i,o,a){let l=(o??e.childForFieldName("name"))?.text;if(!l)return null;let d=qs(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;Xt(n,d.nodeKey,u,i,{locals:Ki(e)})}else a&&Xt(n,d.nodeKey,a,i);return d}function Qd(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=qs(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function KO(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let o=qs(e,t,i,i,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.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:eu(p)})):[{kind:"extends",ref:eu(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:f}of u)f&&n.refs.push({fromKey:o.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let c=e.childForFieldName("body");if(!c)return o;let l=WO(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&Xt(n,o.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=qs(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:o.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&Xt(n,f.nodeKey,m,r,{locals:Ki(d),thisFields:l})}return o}function WO(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"))??Zd(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"),o=Jt(r.childForFieldName("type"));i?.type==="identifier"&&o&&t.set(i.text,o)}return t}function qs(e,t,n,r,i){return{nodeKey:et(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Yt(e.startPosition.row),endLine:Yt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Ws(e),doc:null}}function eu(e){if(!e)return null;switch(e.type){case"generic_type":return eu(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 Gi(e);default:return null}}function tu(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var wb=v(()=>{"use strict";vn();Vs();s(vb,"extractTypescript");s(FO,"unwrapExport");s(jO,"handleTopLevel");s(HO,"handleExportForm");s(UO,"addImport");s(BO,"collectDynamicImports");s(GO,"enclosingDeclarator");s(bb,"addFunctionLike");s(Qd,"addSimpleNamed");s(KO,"addClass");s(WO,"classFieldTypes");s(qs,"makeNode");s(eu,"heritageRef");s(tu,"stringValue")});import{createRequire as VO}from"node:module";import{join as zO}from"node:path";function Sb(e,t){return t?zO(t,kb[e]):VO(import.meta.url).resolve(`tree-sitter-wasms/out/${kb[e]}`)}var kb,xb,Eb=v(()=>{"use strict";kb={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},xb="tree-sitter.wasm";s(Sb,"grammarPath")});import{join as qO}from"node:path";import nu from"web-tree-sitter";var JO,Js,Tb=v(()=>{"use strict";vn();Jo();_b();wb();Vs();Eb();JO=["typescript","tsx","javascript","python"],Js=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await nu.init(this.assetDir?{locateFile:s(t=>qO(this.assetDir,t||xb),"locateFile")}:void 0),this.parser=new nu,this.initialized=!0)}supports(t){return JO.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=o.rootNode,c=Qe(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Yt(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?gb(a,d):vb(a,d);return o.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 nu.Language.load(Sb(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as YO}from"node:module";function Rb(){return Ys("node:sqlite")}function Lr(){if(Wi)return Wi;try{let{DatabaseSync:e}=Rb(),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(),Wi={ok:!0}}finally{t.close()}}catch(e){Wi={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Wi}function XO(e){let{DatabaseSync:t}=Rb(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function ZO(e){let t=Ys("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function Cb(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Xs(e){let t=Cb(),n=s(()=>{let{DatabaseSync:i}=Ys("node:sqlite"),o=new i(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>o.prepare(a),"prepare"),exec:s(a=>o.exec(a),"exec"),close:s(()=>o.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let i=Ys("better-sqlite3"),o=new i(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>o.prepare(a),"prepare"),exec:s(a=>{o.exec(a)},"exec"),close:s(()=>{o.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(i){try{return r()}catch(o){let a=s(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(o)})`)}}}function Zs(e){let t=Cb(),n=s(i=>{let o=i==="node:sqlite"?XO(e):ZO(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=Lr();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=Lr();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var Ys,Wi,Qs=v(()=>{"use strict";Ys=YO(import.meta.url);s(Rb,"loadBuiltin");Wi=null;s(Lr,"probeBuiltinSqlite");s(XO,"openBuiltin");s(ZO,"openBetter");s(Cb,"backendOverride");s(Xs,"openSqliteReadOnly");s(Zs,"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 Lb(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 o=s(a=>i.get(String(a.file_path)),"entry");for(let a of t)o(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Hn(a.receiver),receiverType:Hn(a.receiver_type)});for(let a of n){let c=o(a);if(!c)continue;let l={fromModuleKey:Qe(c.filePath),specifier:String(a.specifier),importedName:Hn(a.imported_name),localName:Hn(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:Hn(a.local_name),specifier:Hn(a.specifier),importedName:Hn(a.imported_name)};o(a)?.exports.push(c)}return[...i.values()]}var Ab,Ib,Nb,Ob,Db,Pb,Mb,Hn,Fb=v(()=>{"use strict";vn();Ab=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Ib="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Nb="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Ob="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Db="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Pb="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Mb="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s($b,"factRows");Hn=s(e=>e==null?null:String(e),"str");s(Lb,"assembleFacts")});function ea(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 jb,Vi,Hb=v(()=>{"use strict";Qs();Er();Fb();id();s(ea,"toNodeRow");jb=400,Vi=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Zs(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(ed)}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 m of i.contains)l.run(m.srcKey,m.dstKey,m.kind);let d=$b(t.path,i),u=this.db.prepare(Ib);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Nb);for(let m of d.imports)p.run(...m);let f=this.db.prepare(Ob);for(let m of d.exports)f.run(...m)}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 Lb(t,this.db.prepare(Db).all(),this.db.prepare(Pb).all(),this.db.prepare(Mb).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 o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.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?ea(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ea)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ea)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ea)}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 o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,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=Dy(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
735
738
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
736
739
  WHERE nodes_fts MATCH ? AND n.kind = ?
737
740
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
738
741
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
739
742
  WHERE nodes_fts MATCH ?
740
- ORDER BY score LIMIT ?`,a=this.db.prepare(s);return(n?a.all(i,n,r):a.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let a=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(a+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),a+=" LIMIT ?",c.push(i),this.db.prepare(a).all(...c).map(d=>({srcKey:d.src_key,dstKey:d.dst_key,kind:d.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
743
+ ORDER BY score LIMIT ?`,a=this.db.prepare(o);return(n?a.all(i,n,r):a.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let a=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(a+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),a+=" LIMIT ?",c.push(i),this.db.prepare(a).all(...c).map(d=>({srcKey:d.src_key,dstKey:d.dst_key,kind:d.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
741
744
  (SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
742
745
  (SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
743
746
  (SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
744
747
  FROM nodes n
745
748
  WHERE n.kind = 'module'
746
749
  ORDER BY imports_in DESC, symbol_count DESC
747
- 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+=yb)for(let a of n.slice(s,s+yb))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let s of ab)this.db.prepare(s).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
750
+ 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(o=>o.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 o=0;o<n.length;o+=jb)for(let a of n.slice(o,o+jb))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let o of Ab)this.db.prepare(o).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
748
751
  node_key, kind, name, qualified_name, file_path, language,
749
752
  start_line, end_line, start_byte, end_byte, signature, doc
750
753
  ) 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)
@@ -754,181 +757,182 @@ ${t.consentDescription}
754
757
  content_hash = excluded.content_hash,
755
758
  mtime_ms = excluded.mtime_ms,
756
759
  size = excluded.size,
757
- indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as dO}from"node:crypto";function Ar(e){return dO("sha256").update(e,"utf8").digest("hex")}function bb(e){return{node_key_hash:Ar(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Ar(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Ar(e.signature):null}}function wb(e){return{src_key_hash:Ar(e.srcKey),dst_key_hash:Ar(e.dstKey),kind:e.kind}}function vb(e,t,n){return{node_key_hash:Ar(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var kb=_(()=>{"use strict";o(Ar,"sha256");o(bb,"toCloudNode");o(wb,"toCloudEdge");o(vb,"toCloudEmbedding")});import{randomUUID as uO}from"node:crypto";function Gd(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Sb(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function xb(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Cr,Ir,fO,Kd=_(()=>{"use strict";hr();kb();Cr=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Ir=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(pr),lastSyncedAt:Sb(await this.store.getMeta(jl))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(bb),n=(await this.store.getAllEdges()).map(wb),r=await this.store.getMeta(It)??Ct,i=await this.store.getMeta(pr),s=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(w=>[w.language,w.count])),c=uO(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:a},d=0,u=Gd(t,this.chunk),f=Gd(n,this.chunk*2),p=Math.max(1,u.length+f.length);for(let w of u)await this.post("/api/codebase/push",{...l,nodes:w,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:p});for(let w of f)await this.post("/api/codebase/push",{...l,nodes:[],edges:w,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(w=>w.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(jl,String(Date.now())),i&&await this.store.setMeta(my,i),{nodes:t.length,edges:n.length,pruned:xb(g.nodes_deleted),edgesPruned:xb(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=>vb(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=Gd(a,fO),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(to),n=await this.store.getMeta(no),r=Sb(await this.store.getMeta(ro));if(!t||!n||!r)throw new Cr("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 Cr(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},fO=250;o(Gd,"chunkArray");o(Sb,"numOrNull");o(xb,"numOr0")});var Vd={};ee(Vd,{CodeIndexSync:()=>Ir,DEFAULT_DB_RELPATH:()=>Wd,SyncError:()=>Cr,createCodeIndexSync:()=>mO,createNodeCodeIndex:()=>Ho,openIndexReader:()=>hO,openSqliteDatabase:()=>Lo,openSqliteReadOnly:()=>$o,probeBuiltinSqlite:()=>Rr});import{mkdirSync as pO}from"node:fs";import{posix as Uo}from"node:path";function Ho(e){let t=e.dbPath??Uo.join(e.repoRoot,Wd);pO(Uo.dirname(t),{recursive:!0}),e.dbPath===void 0&&li(Uo.dirname(t));let n=new $i(t),r=new Po;return new Si({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function mO(e){let t=e.dbPath??Uo.join(e.repoRoot,Wd),n=e.projectKey??ag(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 $i(t);return new Ir(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function hO(e){return ql($o(e).db)}var Wd,Bo=_(()=>{"use strict";Xc();ib();Bl();Jl();_b();Fo();Kd();$s();Kd();Fo();Wd=".maind/code-index.sqlite";o(Ho,"createNodeCodeIndex");o(mO,"createCodeIndexSync");o(hO,"openIndexReader")});import{execFileSync as Eb}from"node:child_process";import{existsSync as Tb,realpathSync as Rb}from"node:fs";import{createRequire as gO}from"node:module";import{basename as yO,dirname as _O,isAbsolute as Ab,join as bO,relative as Cb,resolve as Go,sep as Ib}from"node:path";function Ko(){let e=Rr();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return gO(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 Nb(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 we(e=process.cwd()){try{let t=Eb("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 Db(e,t=we(),n=process.cwd()){let r=Ab(e)?[e]:[Go(t,e),Go(n,e)];for(let i of r){let s=_O(i);if(!Tb(s))continue;let a;try{a=Rb(s)}catch{continue}let c=Pb(a);if(c===null)continue;let l=Cb(c,bO(a,yO(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Ib).join("/")}}return null}function Nr(e,t=we(),n=process.cwd()){let r=Ab(e)?[e]:[Go(t,e),Go(n,e)];for(let i of r){if(!Tb(i))continue;let s;try{s=Rb(i)}catch{continue}let a=Pb(s);if(a===null)continue;let c=Cb(a,s);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Ib).join("/")}}return null}function Pb(e){try{let t=Eb("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 Mb(){return Ho({repoRoot:we()})}function $b(e){return Ho({repoRoot:e})}var Ob,Vt=_(()=>{"use strict";Bo();o(Ko,"probeNativeStore");o(Nb,"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(we,"resolveRepoRoot");o(Db,"resolveRepoRootForPath");o(Nr,"resolveRepoRootForDir");o(Pb,"gitToplevelOf");o(Mb,"defaultEngineFactory");o($b,"engineForRoot")});async function Or(e){return pt("get_session_briefing",{tools:["claude-code"]},e)}async function pt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Li,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:wO,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 Lb(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let w=null;try{let v=JSON.parse(d);typeof v.result?.instructions=="string"&&(w=v.result.instructions)}catch{w=null}n.onInitialize(w)}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(w=>w.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 Lb(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(w=>w.type==="text"&&typeof w.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(s)}}async function Lb(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(`
758
- `).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(`
759
- `))!==-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 Li,wO,zt=_(()=>{"use strict";Li="https://mcp.maind.dev/mcp",wO="2025-06-18";o(Or,"fetchSessionBriefing");o(pt,"fetchToolText");o(Lb,"readSseMessage")});async function K(){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 Dr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Oe(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var pe=_(()=>{"use strict";o(K,"readHookInput");o(Dr,"transcriptPathOf");o(Oe,"toolFilePathOf")});import{existsSync as vO,readFileSync as kO}from"node:fs";import{join as zd}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 qd(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function Ub(e,t={}){return e.some(n=>qd(Ie(n,t,[jb])[0]))}function Wo(e,t){let n=Ie(e,t,[jb])[0],r=Ie(e,t,[SO])[0];return{channel:qd(n)?"core":qd(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function Hb(e,t){let n=[zd(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(zd(t,".claude","settings.json"),zd(t,".claude","settings.local.json")),n.map(r=>{try{return vO(r)?kO(r,"utf8"):null}catch{return null}})}var jb,SO,Vo=_(()=>{"use strict";jt();o(Fb,"hookOf");jb=Fb(Ft,Qe),SO=Fb(Tr,"guard-inject");o(qd,"isRunnable");o(Ub,"coreBriefingWiredIn");o(Wo,"briefingChannel");o(Hb,"claudeSettingsSources")});function Bb(e){return e==="on"?!0:e==="off"?!1:null}function oe(e=process.env,t=Ne()){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:Bb(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:Bb(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function Dn(e,t=He()){let n={};try{let i=await X(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)+`
760
- `,384)}var et=_(()=>{"use strict";Ut();be();o(Bb,"envSwitch");o(oe,"resolveGuardConfig");o(Dn,"writeGuardConfig")});function qo(e){if(!e)return null;let t=e.split(`
760
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as QO}from"node:crypto";function Fr(e){return QO("sha256").update(e,"utf8").digest("hex")}function Ub(e){return{node_key_hash:Fr(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Fr(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Fr(e.signature):null}}function Bb(e){return{src_key_hash:Fr(e.srcKey),dst_key_hash:Fr(e.dstKey),kind:e.kind}}function Gb(e,t,n){return{node_key_hash:Fr(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Kb=v(()=>{"use strict";s(Fr,"sha256");s(Ub,"toCloudNode");s(Bb,"toCloudEdge");s(Gb,"toCloudEmbedding")});import{randomUUID as eD}from"node:crypto";function ru(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Wb(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Vb(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var jr,Hr,tD,iu=v(()=>{"use strict";Er();Kb();jr=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Hr=class{static{s(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(xr),lastSyncedAt:Wb(await this.store.getMeta(nd))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Ub),n=(await this.store.getAllEdges()).map(Bb),r=await this.store.getMeta(jt)??Ft,i=await this.store.getMeta(xr),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=eD(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},d=0,u=ru(t,this.chunk),p=ru(n,this.chunk*2),f=Math.max(1,u.length+p.length);for(let _ of u)await this.post("/api/codebase/push",{...l,nodes:_,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:f});for(let _ of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:_,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 m=t.map(_=>_.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,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(nd,String(Date.now())),i&&await this.store.setMeta(Ny,i),{nodes:t.length,edges:n.length,pruned:Vb(g.nodes_deleted),edgesPruned:Vb(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}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Gb(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&o[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=ru(a,tD),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(ys),r=Wb(await this.store.getMeta(_s));if(!t||!n||!r)throw new jr("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 o=i?.error;throw new jr(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},tD=250;s(ru,"chunkArray");s(Wb,"numOrNull");s(Vb,"numOr0")});var su={};Q(su,{CodeIndexSync:()=>Hr,DEFAULT_DB_RELPATH:()=>ou,SyncError:()=>jr,createCodeIndexSync:()=>rD,createNodeCodeIndex:()=>na,openIndexReader:()=>iD,openSqliteDatabase:()=>Zs,openSqliteReadOnly:()=>Xs,probeBuiltinSqlite:()=>Lr});import{mkdirSync as nD}from"node:fs";import{posix as ta}from"node:path";function na(e){let t=e.dbPath??ta.join(e.repoRoot,ou);nD(ta.dirname(t),{recursive:!0}),e.dbPath===void 0&&_i(ta.dirname(t));let n=new Vi(t),r=new Js;return new Oi({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function rD(e){let t=e.dbPath??ta.join(e.repoRoot,ou),n=e.projectKey??Sg(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 Vi(t);return new Hr(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function iD(e){return ud(Xs(e).db)}var ou,ra=v(()=>{"use strict";ml();Tb();od();pd();Hb();Qs();iu();Xo();iu();Qs();ou=".maind/code-index.sqlite";s(na,"createNodeCodeIndex");s(rD,"createCodeIndexSync");s(iD,"openIndexReader")});import{execFileSync as zb}from"node:child_process";import{existsSync as qb,realpathSync as Jb}from"node:fs";import{createRequire as oD}from"node:module";import{basename as sD,dirname as aD,isAbsolute as Yb,join as cD,relative as Xb,resolve as ia,sep as Zb}from"node:path";function oa(){let e=Lr();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return oD(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 Qb(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 Se(e=process.cwd()){try{let t=zb("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 tv(e,t=Se(),n=process.cwd()){let r=Yb(e)?[e]:[ia(t,e),ia(n,e)];for(let i of r){let o=aD(i);if(!qb(o))continue;let a;try{a=Jb(o)}catch{continue}let c=nv(a);if(c===null)continue;let l=Xb(c,cD(a,sD(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Zb).join("/")}}return null}function Ur(e,t=Se(),n=process.cwd()){let r=Yb(e)?[e]:[ia(t,e),ia(n,e)];for(let i of r){if(!qb(i))continue;let o;try{o=Jb(i)}catch{continue}let a=nv(o);if(a===null)continue;let c=Xb(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Zb).join("/")}}return null}function nv(e){try{let t=zb("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 rv(){return na({repoRoot:Se()})}function iv(e){return na({repoRoot:e})}var ev,Zt=v(()=>{"use strict";ra();s(oa,"probeNativeStore");s(Qb,"isNativeStoreUnavailable");ev="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.";s(Se,"resolveRepoRoot");s(tv,"resolveRepoRootForPath");s(Ur,"resolveRepoRootForDir");s(nv,"gitToplevelOf");s(rv,"defaultEngineFactory");s(iv,"engineForRoot")});async function Br(e){return kt("get_session_briefing",{tools:["claude-code"]},e)}async function kt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??zi,i=new AbortController,o=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:lD,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 ov(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let _=null;try{let b=JSON.parse(d);typeof b.result?.instructions=="string"&&(_=b.result.instructions)}catch{_=null}n.onInitialize(_)}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(_=>_.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 m=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await ov(p):await p.text();if(m.trim().length===0)return null;let g=JSON.parse(m);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(o)}}async function ov(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",a=s(()=>{if(i.length===0)return;let c=i.join(`
761
+ `).trim();i=[],c.length>0&&(o=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(`
762
+ `))!==-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(),o}var zi,lD,Qt=v(()=>{"use strict";zi="https://mcp.maind.dev/mcp",lD="2025-06-18";s(Br,"fetchSessionBriefing");s(kt,"fetchToolText");s(ov,"readSseMessage")});async function G(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=s(o=>{n||(n=!0,clearTimeout(i),t(o))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",o=>e.push(o)),process.stdin.on("end",()=>{try{let o=Buffer.concat(e).toString("utf-8").trim();r(o?JSON.parse(o):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function Gr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Me(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=v(()=>{"use strict";s(G,"readHookInput");s(Gr,"transcriptPathOf");s(Me,"toolFilePathOf")});function Un(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function Bn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function qi(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function sa(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function au(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Ji=v(()=>{"use strict";s(Un,"denyPayload");s(Bn,"advisoryPayload");s(qi,"postAdvisoryPayload");s(sa,"postFailureAdvisoryPayload");s(au,"promptAdvisoryPayload")});function dD(e){return Gn(e)&&/[\\/]\.claude[^\\/]*[\\/]projects[\\/]/.test(e)}function Yi(e,t=process.env){return Gn(e.cursor_version)?"cursor":dD(e.transcript_path)?"claude-code":Gn(t.CURSOR_VERSION)?"cursor":Gn(t.DEVIN_PROJECT_DIR)?"devin":Gn(t.CLAUDE_PROJECT_DIR)||t.CLAUDECODE==="1"?"claude-code":"unknown"}function sv(e,t=process.env){return Yi(e,t)==="cursor"}function en(e){return e==="cursor"||e==="devin"}function Ve(e,t=process.env){return en(Yi(e,t))}function uD(e=process.env,t=null){let n=e.MAIND_DEVIN_HOOK_OUTPUT?.trim().toLowerCase();return n==="off"?!1:n==="on"?!0:t?.devin_hook_output!==!1}function re(e,t=process.env,n=te){let r=Yi(e,t);return{host:r,devinOutput:r==="devin"?uD(t,n()):!1}}function pD(e){switch(e.kind){case"text":return e.text;case"deny":return Un(e.reason);case"context":switch(e.event){case"UserPromptSubmit":return au(e.text);case"PreToolUse":return Bn(e.text);case"PostToolUse":return qi(e.text);case"PostToolUseFailure":return sa(e.text)}}}function fD(e){return e.kind==="deny"?JSON.stringify({permission:"deny",user_message:e.reason,agent_message:e.reason}):null}function mD(e){switch(e.kind){case"text":return JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.text.replace(/\s+$/,"")}});case"deny":return JSON.stringify({decision:"block",reason:e.reason});case"context":return e.event==="UserPromptSubmit"?au(e.text):e.event==="PostToolUse"?qi(e.text):null}}function ce(e,t){switch(e.host){case"claude-code":case"unknown":return pD(t);case"cursor":return fD(t);case"devin":return e.devinOutput?mD(t):null}}function ye(e,t){let n=t.kind==="deny"?{kind:"deny",reason:"x"}:{...t,text:"x"};return ce(e,n)!==null}function aa(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}function ca(e,t=process.env){return e.host==="devin"&&Gn(t.DEVIN_PROJECT_DIR)?t.DEVIN_PROJECT_DIR.trim():e.host==="cursor"&&Gn(t.CURSOR_PROJECT_DIR)?t.CURSOR_PROJECT_DIR.trim():null}var Gn,Re=v(()=>{"use strict";We();Ji();Gn=s(e=>typeof e=="string"&&e.trim().length>0,"filled");s(dD,"isClaudeCodeTranscript");s(Yi,"detectHookHost");s(sv,"runsUnderCursor");s(en,"isForeignHost");s(Ve,"guardStandsDown");s(uD,"devinOutputEnabled");s(re,"resolveHookTarget");s(pD,"claudeCodeBytes");s(fD,"cursorBytes");s(mD,"devinBytes");s(ce,"renderHookOutput");s(ye,"hostDelivers");s(aa,"writeHookStdout");s(ca,"hostProjectDir")});import{existsSync as hD,readFileSync as gD}from"node:fs";import{join as cu}from"node:path";function av(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function lu(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function lv(e,t={}){return e.some(n=>lu(Te(n,t,[cv])[0]))}function la(e,t){let n=Te(e,t,[cv])[0],r=Te(e,t,[yD])[0];return{channel:lu(n)?"core":lu(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function dv(e,t){let n=[cu(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(cu(t,".claude","settings.json"),cu(t,".claude","settings.local.json")),n.map(r=>{try{return hD(r)?gD(r,"utf8"):null}catch{return null}})}var cv,yD,da=v(()=>{"use strict";at();s(av,"hookOf");cv=av(st,ot),yD=av($r,"guard-inject");s(lu,"isRunnable");s(lv,"coreBriefingWiredIn");s(la,"briefingChannel");s(dv,"claudeSettingsSources")});function uv(e){return e==="on"?!0:e==="off"?!1:null}function le(e=process.env,t=te()){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:uv(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:uv(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function Kn(e,t=Ke()){let n={};try{let i=await X(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await z(t,JSON.stringify(r,null,2)+`
763
+ `,384)}var ct=v(()=>{"use strict";We();xe();s(uv,"envSwitch");s(le,"resolveGuardConfig");s(Kn,"writeGuardConfig")});function pa(e){if(!e)return null;let t=e.split(`
761
764
  `),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(`
762
- `):null}function xO(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(`
763
- `),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 Jo(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
764
- `);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...xO(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
765
-
766
- ${d.title}`;if(zo(c+u)>a){l=!1;break}c+=u;for(let f=0;f<d.lines.length;f++){let p=`
767
- ${d.lines[f]}`;if(zo(c+p)<=a){c+=p;continue}l=!1;let h=`
768
- (+${d.lines.length-f} more \u2014 via ${d.more})`;zo(c+h)<=r&&(c+=h);break}if(!l)break}if(!l){let d=`
769
- \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;zo(c+d)<=r&&(c+=d)}return{text:c+`
770
- `,complete:l}}var zo,Yo=_(()=>{"use strict";zo=o(e=>Buffer.byteLength(e,"utf8"),"bytes");o(qo,"extractConventionsBlock");o(xO,"briefingSections");o(Jo,"composeInjection")});import{mkdir as EO,readFile as TO,writeFile as RO,rename as AO}from"node:fs/promises";import{existsSync as Kb}from"node:fs";import{homedir as CO}from"node:os";import{join as Wb}from"node:path";function Gb(){return{config:null,sessions:{},pending_metrics:[]}}async function Q(){if(!Kb(Xo))return Gb();try{let e=await TO(Xo,"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)}
771
- `),Gb()}}async function tt(e){Kb(ke)||await EO(ke,{recursive:!0,mode:448});let t=`${Xo}.tmp`;await RO(t,JSON.stringify(e,null,2),{mode:384}),await AO(t,Xo)}function Jd(e){return e.thresholds??e.config?.thresholds??IO}var ke,Xo,IO,De=_(()=>{"use strict";ke=Wb(CO(),".maind"),Xo=Wb(ke,"state.json"),IO={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};o(Gb,"emptyState");o(Q,"loadState");o(tt,"saveState");o(Jd,"resolveThresholds")});import{existsSync as zb}from"node:fs";import{mkdir as NO,readFile as OO,readdir as DO,rename as PO,stat as MO,unlink as $O,writeFile as LO}from"node:fs/promises";import{join as Fi}from"node:path";function qb(e){return Fi(Yd,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function mt(e){try{let t=qb(e);if(!zb(t))return{};let n=JSON.parse(await OO(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function ve(e,t){await NO(Yd,{recursive:!0,mode:448});let n=qb(e),r=`${n}.tmp`;await LO(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await PO(r,n)}async function Jb(e=7*24*60*60*1e3,t=Date.now()){await Vb(Yd,".json",e,t),await Vb(Xd,".jsonl",e,t)}async function Vb(e,t,n,r){try{if(!zb(e))return;for(let i of await DO(e)){if(!i.endsWith(t))continue;let s=Fi(e,i);try{let a=await MO(s);r-a.mtimeMs>n&&await $O(s)}catch{}}}catch{}}var Be,Yd,Xd,ht=_(()=>{"use strict";De();Be=Fi(ke,"guard"),Yd=Fi(Be,"sessions"),Xd=Fi(Be,"triggers");o(qb,"sessionFile");o(mt,"loadGuardSession");o(ve,"saveGuardSession");o(Jb,"sweepOldGuardSessions");o(Vb,"sweepDir")});import{existsSync as FO}from"node:fs";import{appendFile as jO,mkdir as UO,open as HO}from"node:fs/promises";import{join as BO}from"node:path";async function Z(e){try{await UO(Be,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
772
- `;await jO(Pn,t,{mode:384})}catch{}}async function Yb(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(!FO(Pn))return t;let n=await HO(Pn,"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(`
773
- `);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 Pn,gt=_(()=>{"use strict";ht();Pn=BO(Be,"events.jsonl");o(Z,"appendGuardEvent");o(Yb,"readGuardEventCounts")});var tw={};ee(tw,{BRIEFING_CACHE_FILE:()=>Pr,UNAVAILABLE_LINE:()=>Qb,carriesBriefing:()=>Zb,deliverSessionBriefing:()=>Zo,formatInjection:()=>ew,resolveBriefingInjection:()=>Mr,runGuardInject:()=>QO,runsUnderCursor:()=>ji});import{existsSync as GO}from"node:fs";import{mkdir as KO,readFile as WO,rename as VO,writeFile as zO}from"node:fs/promises";import{homedir as qO}from"node:os";import{dirname as JO,join as YO}from"node:path";async function Mr(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??Pr,s=n.fetcher??Or,a=await nD(i),c=a!==null&&a.format===Xb&&r-Date.parse(a.fetched_at)<XO&&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=qo(f)},"onInitialize"),apiKey:t,deviceId:iD(),projectKey:e,bridgeVersion:G,timeoutMs:ZO});if(u!==null){let f=d;return await rD(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:Xb,...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 QO(){try{if(oe().mode==="off")return 0;let t=await K();return Ub(Hb(qO(),tD(t)))?0:await Zo("guard",t)}catch{return 0}}function Zb(e){return e==="resume"||e==="fork"}function ji(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 eD(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Zo(e,t,n={}){let r=n.write??eD;if(ji(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 Jb();let s=typeof t.source=="string"?t.source:"startup";if(Zb(s)){let h=await mt(i);return await ve(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 Mr(l,a,n.inject),u=await mt(i);if(d.text===null)return await ve(i,{...u,inject_failed:!0}),await Z({event:"inject_fail",session_id:i,cwd:c,project_key:l??void 0,...e==="core"?{detail:"core"}:{}}),await r(Qb),0;let f=ew(d.text,d.via,d.conventions??null,e);await r(f.text),await ve(i,{...u,injected:!0});let p=f.complete?d.via:`${d.via}+budget`;return await Z({event:"inject_ok",session_id:i,cwd:c,project_key:l??void 0,detail:e==="core"?`core:${p}`:p}),0}function tD(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 ew(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 Jo(a,n,e)}async function nD(e){try{if(!GO(e))return null;let t=JSON.parse(await WO(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 rD(e,t){try{await KO(JO(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await zO(n,JSON.stringify(t,null,2),{mode:384}),await VO(n,e)}catch{}}function iD(){try{return re()}catch{return null}}var Pr,XO,Xb,ZO,Qb,Mn=_(()=>{"use strict";ie();pe();Vo();ge();Ue();et();Yo();gt();ht();zt();Pr=YO(Be,"briefing-cache.json"),XO=12*60*60*1e3,Xb=2,ZO=3e3;o(Mr,"resolveBriefingInjection");o(QO,"runGuardInject");o(Zb,"carriesBriefing");o(ji,"runsUnderCursor");o(eD,"writeStdout");o(Zo,"deliverSessionBriefing");Qb=`[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.
774
- `;o(tD,"projectDirOf");o(ew,"formatInjection");o(nD,"readCache");o(rD,"writeCache");o(iD,"safeDeviceId")});var fw={};ee(fw,{AGENTS_MD_READER_FAMILIES:()=>ow,AGENTS_MD_REFRESH_DEBUG_ENV:()=>lw,AGENTS_MD_REFRESH_INTERVAL_MS:()=>aw,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>cw,AGENTS_MD_REFRESH_STATE_FILE:()=>sw,gitToplevel:()=>dw,loadConventionsForAgentsMd:()=>Qo,readsAgentsMd:()=>$r,refreshAgentsMdConventions:()=>Zd,refreshAgentsMdForSession:()=>yD});import{execFileSync as sD}from"node:child_process";import{createHash as oD}from"node:crypto";import{mkdir as aD,readFile as cD,realpath as lD,rename as dD,writeFile as uD}from"node:fs/promises";import{dirname as fD,isAbsolute as pD,join as iw,relative as mD,resolve as hD}from"node:path";function $r(e){return e!==null&&ow.includes(e)}async function Qo(e,t,n){if(e===null)return null;let r=n.clientFamily??"codex",i=await Mr(t,e,{fetcher:n.allowFetch?s=>Or({...s,clientFamily:r}):async()=>null});return i.text===null?null:i.conventions??null}async function Zd(e,t){let n=t.err??(r=>process.stderr.write(`${r}
775
- `));try{if(!$r(e))return{status:"skipped",reason:"family"};let r=t.env??process.env;if(bD(r))return{status:"skipped",reason:"opt-out"};let i=t.cwd??process.cwd(),s=(t.gitToplevel??dw)(i);if(s===null)return Qd(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 ${i} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await rw(s),c=[];for(let T of await(t.findRoots??bo)(i)){let b=await rw(T);_D(b,a)&&!c.includes(b)&&c.push(b)}c.includes(a)||c.push(a);let l=null,d=null;for(let T of c){let b=iw(T,"AGENTS.md"),S=await X(b);if(S!==null&&Eo(S,Cn)){l=b,d=S;break}}if(l===null||d===null)return Qd(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 no AGENTS.md with the "${Cn}" 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??sw,p=await vD(f),h=wD(l),g=p.roots[h]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<aw)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let w=await(t.loadConventions??((T,b)=>Qo(b,T,{allowFetch:!0,clientFamily:e??void 0})))(t.projectKey,t.apiKey);if(w===null||w.trim().length===0)return{status:"skipped",reason:"no-conventions"};let v=xo(w,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??G}),k=To(d,v,Cn);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 kD(f,p,h,u),!k.changed)return{status:"unchanged",file:l};let x=A_(v);return n(`maind: AGENTS.md conventions block refreshed (${x} conventions)`),{status:"refreshed",file:l,conventions:x,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}}}async function yD(e,t){let n=await Zd(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-agents-md-in-repo"||t.listRoots===void 0)return n;let r=t.env??process.env,i=t.err??(l=>process.stderr.write(`${l}
776
- `)),s;try{s=await t.listRoots()}catch{s=null}if(s===null||s.length===0)return Qd(r)&&i("maind: AGENTS.md conventions block skipped \u2014 the working directory gave no repository with our AGENTS.md, "+(s===null?"and the client offers no workspace roots (no MCP roots capability, or no answer)":"and the client lists no workspace roots")),n;let a=t.cwd??process.cwd(),c=n;for(let l of s){if(l===a)continue;let d=await Zd(e,{...t,cwd:l,projectKey:(t.projectKeyFor??Pt)(l)??t.projectKey});nw(d)>nw(c)&&(c=d)}return c}function nw(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function dw(e){try{let t=sD("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 _D(e,t){let n=mD(t,e);return n===""||!n.startsWith("..")&&!pD(n)}async function rw(e){try{return await lD(e)}catch{return hD(e)}}function bD(e){return uw(e[cw])}function Qd(e){return uw(e[lw])}function uw(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function wD(e){return oD("sha256").update(e).digest("hex")}async function vD(e){let t={version:1,roots:{}};try{let n=JSON.parse(await cD(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 kD(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<gD&&(i[a]=c)}i[n]={checked_at:new Date(r).toISOString()},await aD(fD(e),{recursive:!0,mode:448});let s=`${e}.${process.pid}.tmp`;await uD(s,JSON.stringify({version:1,roots:i},null,2),{mode:384}),await dD(s,e)}var sw,ow,aw,cw,lw,gD,ea=_(()=>{"use strict";zt();Mn();ht();wd();be();vd();gd();ge();Ue();sw=iw(Be,"agents-md-refresh.json"),ow=["codex","cursor","windsurf","copilot"];o($r,"readsAgentsMd");aw=12*60*60*1e3,cw="MAIND_NO_AGENTS_MD_REFRESH",lw="MAIND_DEBUG",gD=30*24*60*60*1e3;o(Qo,"loadConventionsForAgentsMd");o(Zd,"refreshAgentsMdConventions");o(yD,"refreshAgentsMdForSession");o(nw,"rank");o(dw,"gitToplevel");o(_D,"isWithin");o(rw,"realpathOrResolve");o(bD,"isOptedOut");o(Qd,"isDebug");o(uw,"isSet");o(wD,"fileKey");o(vD,"readState");o(kD,"writeState")});import{mkdirSync as bw,rmdirSync as ww,statSync as RD}from"node:fs";import{join as vw}from"node:path";import{setTimeout as AD}from"node:timers/promises";function kw(e){return vw(e,".maind","index-refresh.lock")}function ra(e,t=Date.now()){let n=kw(e);try{if(t-RD(n).mtimeMs<CD)return!1;ww(n)}catch{}try{return bw(n,{recursive:!1}),!0}catch{return!1}}function Ui(e){try{ww(kw(e))}catch{}}async function Sw(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(a=>AD(a).then(()=>{})),s=r()+(n.waitMs??3e4);try{bw(vw(e,".maind"),{recursive:!0})}catch{}for(;!ra(e,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Ui(e)}}var CD,eu=_(()=>{"use strict";CD=30*6e4;o(kw,"lockPath");o(ra,"acquireLock");o(Ui,"releaseLock");o(Sw,"withIndexLock")});import{execFile as jw}from"node:child_process";import{randomUUID as ZD}from"node:crypto";function iP(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return ou.test(t)?t:ZD()}function au(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function sP(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 oP(e){return await new Promise(t=>{jw("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(aP(r))})})}function aP(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 cP(){return await new Promise(e=>{jw("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 lP(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function dP(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=ou.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(s=>{ou.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var Fw,Uw,QD,eP,tP,nP,rP,ou,aa,cu=_(()=>{"use strict";Ut();Fw=45e3,Uw=3e4,QD=5,eP=120,tP=3e4,nP=15*6e4,rP=1500,ou=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(iP,"resolveClientSessionId");o(au,"autoAnnounceDisabled");o(sP,"autoWorkingPathsEnabled");aa=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??Ne)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??cP,this.gitBranchObject=t.gitBranchObject??oP,this.log=t.log??(i=>process.stderr.write(i+`
777
- `)),this.machineLabel=lP(r?.machine_label),this.enabled=this.projectKey!==null&&!au(n,r),this.workingPathsEnabled=sP(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??dP(n,iP(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<Fw||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<Fw||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<QD||(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,rP).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(tP*2**(this.consecutiveFailures-1),nP);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:eP,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(oP,"defaultGitBranchObject");o(aP,"normalizeObjectId");o(cP,"defaultGitBranch");o(lP,"normalizeMachineLabel");o(dP,"staticIdentity")});import{mkdirSync as Hw,readdirSync as Ww,readFileSync as uP,renameSync as Bw,statSync as fP,unlinkSync as lu,writeFileSync as Gw}from"node:fs";import{homedir as pP}from"node:os";import{join as Lr}from"node:path";function Vw(){return Lr(pP(),".maind","presence")}function zw(e,t){return Lr(e,t)}function qw(e){let t=e.baseDir??Vw(),n=zw(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{lu(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=ms(f.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};Hw(n,{recursive:!0,mode:448});let h=Lr(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;Gw(g,JSON.stringify(p),{mode:384}),Bw(g,h),l(h),Kw(n,a(),h)}catch{}},endSession(){try{c&&lu(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};Hw(n,{recursive:!0,mode:448});let p=Lr(n,`${u.sessionId}.json`),h=`${p}.tmp-${r}`;Gw(h,JSON.stringify(f),{mode:384}),Bw(h,p),l(p),Kw(n,a(),p)}catch{}}}}function Kw(e,t,n){try{for(let r of Ww(e)){if(!r.endsWith(".json"))continue;let i=Lr(e,r);if(i!==n)try{t-fP(i).mtimeMs>mP&&lu(i)}catch{}}}catch{}}function Fn(e,t=Vw()){try{let n=zw(t,e),r=[];for(let i of Ww(n))if(i.endsWith(".json"))try{let s=JSON.parse(uP(Lr(n,i),"utf8")),a=hP(s);a&&r.push(a)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function hP(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=ms(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var mP,ca=_(()=>{"use strict";Xr();mP=120*6e4;o(Vw,"presenceSnapshotBaseDir");o(zw,"projectDir");o(qw,"createSnapshotStore");o(Kw,"pruneStale");o(Fn,"readSnapshots");o(hP,"parseSnapshot")});import{execFileSync as gP}from"node:child_process";import{createHash as yP,randomUUID as _P}from"node:crypto";import{existsSync as bP,mkdirSync as wP,readdirSync as vP,readFileSync as Yw,renameSync as kP,statSync as du,unlinkSync as Xw,writeFileSync as SP}from"node:fs";import{homedir as xP}from"node:os";import{basename as EP,join as qt}from"node:path";function Fr(e){return qt(e??qt(xP(),".maind","presence"),"identity")}function Bi(e,t){if(e){let n=EP(e).replace(/\.jsonl$/i,"");if(Hi.test(n))return n.toLowerCase()}return t&&Hi.test(t)?t.toLowerCase():null}function Zw(e){let t=e.nowMs??Date.now();wP(e.dir,{recursive:!0,mode:448});let n=qt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(Yw(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}:{}};SP(r,JSON.stringify(c,null,2)+`
778
- `,{mode:384}),kP(r,n),IP(e.dir,t)}function Qw(e,t,n,r=Date.now()){try{let i=du(qt(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function ev(e,t){try{Xw(qt(e,`${t}.json`))}catch{}}function IP(e,t){try{for(let n of vP(e))if(n.endsWith(".json"))try{let r=du(qt(e,n));t-r.mtimeMs>RP&&Xw(qt(e,n))}catch{}}catch{}}function NP(e){return tv(e)?.file??null}function tv(e){let t=qt(e.dir,`${e.agentPid}.json`);try{if(!bP(t))return null;let n=du(t);if(n.mtimeMs<e.bridgeStartMs-AP)return null;let r=JSON.parse(Yw(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Hi.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!OP(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function Jw(e){return e.replace(/\/+$/,"")}function OP(e,t){let n=Jw(e),r=Jw(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function DP(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=yP("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 PP(e){if(process.platform==="win32")return null;try{let t=gP("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function MP(){try{return re()}catch{return null}}var Hi,TP,RP,AP,CP,la,da=_(()=>{"use strict";ie();Hi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,TP=8,RP=48*60*6e4,AP=6e4,CP="9f3c72da-2f10-4b8f-9c31-ad291c0de291";o(Fr,"identityDirPath");o(Bi,"transcriptStemOf");o(Zw,"writeAgentIdentityFile");o(Qw,"identityFileStale");o(ev,"deleteAgentIdentityFile");o(IP,"pruneIdentityDir");o(NP,"readAgentIdentityFile");o(tv,"readAgentIdentityEntry");o(Jw,"normDir");o(OP,"sameSessionTree");o(DP,"uuidV5");o(PP,"processStartTime");la=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??Fr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Hi.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??MP)(),s=(t.ppidStart??PP)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=DP(`${i}|${this.agentPid}|${s}|${t.projectKey}`,CP),this.source="derived";return}this.id=_P(),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(!Hi.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>TP&&this.aliases.shift())}activityAtMs(){return tv({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 NP({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};o(MP,"defaultDeviceId")});function uu(){return{ultracode:!1,planMode:!1,autoMode:!1}}var fu=_(()=>{"use strict";o(uu,"newModeState")});import{createReadStream as $P,existsSync as LP}from"node:fs";import{stat as FP}from"node:fs/promises";import{createInterface as jP}from"node:readline";async function pu(e){if(!e||!LP(e))return null;let t;try{t=await FP(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(a=>{let c=$P(e,{encoding:"utf-8"}),l=jP({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 nv=_(()=>{"use strict";o(pu,"summariseTranscript")});var rv=_(()=>{"use strict"});function Gi(e){if(!e)return null;let t=null;for(let n of e.matchAll(HP)){let r=n[1].toLowerCase();UP.has(r)&&(t=r)}return t}var UP,HP,ua=_(()=>{"use strict";UP=new Set(["low","medium","high","xhigh","max"]),HP=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;o(Gi,"detectEffortLevel")});import{createReadStream as BP,existsSync as GP,readdirSync as KP}from"node:fs";import{basename as ov,dirname as WP,join as iv}from"node:path";import{createInterface as VP}from"node:readline";function cv(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!JP.test(n)||e.ids.includes(n)||e.ids.length>=av||e.ids.push(n)}function YP(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(fa)||qP.has(r.name))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?cv(e,i.session_id):r.name===`${fa}announce_session`&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function XP(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 ZP(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=XP(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}cv(e,s)}}function jr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function eM(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=QP[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 pa(e){let t=ov(e).replace(/\.jsonl$/,""),n=iv(WP(e),t,"subagents"),r;try{r=KP(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>iv(n,i))}async function sv(e,t,n,r,i,s){GP(e)&&await new Promise(a=>{let c=BP(e,{encoding:"utf-8"}),l=VP({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"){ZP(s,p.message.content);return}if(p.message?.role!=="assistant")return;YP(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}`,w=eM(p.message.content),v=r.get(y);if(v){for(let S of w)v.edited_paths.includes(S)||v.edited_paths.push(S);return}if(n.has(y))return;n.add(y);let k=p.message.usage??{},x=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,T=typeof p.message.model=="string"&&p.message.model?p.message.model:"",b={ts:Number.isFinite(x)?x:0,model:T||"<unknown>",synthetic:T===zP,input_tokens:jr(k.input_tokens),output_tokens:jr(k.output_tokens),cache_read_tokens:jr(k.cache_read_input_tokens),cache_creation_tokens:jr(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(jr(k.cache_creation?.ephemeral_1h_input_tokens),jr(k.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:w,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(y,b),i.push(b)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function mu(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 Ki(e){let t=new Set,n=new Map,r=[],i=e?pa(e):[],s={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:i,coordination_ids:[]};let a=[];await sv(e,jn,t,n,a,s),mu(a),r.push(...a);for(let c of i){let l=[],d=ov(c).replace(/\.jsonl$/,"");s.pendingAnnounce.clear(),await sv(c,d,t,n,l,s),mu(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:i,coordination_ids:s.ids}}var jn,zP,fa,qP,JP,av,QP,ma=_(()=>{"use strict";jn="main",zP="<synthetic>",fa="mcp__maind__",qP=new Set([`${fa}get_session_analysis`,`${fa}get_session_cost_context`]),JP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,av=32;o(cv,"addCoordinationId");o(YP,"noteCoordinationUse");o(XP,"resultText");o(ZP,"noteAnnounceResult");QP={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};o(jr,"num");o(eM,"editedPathsOf");o(pa,"subagentFilesOf");o(sv,"readStream");o(mu,"fillTimestamps");o(Ki,"collectTurns")});import{createReadStream as lv,existsSync as tM}from"node:fs";import{createInterface as dv}from"node:readline";function cM(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 ha(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function lM(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
779
- `)}function dM(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 uM(e,t,n){return nM.test(e)?{polarity:-1,magnitude:Ur.rework,kind:"rework"}:n&&rM.test(e)?{polarity:-1,magnitude:Ur.correction,kind:"correction"}:iM.test(e)?{polarity:1,magnitude:Ur.acceptance,kind:"acceptance"}:t!==null&&dM(t,e)?{polarity:-1,magnitude:Ur.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function fM(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:uv,behaviour_measured:!0}}async function pM(e,t){for(let n of pa(e))await new Promise(r=>{let i=dv({input:lv(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 ha(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(ga))continue;let d=l.name.slice(ga.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 hu(e,t={}){let n=fM("");if(!e||!tM(e))return n;let r=t.turns??(await Ki(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=lv(e,{encoding:"utf-8"}),y=dv({input:g}),w=o(v=>{let k=v.trim();if(!k)return;let x;try{x=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let F=x.sessionId??x.session_id;typeof F=="string"&&F&&(n.session_id=F)}x.type==="ai-title"&&typeof x.aiTitle=="string"&&x.aiTitle&&(n.ai_title=x.aiTitle),typeof x.slug=="string"&&x.slug&&(n.session_slug=x.slug);let T=x.message?.role,b=x.isSidechain===!0;if(T==="assistant")for(let F of ha(x.message?.content)){if(F.type!=="tool_use"||typeof F.name!="string"||!F.name.startsWith(ga))continue;let W=F.name.slice(ga.length);W&&(n.maind_tool_calls??={},n.maind_tool_calls[W]=(n.maind_tool_calls[W]??0)+1)}if(b)return;if(T==="assistant"){let F=ha(x.message?.content),W=!1;for(let _t of F)_t.type==="tool_use"&&(n.tool_calls++,W=!0,_t.name==="AskUserQuestion"&&n.agent_questions++);c=W;return}if(T!=="user")return;let S=ha(x.message?.content),N=lM(S);if(N.includes(sM)){n.interrupts++,i.push({polarity:-1,magnitude:Ur.interrupt,kind:"interrupt"});return}if(S.some(F=>F.type==="tool_result"&&F.is_error===!0&&typeof F.content=="string"&&F.content.includes(oM))){n.tool_denials++,i.push({polarity:-1,magnitude:Ur.denial,kind:"denial"});return}if(S.some(F=>F.type==="tool_result")||!N.trim())return;n.user_turns++,n.user_chars+=N.length;let B=Gi(N);B&&(a=B);let P=uM(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",v=>{try{w(v)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await pM(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||cM(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*aM+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 ga,uv,nM,rM,iM,sM,oM,aM,Ur,fv=_(()=>{"use strict";ua();ma();ga="mcp__maind__",uv="2026-10-01",nM=/(\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,rM=/(\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,iM=/(\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,sM="[Request interrupted by user",oM="The user doesn't want to proceed with this tool use",aM=.7,Ur={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(cM,"bumpModel");o(ha,"asBlocks");o(lM,"textOf");o(dM,"isRepeat");o(uM,"classifyGenuine");o(fM,"emptyAnalysis");o(pM,"tallySubagentMaindCalls");o(hu,"analyzeSession")});function gu(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 yu(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 _u(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 pv=_(()=>{"use strict";o(gu,"parseIngestResponse");o(yu,"describeSliceVerdict");o(_u,"ingestBody")});import{isAbsolute as mv,relative as mM,resolve as hv,sep as gv}from"node:path";function yv(e){return e>_a[1]?"above_272k":e>_a[0]?"band_200k_272k":"standard"}function _v(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ya(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Wi(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=ya(d.from);typeof d.object_id!="string"||!bu.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ya(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=ya(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:ya(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"||!bu.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"&&bu.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 ba(e,t){if(!mv(e))return null;let n=mM(hv(t),hv(e));return!n||n==="."||n.startsWith("..")||mv(n)?null:gv==="/"?n:n.split(gv).join("/")}function gM(e,t){return t===""||e===t||e.startsWith(t+"/")}function vu(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function bv(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function ku(e,t){for(let n of bv(t))if(gM(e,n.path_prefix))return n.object_id;return null}function yM(e,t){for(let n of bv(t))if(vu(e,n.path_prefix))return n.object_id;return null}function wu(e,t){return e>=t.from&&(t.to===null||e<t.to)}function wv(e,t,n,r){let i=e.ts,s=r?.anchors??[],a=t.map(c=>ku(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>wu(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=>wu(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=>wu(i,u));if(d.length){let u=t[0]??n?.rel??null,f=(u===null?d:d.filter(p=>vu(p.path_prefix,u))).sort((p,h)=>h.path_prefix.length-p.path_prefix.length);for(let p of f){let h=yM(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 Su(e,t,n){let r=t?.anchors??[],i=n.repoRoot,s=n.relativize??(i?w=>ba(w,i):null),a=o(w=>{if(!s)return[];let v=[];for(let k of w.edited_paths){let x=s(k);x!==null&&!v.includes(x)&&v.push(x)}return v},"relOf"),c=o(w=>{for(let v of w){let k=ku(v,r);if(k)return{object_id:k,rel:v}}return null},"firstAnchoredEdit"),l=new Map;for(let w of e){let v=l.get(w.stream)??[];v.push(w),l.set(w.stream,v)}let d=[...l.entries()].sort(([w],[v])=>w===jn?-1:v===jn?1:0),u=[],f=o(w=>{let v=null;for(let k of u){if(k.ts>w&&w>0)break;v=k.seg}return v},"mainSegmentAt"),p=new Map;for(let[w,v]of d){let k=v.map((T,b)=>({t:T,i:b,rels:a(T)})).sort((T,b)=>T.t.ts-b.t.ts||T.i-b.i),x=null;for(let T of k){let b=c(T.rels);if(b){x=b;break}}!x&&w!==jn&&k.length&&(x=f(k[0].t.ts));for(let T of k){let b=c(T.rels);b&&(x=b),w===jn&&u.push({ts:T.t.ts,seg:x});let S=T.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let M=wv(S,T.rels,x,t),B=yv(S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens),P=_v(S.model),F=`${M.object_id??""}|${M.source}|${P}|${B}`,W=p.get(F);W||(W={object_id:M.object_id,attribution_source:M.source,model:P,context_tier:B,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(F,W)),W.input_tokens+=S.input_tokens,W.output_tokens+=S.output_tokens,W.cache_read_tokens+=S.cache_read_tokens,W.cache_creation_tokens+=S.cache_creation_tokens,W.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,W.turns+=1,S.ts>0&&((W.firstMs===0||S.ts<W.firstMs)&&(W.firstMs=S.ts),S.ts>W.lastMs&&(W.lastMs=S.ts))}}let h=n.nowMs??Date.now(),g=[];for(let w of p.values()){let{firstMs:v,lastMs:k,...x}=w;x.first_ts=new Date(v>0?v:h).toISOString(),x.last_ts=new Date(k>0?k:h).toISOString(),g.push(x)}let y={lease:0,binding:1,claim:2,path:3,none:4};return g.sort((w,v)=>y[w.attribution_source]-y[v.attribution_source]||(w.object_id??"").localeCompare(v.object_id??"")||w.model.localeCompare(v.model)||w.context_tier.localeCompare(v.context_tier)),g}var _a,hM,bu,xu=_(()=>{"use strict";ma();_a=[2e5,272e3];o(yv,"contextTierOf");o(_v,"normalizeModelId");hM=_a[0],bu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(ya,"msOf");o(Wi,"parseCostContext");o(ba,"toRepoRelative");o(gM,"underPrefix");o(vu,"prefixesOverlap");o(bv,"sortedAnchors");o(ku,"anchorFor");o(yM,"bestAnchorOverlapping");o(wu,"inWindow");o(wv,"assignTurn");o(Su,"sliceSession")});import{mkdirSync as _M,readFileSync as bM,renameSync as wM,writeFileSync as vM}from"node:fs";import{dirname as kM,isAbsolute as wa,sep as Eu}from"node:path";function SM(e){let t=e.split(Eu).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function xM(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function Tu(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])=>wa(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 w=y.lastIndexOf("-");w>0;w=y.lastIndexOf("-",w-1)){let v=`${g==="/"?"":g}/${y.slice(0,w)}`;if(e.isDir(v)&&i(v)===v)return{root:h,key:n(v)}}return null}return null},"conventionRoot");return{of(u){if(!wa(u))return null;let f=u.split(Eu).join("/"),p=SM(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(!(!xM(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 Ru(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 Au(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:ba(n.split(Eu).join("/"),r.root)}}function Sv(e){try{let t=JSON.parse(bM(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 Vi(e){let t=new Map,n=Sv(e);for(let[r,i]of Object.entries(n.checkouts)){if(!wa(r)||!i||typeof i!="object")continue;let s=typeof i.project_key=="string"&&kv.test(i.project_key)?i.project_key:null;t.set(r,s)}return t}function zi(e,t,n=Date.now()){try{let r=Sv(e),i=new Date(n).toISOString(),s=!1;for(let c of t){if(!wa(c.root))continue;let l=c.key&&kv.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>EM)&&(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>vv)&&(delete r.checkouts[c],s=!0)}if(!s)return;_M(kM(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;vM(a,JSON.stringify(r),{mode:384}),wM(a,e)}catch{}}var vv,EM,kv,xv=_(()=>{"use strict";xu();o(SM,"dirOf");o(xM,"within");o(Tu,"createCheckoutResolver");o(Ru,"dominantProjectKey");o(Au,"relativizerFor");vv=90*24*60*60*1e3,EM=60*60*1e3,kv=/^[a-f0-9]{64}$/;o(Sv,"readMemory");o(Vi,"loadCheckoutMemory");o(zi,"rememberCheckouts")});import{homedir as TM}from"node:os";import{join as RM}from"node:path";var AM,Cu=_(()=>{"use strict";AM=RM(TM(),".codex","sessions")});var Ev=_(()=>{"use strict";Cu()});var Tv=_(()=>{"use strict"});import{createReadStream as IM,existsSync as NM}from"node:fs";import{createInterface as OM}from"node:readline";function Rv(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function MM(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
780
- `)}function Iv(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 $M(e){let t=e.message?.role;if(t==="assistant")return{holder:Rv(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Rv(e.message?.content),r=MM(n);return r.includes(DM)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(PM))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Iu(e){let t=Iv("");if(!e||!NM(e))return t;let n=null,r=0,i=0,s=null,a="human",c=[];return await new Promise(l=>{let d=IM(e,{encoding:"utf-8"}),u=OM({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 v=g.sessionId??g.session_id;typeof v=="string"&&v&&(t.session_id=v)}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 w=$M(g);if(w!==null){if(t.event_count++,w.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let v=y-s;a==="agent"?i+=v:v>=Av*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(v/1e3),c.length<Cv&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(v/1e3)}))}s=y,a=w.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 DM,PM,Av,Cv,Nv=_(()=>{"use strict";DM="[Request interrupted by user",PM="The user doesn't want to proceed with this tool use",Av=60,Cv=200;o(Rv,"asBlocks");o(MM,"textOf");o(Iv,"emptySpan");o($M,"classify");o(Iu,"analyzeSpan")});import{createReadStream as LM,existsSync as FM}from"node:fs";import{createInterface as jM}from"node:readline";function HM(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function va(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function BM(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(`
781
- `)}return""}async function Nu(e,t={}){if(!e||!FM(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:uu(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:uu(),a=t.start??0;return await new Promise(c=>{let l=LM(e,{encoding:"utf-8",start:t.start??0}),d=jM({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(),w=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 v=UM[h.attachment.type];v&&(s[HM(v.mode)]=v.active,n.push({kind:"mode",session_id:g,ts:y,mode:v.mode,active:v.active}));return}if(w==="user"){let v=BM(h.message?.content),k=Gi(v);k&&(i=k);let x={session_id:g,ts:y,text:v,effort_directive:k};n.push({kind:"user",...x});return}if(w==="assistant"){let v=h.message?.usage,k=typeof h.message?.id=="string"&&h.message.id?h.message.id:null,x=typeof h.requestId=="string"&&h.requestId?h.requestId:null,T=k??x,b=T!==null&&r.has(T);T!==null&&!b&&r.add(T);let S={session_id:g,ts:y,model:h.message?.model??null,input_tokens:b?0:va(v?.input_tokens),output_tokens:b?0:va(v?.output_tokens),cache_read_input_tokens:b?0:va(v?.cache_read_input_tokens),cache_creation_input_tokens:b?0:va(v?.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",...S})}});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 UM,Ov=_(()=>{"use strict";ua();fu();UM={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(HM,"modeFlagKey");o(va,"num");o(BM,"extractUserText");o(Nu,"streamTranscript")});var Dv=_(()=>{"use strict"});import{homedir as GM}from"node:os";import{join as KM}from"node:path";function Du(e){return e.replace(/[/.]/g,"-")}var WM,Ou,Pv=_(()=>{"use strict";WM=GM(),Ou=KM(WM,".claude","projects");o(Du,"projectPathFromCwd")});var Un=_(()=>{"use strict";fu();nv();rv();fv();pv();ma();xv();Cu();Ev();xu();Tv();Nv();Ov();ua();Dv();Pv()});import{parse as e$}from"jsonc-parser";function Pu(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 $u(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=e$(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 Hr(e,t){let n=`npm i -g ${Br}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Sa(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(f=>f.bridgeVersion).filter(f=>f!==null)],r=e.latestVersion??n.sort(Pu).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:Hr(r,g.node)})}if(new Set(i.map(g=>g.bridgeVersion)).size>1)for(let g of i.filter(y=>Pu(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:Hr(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=$u(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(Br))){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:`${Hr(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 ${Br}@${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 ${Hr(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:Hr(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 ${Br} 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(Pu(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?Hr(e.latestVersion,g):`npx -y ${Br}@${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||!Lv.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"}):t$.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&Lv.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=Ie(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=Wo(e.claudeSettings,{guardMode:f,fileExists:o(w=>e.fileExists(w),"fileExists")}),g=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Br}`)} install --hooks-only`,y=(e.declinedHooks??[]).includes(Qe);p.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${Qe} hook).`}):p.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${Qe} 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 ${Qe} 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 ${Qe} 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 (${Qe}) \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=Ie(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 Fv(e){let t=e.filter(i=>i.level==="error"&&Mu.includes(i.check)).sort((i,s)=>Mu.indexOf(i.check)-Mu.indexOf(s.check)),n=t[0];if(n===void 0)return n$(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 n$(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 jv(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(`
765
+ `):null}function _D(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(`
766
+ `),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=s((o,a)=>(o??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,o=>o.title?`- ${o.title}${o.id?` (${o.id})`:""}${o.summary?` \u2014 ${o.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,o=>o.id?`- ${o.id}${o.summary?`: ${o.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,o=>o.title?`- ${o.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,o=>o.id?`- ${o.id}${o.title?`: ${o.title}`:""}`:null),more:"search_lessons"}),r.filter(o=>o.lines.length>0)}function fa(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
767
+ `);i.push({title:d,lines:u,more:"get_conventions"})}i.push(..._D(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
768
+
769
+ ${d.title}`;if(ua(c+u)>a){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let f=`
770
+ ${d.lines[p]}`;if(ua(c+f)<=a){c+=f;continue}l=!1;let m=`
771
+ (+${d.lines.length-p} more \u2014 via ${d.more})`;ua(c+m)<=r&&(c+=m);break}if(!l)break}if(!l){let d=`
772
+ \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;ua(c+d)<=r&&(c+=d)}return{text:c+`
773
+ `,complete:l}}var ua,ma=v(()=>{"use strict";ua=s(e=>Buffer.byteLength(e,"utf8"),"bytes");s(pa,"extractConventionsBlock");s(_D,"briefingSections");s(fa,"composeInjection")});import{mkdir as bD,readFile as vD,writeFile as wD,rename as kD}from"node:fs/promises";import{existsSync as fv}from"node:fs";import{homedir as xD}from"node:os";import{join as mv}from"node:path";function pv(){return{config:null,sessions:{},pending_metrics:[]}}async function ee(){if(!fv(ha))return pv();try{let e=await vD(ha,"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)}
774
+ `),pv()}}async function lt(e){fv(Ce)||await bD(Ce,{recursive:!0,mode:448});let t=`${ha}.${process.pid}.tmp`;await wD(t,JSON.stringify(e,null,2),{mode:384}),await kD(t,ha)}function du(e){return e.thresholds??e.config?.thresholds??SD}var Ce,ha,SD,$e=v(()=>{"use strict";Ce=mv(xD(),".maind"),ha=mv(Ce,"state.json"),SD={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(pv,"emptyState");s(ee,"loadState");s(lt,"saveState");s(du,"resolveThresholds")});import{existsSync as gv}from"node:fs";import{mkdir as ED,readFile as TD,readdir as RD,rename as CD,stat as AD,unlink as ID,writeFile as ND}from"node:fs/promises";import{join as Xi}from"node:path";function yv(e){return Xi(uu,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function xt(e){try{let t=yv(e);if(!gv(t))return{};let n=JSON.parse(await TD(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Ee(e,t){await ED(uu,{recursive:!0,mode:448});let n=yv(e),r=`${n}.tmp`;await ND(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await CD(r,n)}async function _v(e=7*24*60*60*1e3,t=Date.now()){await hv(uu,".json",e,t),await hv(pu,".jsonl",e,t)}async function hv(e,t,n,r){try{if(!gv(e))return;for(let i of await RD(e)){if(!i.endsWith(t))continue;let o=Xi(e,i);try{let a=await AD(o);r-a.mtimeMs>n&&await ID(o)}catch{}}}catch{}}var ze,uu,pu,St=v(()=>{"use strict";$e();ze=Xi(Ce,"guard"),uu=Xi(ze,"sessions"),pu=Xi(ze,"triggers");s(yv,"sessionFile");s(xt,"loadGuardSession");s(Ee,"saveGuardSession");s(_v,"sweepOldGuardSessions");s(hv,"sweepDir")});import{existsSync as OD}from"node:fs";import{appendFile as DD,mkdir as PD,open as MD}from"node:fs/promises";import{join as $D}from"node:path";async function Z(e){try{await PD(ze,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
775
+ `;await DD(Wn,t,{mode:384})}catch{}}async function bv(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(!OD(Wn))return t;let n=await MD(Wn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),o=Buffer.alloc(r-i);await n.read(o,0,o.length,i);let c=o.toString("utf8").split(`
776
+ `);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 Wn,Et=v(()=>{"use strict";St();Wn=$D(ze,"events.jsonl");s(Z,"appendGuardEvent");s(bv,"readGuardEventCounts")});var Sv={};Q(Sv,{BRIEFING_CACHE_FILE:()=>Kr,UNAVAILABLE_LINE:()=>kv,carriesBriefing:()=>wv,deliverSessionBriefing:()=>ga,formatInjection:()=>xv,resolveBriefingInjection:()=>Wr,runGuardInject:()=>zD,runsUnderCursor:()=>sv});import{existsSync as LD}from"node:fs";import{mkdir as FD,readFile as jD,rename as HD,writeFile as UD}from"node:fs/promises";import{homedir as BD}from"node:os";import{dirname as GD,join as KD}from"node:path";async function Wr(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??Kr,o=n.fetcher??Br,a=await XD(i),c=a!==null&&a.format===vv&&r-Date.parse(a.fetched_at)<WD&&a.project_key===e,l=s(p=>p.conventions?{conventions:p.conventions}:{},"withConventions");if(c)return{text:a.text,via:"cache",...l(a)};let d=null,u=await o({onInitialize:s(p=>{d=pa(p)},"onInitialize"),apiKey:t,deviceId:QD(),projectKey:e,bridgeVersion:K,timeoutMs:VD});if(u!==null){let p=d;return await ZD(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:vv,...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 zD(){try{if(le().mode==="off")return 0;let t=await G();return lv(dv(BD(),YD(t)))?0:await ga("guard",t)}catch{return 0}}function wv(e){return e==="resume"||e==="fork"}function qD(e,t){let n=ca(e,t);if(n===null)return Y();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:nt(n)}function JD(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function ga(e,t,n={}){let r=n.env??process.env,i=re(t,r,n.readConfig??te);if(!ye(i,{kind:"text",event:"SessionStart"}))return 0;let o=n.write??JD,a=s(async b=>{let k=ce(i,{kind:"text",event:"SessionStart",text:b});k!==null&&await o(k)},"write"),c=en(i.host)?{host:i.host}:{},l=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(l===null)return 0;await _v();let d=typeof t.source=="string"?t.source:"startup";if(wv(d)){let b=await xt(l);return await Ee(l,{...b,carryover:!0}),0}let u=(n.apiKey??J)();if(u===null)return 0;let p=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),f=(n.projectKey??(()=>qD(i,r)))(),m=await Wr(f,u,n.inject),g=await xt(l);if(m.text===null)return await Ee(l,{...g,inject_failed:!0}),await Z({event:"inject_fail",session_id:l,cwd:p,project_key:f??void 0,...e==="core"?{detail:"core"}:{},...c}),await a(kv),0;let y=xv(m.text,m.via,m.conventions??null,e);await a(y.text),await Ee(l,{...g,injected:!0});let _=y.complete?m.via:`${m.via}+budget`;return await Z({event:"inject_ok",session_id:l,cwd:p,project_key:f??void 0,detail:e==="core"?`core:${_}`:_,...c}),0}function YD(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 xv(e,t,n=null,r="guard"){let i=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",o=`Session briefing${n?" + project conventions":""}`,a=(r==="core"?`[maind] ${o}, delivered by the bridge's session-start hook (ADR-359)${i} \u2014 `:`[maind guard] ${o}, injected deterministically (ADR-284)${i} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return fa(a,n,e)}async function XD(e){try{if(!LD(e))return null;let t=JSON.parse(await jD(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 ZD(e,t){try{await FD(GD(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await UD(n,JSON.stringify(t,null,2),{mode:384}),await HD(n,e)}catch{}}function QD(){try{return oe()}catch{return null}}var Kr,WD,vv,VD,kv,Vn=v(()=>{"use strict";We();se();ge();Re();da();we();Ge();ct();ma();Et();St();Qt();Kr=KD(ze,"briefing-cache.json"),WD=12*60*60*1e3,vv=2,VD=3e3;s(Wr,"resolveBriefingInjection");s(zD,"runGuardInject");s(wv,"carriesBriefing");s(qD,"sessionProjectKey");s(JD,"writeStdout");s(ga,"deliverSessionBriefing");kv=`[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.
777
+ `;s(YD,"projectDirOf");s(xv,"formatInjection");s(XD,"readCache");s(ZD,"writeCache");s(QD,"safeDeviceId")});var Mv={};Q(Mv,{AGENTS_MD_READER_FAMILIES:()=>Av,AGENTS_MD_REFRESH_DEBUG_ENV:()=>Ov,AGENTS_MD_REFRESH_INTERVAL_MS:()=>Iv,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>Nv,AGENTS_MD_REFRESH_STATE_FILE:()=>Cv,gitToplevel:()=>Dv,loadConventionsForAgentsMd:()=>ya,readsAgentsMd:()=>Vr,refreshAgentsMdConventions:()=>fu,refreshAgentsMdForSession:()=>pP});import{execFileSync as eP}from"node:child_process";import{createHash as tP}from"node:crypto";import{mkdir as nP,readFile as rP,realpath as iP,rename as oP,writeFile as sP}from"node:fs/promises";import{dirname as aP,isAbsolute as cP,join as Rv,relative as lP,resolve as dP}from"node:path";function Vr(e){return e!==null&&Av.includes(e)}async function ya(e,t,n){if(e===null)return null;let r=n.clientFamily??"codex",i=await Wr(t,e,{fetcher:n.allowFetch?o=>Br({...o,clientFamily:r}):async()=>null});return i.text===null?null:i.conventions??null}async function fu(e,t){let n=t.err??(r=>process.stderr.write(`${r}
778
+ `));try{if(!Vr(e))return{status:"skipped",reason:"family"};let r=t.env??process.env;if(mP(r))return{status:"skipped",reason:"opt-out"};let i=t.cwd??process.cwd(),o=(t.gitToplevel??Dv)(i);if(o===null)return mu(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 ${i} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Tv(o),c=[];for(let T of await(t.findRoots??Ms)(i)){let w=await Tv(T);fP(w,a)&&!c.includes(w)&&c.push(w)}c.includes(a)||c.push(a);let l=null,d=null;for(let T of c){let w=Rv(T,"AGENTS.md"),x=await X(w);if(x!==null&&Hs(x,$n)){l=w,d=x;break}}if(l===null||d===null)return mu(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 no AGENTS.md with the "${$n}" 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??Cv,f=await gP(p),m=hP(l),g=f.roots[m]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<Iv)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((T,w)=>ya(w,T,{allowFetch:!0,clientFamily:e??void 0})))(t.projectKey,t.apiKey);if(_===null||_.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=js(_,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??K}),k=Us(d,b,$n);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 yP(p,f,m,u),!k.changed)return{status:"unchanged",file:l};let S=X_(b);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}}}async function pP(e,t){let n=await fu(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-agents-md-in-repo"||t.listRoots===void 0)return n;let r=t.env??process.env,i=t.err??(l=>process.stderr.write(`${l}
779
+ `)),o;try{o=await t.listRoots()}catch{o=null}if(o===null||o.length===0)return mu(r)&&i("maind: AGENTS.md conventions block skipped \u2014 the working directory gave no repository with our AGENTS.md, "+(o===null?"and the client offers no workspace roots (no MCP roots capability, or no answer)":"and the client lists no workspace roots")),n;let a=t.cwd??process.cwd(),c=n;for(let l of o){if(l===a)continue;let d=await fu(e,{...t,cwd:l,projectKey:(t.projectKeyFor??nt)(l)??t.projectKey});Ev(d)>Ev(c)&&(c=d)}return c}function Ev(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function Dv(e){try{let t=eP("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 fP(e,t){let n=lP(t,e);return n===""||!n.startsWith("..")&&!cP(n)}async function Tv(e){try{return await iP(e)}catch{return dP(e)}}function mP(e){return Pv(e[Nv])}function mu(e){return Pv(e[Ov])}function Pv(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function hP(e){return tP("sha256").update(e).digest("hex")}async function gP(e){let t={version:1,roots:{}};try{let n=JSON.parse(await rP(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[i,o]of Object.entries(n.roots))o&&typeof o.checked_at=="string"&&(r[i]={checked_at:o.checked_at});return{version:1,roots:r}}catch{return t}}async function yP(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<uP&&(i[a]=c)}i[n]={checked_at:new Date(r).toISOString()},await nP(aP(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await sP(o,JSON.stringify({version:1,roots:i},null,2),{mode:384}),await oP(o,e)}var Cv,Av,Iv,Nv,Ov,uP,_a=v(()=>{"use strict";Qt();Vn();St();Md();xe();$d();Nd();we();Ge();Cv=Rv(ze,"agents-md-refresh.json"),Av=["codex","cursor","windsurf","copilot"];s(Vr,"readsAgentsMd");Iv=12*60*60*1e3,Nv="MAIND_NO_AGENTS_MD_REFRESH",Ov="MAIND_DEBUG",uP=30*24*60*60*1e3;s(ya,"loadConventionsForAgentsMd");s(fu,"refreshAgentsMdConventions");s(pP,"refreshAgentsMdForSession");s(Ev,"rank");s(Dv,"gitToplevel");s(fP,"isWithin");s(Tv,"realpathOrResolve");s(mP,"isOptedOut");s(mu,"isDebug");s(Pv,"isSet");s(hP,"fileKey");s(gP,"readState");s(yP,"writeState")});import{mkdirSync as Bv,rmdirSync as Gv,statSync as kP}from"node:fs";import{join as Kv}from"node:path";import{setTimeout as xP}from"node:timers/promises";function Wv(e){return Kv(e,".maind","index-refresh.lock")}function wa(e,t=Date.now()){let n=Wv(e);try{if(t-kP(n).mtimeMs<SP)return!1;Gv(n)}catch{}try{return Bv(n,{recursive:!1}),!0}catch{return!1}}function Zi(e){try{Gv(Wv(e))}catch{}}async function Vv(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(a=>xP(a).then(()=>{})),o=r()+(n.waitMs??3e4);try{Bv(Kv(e,".maind"),{recursive:!0})}catch{}for(;!wa(e,r());){if(r()>=o)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Zi(e)}}var SP,hu=v(()=>{"use strict";SP=30*6e4;s(Wv,"lockPath");s(wa,"acquireLock");s(Zi,"releaseLock");s(Vv,"withIndexLock")});import{execFile as cw}from"node:child_process";import{randomUUID as zP}from"node:crypto";function QP(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return wu.test(t)?t:zP()}function ku(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function eM(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 tM(e){return await new Promise(t=>{cw("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(nM(r))})})}function nM(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 rM(){return await new Promise(e=>{cw("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 iM(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function oM(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=wu.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{wu.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var aw,lw,qP,JP,YP,XP,ZP,wu,Ea,xu=v(()=>{"use strict";We();aw=45e3,lw=3e4,qP=5,JP=120,YP=3e4,XP=15*6e4,ZP=1500,wu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(QP,"resolveClientSessionId");s(ku,"autoAnnounceDisabled");s(eM,"autoWorkingPathsEnabled");Ea=class{static{s(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??te)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??rM,this.gitBranchObject=t.gitBranchObject??tM,this.log=t.log??(i=>process.stderr.write(i+`
780
+ `)),this.machineLabel=iM(r?.machine_label),this.enabled=this.projectKey!==null&&!ku(n,r),this.workingPathsEnabled=eM(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??oM(n,QP(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<aw||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<aw||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<qP||(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,ZP).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(YP*2**(this.consecutiveFailures-1),XP);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 o=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 (${o} \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:JP,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let o=await this.gitBranch();if(o&&(r.branch=o),this.lastBranch=o,o)try{let a=await this.gitBranchObject(o);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 o=i;if(o.ok===!0&&typeof o.session_id=="string")try{this.identity.adopt(o.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let o={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};s(tM,"defaultGitBranchObject");s(nM,"normalizeObjectId");s(rM,"defaultGitBranch");s(iM,"normalizeMachineLabel");s(oM,"staticIdentity")});import{mkdirSync as dw,readdirSync as mw,readFileSync as sM,renameSync as uw,statSync as aM,unlinkSync as Su,writeFileSync as pw}from"node:fs";import{homedir as cM}from"node:os";import{join as zr}from"node:path";function hw(){return zr(cM(),".maind","presence")}function gw(e,t){return zr(e,t)}function yw(e){let t=e.baseDir??hw(),n=gw(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=s(d=>{if(c!==null&&c!==d)try{Su(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:o,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[],...(()=>{let y=Ao(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};dw(n,{recursive:!0,mode:448});let m=zr(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;pw(g,JSON.stringify(f),{mode:384}),uw(g,m),l(m),fw(n,a(),m)}catch{}},endSession(){try{c&&Su(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:o,branch:u.branch,peers:[],conflicts:[],announce_error:d};dw(n,{recursive:!0,mode:448});let f=zr(n,`${u.sessionId}.json`),m=`${f}.tmp-${r}`;pw(m,JSON.stringify(p),{mode:384}),uw(m,f),l(f),fw(n,a(),f)}catch{}}}}function fw(e,t,n){try{for(let r of mw(e)){if(!r.endsWith(".json"))continue;let i=zr(e,r);if(i!==n)try{t-aM(i).mtimeMs>lM&&Su(i)}catch{}}}catch{}}function Jn(e,t=hw()){try{let n=gw(t,e),r=[];for(let i of mw(n))if(i.endsWith(".json"))try{let o=JSON.parse(sM(zr(n,i),"utf8")),a=dM(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function dM(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=Ao(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var lM,Ta=v(()=>{"use strict";si();lM=120*6e4;s(hw,"presenceSnapshotBaseDir");s(gw,"projectDir");s(yw,"createSnapshotStore");s(fw,"pruneStale");s(Jn,"readSnapshots");s(dM,"parseSnapshot")});import{execFileSync as uM}from"node:child_process";import{createHash as pM,randomUUID as fM}from"node:crypto";import{existsSync as mM,mkdirSync as hM,readdirSync as gM,readFileSync as bw,renameSync as yM,statSync as Eu,unlinkSync as vw,writeFileSync as _M}from"node:fs";import{homedir as bM}from"node:os";import{basename as vM,join as tn}from"node:path";function qr(e){return tn(e??tn(bM(),".maind","presence"),"identity")}function eo(e,t){if(e){let n=vM(e).replace(/\.jsonl$/i,"");if(Qi.test(n))return n.toLowerCase()}return t&&Qi.test(t)?t.toLowerCase():null}function ww(e){let t=e.nowMs??Date.now();hM(e.dir,{recursive:!0,mode:448});let n=tn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(bw(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 o=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(),...o?{transcript_path:o}:{},...a?{model:a}:{}};_M(r,JSON.stringify(c,null,2)+`
781
+ `,{mode:384}),yM(r,n),EM(e.dir,t)}function kw(e,t,n,r=Date.now()){try{let i=Eu(tn(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function xw(e,t){try{vw(tn(e,`${t}.json`))}catch{}}function EM(e,t){try{for(let n of gM(e))if(n.endsWith(".json"))try{let r=Eu(tn(e,n));t-r.mtimeMs>kM&&vw(tn(e,n))}catch{}}catch{}}function TM(e){return Sw(e)?.file??null}function Sw(e){let t=tn(e.dir,`${e.agentPid}.json`);try{if(!mM(t))return null;let n=Eu(t);if(n.mtimeMs<e.bridgeStartMs-xM)return null;let r=JSON.parse(bw(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Qi.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!RM(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function _w(e){return e.replace(/\/+$/,"")}function RM(e,t){let n=_w(e),r=_w(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function CM(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=pM("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 o=i.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function AM(e){if(process.platform==="win32")return null;try{let t=uM("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function IM(){try{return oe()}catch{return null}}var Qi,wM,kM,xM,SM,Ra,Ca=v(()=>{"use strict";se();Qi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,wM=8,kM=48*60*6e4,xM=6e4,SM="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(qr,"identityDirPath");s(eo,"transcriptStemOf");s(ww,"writeAgentIdentityFile");s(kw,"identityFileStale");s(xw,"deleteAgentIdentityFile");s(EM,"pruneIdentityDir");s(TM,"readAgentIdentityFile");s(Sw,"readAgentIdentityEntry");s(_w,"normDir");s(RM,"sameSessionTree");s(CM,"uuidV5");s(AM,"processStartTime");Ra=class{static{s(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??qr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Qi.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??IM)(),o=(t.ppidStart??AM)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=CM(`${i}|${this.agentPid}|${o}|${t.projectKey}`,SM),this.source="derived";return}this.id=fM(),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(!Qi.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>wM&&this.aliases.shift())}activityAtMs(){return Sw({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 TM({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(IM,"defaultDeviceId")});function Tu(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Ru=v(()=>{"use strict";s(Tu,"newModeState")});import{createReadStream as NM,existsSync as OM}from"node:fs";import{stat as DM}from"node:fs/promises";import{createInterface as PM}from"node:readline";async function Cu(e){if(!e||!OM(e))return null;let t;try{t=await DM(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=NM(e,{encoding:"utf-8"}),l=PM({input:c});l.on("line",d=>{let u=d.trim();if(u){o++;try{let p=JSON.parse(u),f=p.message?.usage;if(!f)return;let m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=m??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:o,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var Ew=v(()=>{"use strict";s(Cu,"summariseTranscript")});var Tw=v(()=>{"use strict"});function to(e){if(!e)return null;let t=null;for(let n of e.matchAll($M)){let r=n[1].toLowerCase();MM.has(r)&&(t=r)}return t}var MM,$M,Aa=v(()=>{"use strict";MM=new Set(["low","medium","high","xhigh","max"]),$M=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(to,"detectEffortLevel")});import{createReadStream as LM,existsSync as FM,readdirSync as jM}from"node:fs";import{basename as Aw,dirname as HM,join as Rw}from"node:path";import{createInterface as UM}from"node:readline";function Nw(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!KM.test(n)||e.ids.includes(n)||e.ids.length>=Iw||e.ids.push(n)}function WM(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(Ia)||GM.has(r.name))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?Nw(e,i.session_id):r.name===`${Ia}announce_session`&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function VM(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 zM(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=VM(r.content),o=null;try{let a=JSON.parse(i);a&&a.ok===!0&&(o=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(i);o=a?a[1]:null}Nw(e,o)}}function Jr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function JM(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=qM[r.name];if(!i||!r.input||typeof r.input!="object")continue;let o=r.input[i];typeof o=="string"&&o.length>0&&t.push(o)}return t}function Na(e){let t=Aw(e).replace(/\.jsonl$/,""),n=Rw(HM(e),t,"subagents"),r;try{r=jM(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>Rw(n,i))}async function Cw(e,t,n,r,i,o){FM(e)&&await new Promise(a=>{let c=LM(e,{encoding:"utf-8"}),l=UM({input:c}),d=0;l.on("line",u=>{d++;let p=u.trim();if(!p)return;let f;try{f=JSON.parse(p)}catch{return}if(f.message?.role==="user"){zM(o,f.message.content);return}if(f.message?.role!=="assistant")return;WM(o,f.message.content);let m=typeof f.message.id=="string"&&f.message.id?f.message.id:null,g=typeof f.requestId=="string"&&f.requestId?f.requestId:null,y=m??g??`${e}#${d}`,_=JM(f.message.content),b=r.get(y);if(b){for(let x of _)b.edited_paths.includes(x)||b.edited_paths.push(x);return}if(n.has(y))return;n.add(y);let k=f.message.usage??{},S=typeof f.timestamp=="string"?Date.parse(f.timestamp):Number.NaN,T=typeof f.message.model=="string"&&f.message.model?f.message.model:"",w={ts:Number.isFinite(S)?S:0,model:T||"<unknown>",synthetic:T===BM,input_tokens:Jr(k.input_tokens),output_tokens:Jr(k.output_tokens),cache_read_tokens:Jr(k.cache_read_input_tokens),cache_creation_tokens:Jr(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Jr(k.cache_creation?.ephemeral_1h_input_tokens),Jr(k.cache_creation_input_tokens)),sidechain:f.isSidechain===!0,stream:t,edited_paths:_,cwd:typeof f.cwd=="string"&&f.cwd?f.cwd:null};r.set(y,w),i.push(w)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function Au(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 no(e){let t=new Set,n=new Map,r=[],i=e?Na(e):[],o={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:i,coordination_ids:[]};let a=[];await Cw(e,Yn,t,n,a,o),Au(a),r.push(...a);for(let c of i){let l=[],d=Aw(c).replace(/\.jsonl$/,"");o.pendingAnnounce.clear(),await Cw(c,d,t,n,l,o),Au(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:i,coordination_ids:o.ids}}var Yn,BM,Ia,GM,KM,Iw,qM,Oa=v(()=>{"use strict";Yn="main",BM="<synthetic>",Ia="mcp__maind__",GM=new Set([`${Ia}get_session_analysis`,`${Ia}get_session_cost_context`]),KM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Iw=32;s(Nw,"addCoordinationId");s(WM,"noteCoordinationUse");s(VM,"resultText");s(zM,"noteAnnounceResult");qM={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(Jr,"num");s(JM,"editedPathsOf");s(Na,"subagentFilesOf");s(Cw,"readStream");s(Au,"fillTimestamps");s(no,"collectTurns")});import{createReadStream as Ow,existsSync as YM}from"node:fs";import{createInterface as Dw}from"node:readline";function r$(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,a=e.get(o);if(!a){e.set(o,{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 Da(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function i$(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
782
+ `)}function o$(e,t){let n=s(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[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function s$(e,t,n){return XM.test(e)?{polarity:-1,magnitude:Yr.rework,kind:"rework"}:n&&ZM.test(e)?{polarity:-1,magnitude:Yr.correction,kind:"correction"}:QM.test(e)?{polarity:1,magnitude:Yr.acceptance,kind:"acceptance"}:t!==null&&o$(t,e)?{polarity:-1,magnitude:Yr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function a$(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:Pw,behaviour_measured:!0}}async function c$(e,t){for(let n of Na(e))await new Promise(r=>{let i=Dw({input:Ow(n,{encoding:"utf-8"})});i.on("line",o=>{let a=o.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of Da(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Pa))continue;let d=l.name.slice(Pa.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 Iu(e,t={}){let n=a$("");if(!e||!YM(e))return n;let r=t.turns??(await no(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(m=>{let g=Ow(e,{encoding:"utf-8"}),y=Dw({input:g}),_=s(b=>{let k=b.trim();if(!k)return;let S;try{S=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let j=S.sessionId??S.session_id;typeof j=="string"&&j&&(n.session_id=j)}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 T=S.message?.role,w=S.isSidechain===!0;if(T==="assistant")for(let j of Da(S.message?.content)){if(j.type!=="tool_use"||typeof j.name!="string"||!j.name.startsWith(Pa))continue;let W=j.name.slice(Pa.length);W&&(n.maind_tool_calls??={},n.maind_tool_calls[W]=(n.maind_tool_calls[W]??0)+1)}if(w)return;if(T==="assistant"){let j=Da(S.message?.content),W=!1;for(let ut of j)ut.type==="tool_use"&&(n.tool_calls++,W=!0,ut.name==="AskUserQuestion"&&n.agent_questions++);c=W;return}if(T!=="user")return;let x=Da(S.message?.content),N=i$(x);if(N.includes(e$)){n.interrupts++,i.push({polarity:-1,magnitude:Yr.interrupt,kind:"interrupt"});return}if(x.some(j=>j.type==="tool_result"&&j.is_error===!0&&typeof j.content=="string"&&j.content.includes(t$))){n.tool_denials++,i.push({polarity:-1,magnitude:Yr.denial,kind:"denial"});return}if(x.some(j=>j.type==="tool_result")||!N.trim())return;n.user_turns++,n.user_chars+=N.length;let B=to(N);B&&(a=B);let P=s$(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",b=>{try{_(b)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await c$(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||r$(o,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...o.values()].sort((m,g)=>m.first_ts-g.first_ts||m.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((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*n$+m.polarity*m.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=y,g>0&&i[g-1].polarity<0&&m.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 Pa,Pw,XM,ZM,QM,e$,t$,n$,Yr,Mw=v(()=>{"use strict";Aa();Oa();Pa="mcp__maind__",Pw="2026-10-01",XM=/(\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,ZM=/(\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,QM=/(\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,e$="[Request interrupted by user",t$="The user doesn't want to proceed with this tool use",n$=.7,Yr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(r$,"bumpModel");s(Da,"asBlocks");s(i$,"textOf");s(o$,"isRepeat");s(s$,"classifyGenuine");s(a$,"emptyAnalysis");s(c$,"tallySubagentMaindCalls");s(Iu,"analyzeSession")});function Nu(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 Ou(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 Du(e,t,n,r="unknown",i){let o={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;o.session_span={...t,...c}}else o.session_span=t;return o}var $w=v(()=>{"use strict";s(Nu,"parseIngestResponse");s(Ou,"describeSliceVerdict");s(Du,"ingestBody")});import{isAbsolute as Lw,relative as l$,resolve as Fw,sep as jw}from"node:path";function Hw(e){return e>$a[1]?"above_272k":e>$a[0]?"band_200k_272k":"standard"}function Uw(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Ma(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function ro(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=s(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let d=l,u=Ma(d.from);typeof d.object_id!="string"||!Pu.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:Ma(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=Ma(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:Ma(c.to)})}let o=[];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"||!Pu.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Pu.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:o}}function La(e,t){if(!Lw(e))return null;let n=l$(Fw(t),Fw(e));return!n||n==="."||n.startsWith("..")||Lw(n)?null:jw==="/"?n:n.split(jw).join("/")}function u$(e,t){return t===""||e===t||e.startsWith(t+"/")}function $u(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Bw(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Lu(e,t){for(let n of Bw(t))if(u$(e,n.path_prefix))return n.object_id;return null}function p$(e,t){for(let n of Bw(t))if($u(e,n.path_prefix))return n.object_id;return null}function Mu(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Gw(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>Lu(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Mu(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=>Mu(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=>Mu(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>$u(f.path_prefix,u))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=p$(f.path_prefix,o);if(m)return{object_id:m,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 Fu(e,t,n){let r=t?.anchors??[],i=n.repoRoot,o=n.relativize??(i?_=>La(_,i):null),a=s(_=>{if(!o)return[];let b=[];for(let k of _.edited_paths){let S=o(k);S!==null&&!b.includes(S)&&b.push(S)}return b},"relOf"),c=s(_=>{for(let b of _){let k=Lu(b,r);if(k)return{object_id:k,rel:b}}return null},"firstAnchoredEdit"),l=new Map;for(let _ of e){let b=l.get(_.stream)??[];b.push(_),l.set(_.stream,b)}let d=[...l.entries()].sort(([_],[b])=>_===Yn?-1:b===Yn?1:0),u=[],p=s(_=>{let b=null;for(let k of u){if(k.ts>_&&_>0)break;b=k.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let k=b.map((T,w)=>({t:T,i:w,rels:a(T)})).sort((T,w)=>T.t.ts-w.t.ts||T.i-w.i),S=null;for(let T of k){let w=c(T.rels);if(w){S=w;break}}!S&&_!==Yn&&k.length&&(S=p(k[0].t.ts));for(let T of k){let w=c(T.rels);w&&(S=w),_===Yn&&u.push({ts:T.t.ts,seg:S});let x=T.t;if(x.input_tokens+x.output_tokens+x.cache_read_tokens+x.cache_creation_tokens===0)continue;let L=Gw(x,T.rels,S,t),B=Hw(x.input_tokens+x.cache_read_tokens+x.cache_creation_tokens),P=Uw(x.model),j=`${L.object_id??""}|${L.source}|${P}|${B}`,W=f.get(j);W||(W={object_id:L.object_id,attribution_source:L.source,model:P,context_tier:B,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},f.set(j,W)),W.input_tokens+=x.input_tokens,W.output_tokens+=x.output_tokens,W.cache_read_tokens+=x.cache_read_tokens,W.cache_creation_tokens+=x.cache_creation_tokens,W.cache_creation_1h_tokens+=x.cache_creation_1h_tokens,W.turns+=1,x.ts>0&&((W.firstMs===0||x.ts<W.firstMs)&&(W.firstMs=x.ts),x.ts>W.lastMs&&(W.lastMs=x.ts))}}let m=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:k,...S}=_;S.first_ts=new Date(b>0?b:m).toISOString(),S.last_ts=new Date(k>0?k:m).toISOString(),g.push(S)}let y={lease:0,binding:1,claim:2,path:3,none:4};return g.sort((_,b)=>y[_.attribution_source]-y[b.attribution_source]||(_.object_id??"").localeCompare(b.object_id??"")||_.model.localeCompare(b.model)||_.context_tier.localeCompare(b.context_tier)),g}var $a,d$,Pu,ju=v(()=>{"use strict";Oa();$a=[2e5,272e3];s(Hw,"contextTierOf");s(Uw,"normalizeModelId");d$=$a[0],Pu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Ma,"msOf");s(ro,"parseCostContext");s(La,"toRepoRelative");s(u$,"underPrefix");s($u,"prefixesOverlap");s(Bw,"sortedAnchors");s(Lu,"anchorFor");s(p$,"bestAnchorOverlapping");s(Mu,"inWindow");s(Gw,"assignTurn");s(Fu,"sliceSession")});import{mkdirSync as f$,readFileSync as m$,renameSync as h$,writeFileSync as g$}from"node:fs";import{dirname as y$,isAbsolute as Fa,sep as Hu}from"node:path";function _$(e){let t=e.split(Hu).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function b$(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function Uu(e){let t=new Map,n=s(u=>{let p=t.get(u);if(p!==void 0)return p;let f=e.keyOfRoot(u);return t.set(u,f),f},"keyOf"),r=new Map,i=s(u=>{let p=r.get(u);if(p!==void 0)return p;let f=e.gitRoot(u);return r.set(u,f),f},"gitRoot"),o=new Map,a=[...(e.known??new Map).entries()].filter(([u])=>Fa(u)).sort((u,p)=>p[0].length-u[0].length),c=new Map,l=s(u=>{if(!e.isDir)return null;let p=c.get(u);if(p!==void 0)return p;let f=d(u);return c.set(u,f),f},"byConvention"),d=s(u=>{if(!e.isDir)return null;let p=u.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let g=p.slice(0,f-1).join("/")||"/",y=p[f-1];for(let _=y.lastIndexOf("-");_>0;_=y.lastIndexOf("-",_-1)){let b=`${g==="/"?"":g}/${y.slice(0,_)}`;if(e.isDir(b)&&i(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!Fa(u))return null;let p=u.split(Hu).join("/"),f=_$(p),m=i(f);if(m){let g=n(m);return o.set(m,g),{root:m,key:g}}for(let[g,y]of a)if(!(!b$(p,g)||p===g)&&!(e.isDir&&e.isDir(g)))return{root:g,key:y};return l(f)},seenLive(){return[...o.entries()].map(([u,p])=>({root:u,key:p}))}}}function Bu(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,o=0;for(let[a,c]of n)(c.turns>i||c.turns===i&&(c.depth>o||c.depth===o&&r!==null&&a<r))&&(r=a,i=c.turns,o=c.depth);return r}function Gu(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:La(n.split(Hu).join("/"),r.root)}}function Vw(e){try{let t=JSON.parse(m$(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 io(e){let t=new Map,n=Vw(e);for(let[r,i]of Object.entries(n.checkouts)){if(!Fa(r)||!i||typeof i!="object")continue;let o=typeof i.project_key=="string"&&Ww.test(i.project_key)?i.project_key:null;t.set(r,o)}return t}function oo(e,t,n=Date.now()){try{let r=Vw(e),i=new Date(n).toISOString(),o=!1;for(let c of t){if(!Fa(c.root))continue;let l=c.key&&Ww.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>v$)&&(r.checkouts[c.root]={project_key:l,seen_at:i},o=!0)}for(let[c,l]of Object.entries(r.checkouts)){let d=Date.parse(l?.seen_at??"");(!Number.isFinite(d)||n-d>Kw)&&(delete r.checkouts[c],o=!0)}if(!o)return;f$(y$(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;g$(a,JSON.stringify(r),{mode:384}),h$(a,e)}catch{}}var Kw,v$,Ww,zw=v(()=>{"use strict";ju();s(_$,"dirOf");s(b$,"within");s(Uu,"createCheckoutResolver");s(Bu,"dominantProjectKey");s(Gu,"relativizerFor");Kw=90*24*60*60*1e3,v$=60*60*1e3,Ww=/^[a-f0-9]{64}$/;s(Vw,"readMemory");s(io,"loadCheckoutMemory");s(oo,"rememberCheckouts")});import{homedir as w$}from"node:os";import{join as k$}from"node:path";var x$,Ku=v(()=>{"use strict";x$=k$(w$(),".codex","sessions")});var qw=v(()=>{"use strict";Ku()});var Jw=v(()=>{"use strict"});import{createReadStream as E$,existsSync as T$}from"node:fs";import{createInterface as R$}from"node:readline";function Yw(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function I$(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
783
+ `)}function Qw(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 N$(e){let t=e.message?.role;if(t==="assistant")return{holder:Yw(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Yw(e.message?.content),r=I$(n);return r.includes(C$)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(A$))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Wu(e){let t=Qw("");if(!e||!T$(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let d=E$(e,{encoding:"utf-8"}),u=R$({input:d}),p=s(f=>{let m=f.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let b=g.sessionId??g.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||o!==null&&y<o)return;let _=N$(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,o!==null){let b=y-o;a==="agent"?i+=b:b>=Xw*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<Zw&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(b/1e3)}))}o=y,a=_.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 C$,A$,Xw,Zw,ek=v(()=>{"use strict";C$="[Request interrupted by user",A$="The user doesn't want to proceed with this tool use",Xw=60,Zw=200;s(Yw,"asBlocks");s(I$,"textOf");s(Qw,"emptySpan");s(N$,"classify");s(Wu,"analyzeSpan")});import{createReadStream as O$,existsSync as D$}from"node:fs";import{createInterface as P$}from"node:readline";function $$(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function ja(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function L$(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(`
784
+ `)}return""}async function Vu(e,t={}){if(!e||!D$(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Tu(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:Tu(),a=t.start??0;return await new Promise(c=>{let l=O$(e,{encoding:"utf-8",start:t.start??0}),d=P$({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),_=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=M$[m.attachment.type];b&&(o[$$(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=L$(m.message?.content),k=to(b);k&&(i=k);let S={session_id:g,ts:y,text:b,effort_directive:k};n.push({kind:"user",...S});return}if(_==="assistant"){let b=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,S=typeof m.requestId=="string"&&m.requestId?m.requestId:null,T=k??S,w=T!==null&&r.has(T);T!==null&&!w&&r.add(T);let x={session_id:g,ts:y,model:m.message?.model??null,input_tokens:w?0:ja(b?.input_tokens),output_tokens:w?0:ja(b?.output_tokens),cache_read_input_tokens:w?0:ja(b?.cache_read_input_tokens),cache_creation_input_tokens:w?0:ja(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...o.ultracode?{ultracode:!0}:{},...o.planMode?{planMode:!0}:{},...o.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...x})}});let u=s(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...o},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var M$,tk=v(()=>{"use strict";Aa();Ru();M$={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}};s($$,"modeFlagKey");s(ja,"num");s(L$,"extractUserText");s(Vu,"streamTranscript")});var nk=v(()=>{"use strict"});import{homedir as F$}from"node:os";import{join as j$}from"node:path";function qu(e){return e.replace(/[/.]/g,"-")}var H$,zu,rk=v(()=>{"use strict";H$=F$(),zu=j$(H$,".claude","projects");s(qu,"projectPathFromCwd")});var Xn=v(()=>{"use strict";Ru();Ew();Tw();Mw();$w();Oa();zw();Ku();qw();ju();Jw();ek();tk();Aa();nk();rk()});import{parse as J$}from"jsonc-parser";function Ju(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 Xu(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=J$(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,o=i?.transport??i;return!o||typeof o.command!="string"?null:{command:o.command,args:Array.isArray(o.args)?o.args.filter(a=>typeof a=="string"):[]}}function Xr(e,t){let n=`npm i -g ${Zn}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Ua(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(p=>p.bridgeVersion).filter(p=>p!==null)],r=e.latestVersion??n.sort(Ju).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:Xr(r,g.node)})}if(new Set(i.map(g=>g.bridgeVersion)).size>1)for(let g of i.filter(y=>Ju(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:Xr(r,g.node)})}let o=!1,a=new Map,c=s((p,f)=>{let m=a.get(p)??{version:e.installVersionOf(p),clients:[]};m.clients.push(f),a.set(p,m)},"noteInstall");for(let p of e.clientConfigs){let f=Xu(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(o=!0,/(^|\/)npx(\.cmd)?$/.test(f.command)&&f.args.some(y=>y.includes(Zn))){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:`${Xr(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 ${Zn}@${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 ${Xr(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:Xr(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(o||t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${Zn} install`}),e.latestVersion!==null)for(let[p,f]of a){let m=f.clients.join(", ");if(f.version===null)t.push({check:"version",level:"info",message:`${m}: cannot tell which bridge version ${p} is.`});else if(Ju(f.version,e.latestVersion)<0){let g=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(p)?.[1]??null;t.push({check:"version",level:"warn",message:`${m} run bridge ${f.version} (${p}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:g?Xr(e.latestVersion,g):`npx -y ${Zn}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${m} 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||!sk.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"}):X$.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&sk.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=Te(e.claudeSettings,{fileExists:s(m=>e.fileExists(m),"fileExists")}),f=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let m of p){if(m.status==="missing"||m.status==="superseded")continue;if(m.status!=="ok"){t.push({check:"hooks",level:m.status==="broken"?"error":"warn",message:m.detail});continue}let g=m.command?/(\S+\/build\/index\.js)/.exec(m.command)?.[1]??null:null,y=g?e.installVersionOf(g):null;y!==null&&f!==null&&y!==f&&t.push({check:"hooks",level:"warn",message:`${m.event}/${m.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"} ${m.subcommand}`})}t.some(m=>m.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=la(e.claudeSettings,{guardMode:p,fileExists:s(_=>e.fileExists(_),"fileExists")}),g=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Zn}`)} install --hooks-only`,y=(e.declinedHooks??[]).includes(ot);f.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${ot} hook).`}):f.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${ot} 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 ${ot} 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 ${ot} 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 (${ot}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:g})}if(e.claudeSettings!==null){let p=Te(e.claudeSettings,{fileExists:s(f=>e.fileExists(f),"fileExists")},[Y$])[0];if(p.status==="superseded"){let f=e.foreignHookHosts??[],m=f.includes("cursor"),g=(e.declinedHooks??[]).includes(Ln),y=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Zn}`),_=p.remedy==="run-install"?`${y} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${y} ${Ln}`,b=m?`Cursor, installed here, imports it from ~/.claude/settings.json and takes only JSON at session start \u2014 it gets plain text it cannot parse${f.includes("devin")?"; Devin Local gets text whose handling it does not document":""}`:f.includes("devin")?"Devin Local, installed here, runs it too and documents only JSON context for hooks":"it is fine in Claude Code, but Cursor and Devin Local, which import the same hooks, would get plain text";t.push({check:"hook-hosts",level:m&&!g?"warn":"info",message:`the SessionStart reminder hook still runs \`${p.command}\` \u2014 ${b}. ${Ln} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:_})}}let u=e.context??null;if(u!==null&&e.claudeSettings!==null){let p=Te(e.claudeSettings,{fileExists:s(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 ak(e){let t=e.filter(i=>i.level==="error"&&Yu.includes(i.check)).sort((i,o)=>Yu.indexOf(i.check)-Yu.indexOf(o.check)),n=t[0];if(n===void 0)return Z$(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 Z$(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?Q$(e):`[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 Q$(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?null:`[maind] setup gap \u2014 ${t.message}`+(t.fix?` To switch to it, run in a terminal (asks consent, replaces only that entry): ${t.fix}`:"")}function ck(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,o=e.filter(a=>a.level==="warn").length;return r.push("",i+o===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${o} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
782
785
  `)+`
783
- `}var Br,t$,Lv,Mu,xa=_(()=>{"use strict";Vo();jt();Br="@maind-dev/mcp-bridge",t$=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,Lv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(Pu,"compareVersions");o($u,"maindEntry");o(Hr,"installFix");o(Sa,"diagnose");Mu=["connection","client-config","npx-cache","hooks"];o(Fv,"sessionStartLine");o(n$,"briefingGapLine");o(jv,"renderFindings")});import{findNodeAtLocation as r$,parse as Uv,parseTree as i$,stripComments as s$}from"jsonc-parser";function Hv(e){let t=[];for(let n of e){if(n.present!==!1||n.kind!=="json"||n.raw===null||$u(n)===null)continue;let r=[],i=Uv(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!Lu(i))continue;let s=Lu(i.servers)&&"maind"in i.servers?"servers":"mcpServers",a=i[s];if(!Lu(a)||!("maind"in a))continue;let c=Object.keys(a).filter(p=>p!=="maind").length,l=Object.keys(i).filter(p=>p!==s),d=s$(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=o$(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 o$(e,t){let n=i$(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:r$(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 Uv(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function Bv(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
786
+ `}var Zn,Y$,X$,sk,Yu,Ba=v(()=>{"use strict";da();at();Zn="@maind-dev/mcp-bridge",Y$=st.find(e=>e.subcommand===Ln),X$=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,sk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Ju,"compareVersions");s(Xu,"maindEntry");s(Xr,"installFix");s(Ua,"diagnose");Yu=["connection","client-config","npx-cache","hooks"];s(ak,"sessionStartLine");s(Z$,"briefingGapLine");s(Q$,"hookHostsGapLine");s(ck,"renderFindings")});import{parse as uk}from"smol-toml";function pk(e){let t;try{t=uk(e)}catch{return null}if(!Tt(t)||!Tt(t.mcp_servers)||!Tt(t.mcp_servers.maind))return null;let n=Object.keys(t.mcp_servers).filter(u=>u!=="maind").length,r=Object.keys(t).filter(u=>u!=="mcp_servers"),i=[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[]],o=rL(e);if(o===null)return{action:"manual",next:null,stays:i};let a=eL(o),l=o.some(u=>u.comment&&!a.some(([p,f])=>u.start>=p&&u.end<=f))?[...i,"comments"]:i;if(l.length===0)return{action:"delete",next:null,stays:l};if(a.length===0)return{action:"manual",next:null,stays:l};let d=tL(e,a);return nL(t,d)?{action:"edit",next:d,stays:l}:{action:"manual",next:null,stays:l}}function eL(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.kind!=="header"||i.path?.[0]!=="mcp_servers"||i.path[1]!=="maind")continue;let o=r;for(let c=r+1;c<e.length&&e[c].kind!=="header";c++)(e[c].kind==="keyval"||e[c].kind==="continuation")&&(o=c);let a=r;for(;a>0&&e[a-1].kind==="blank";)a--;t.push([e[a].start,e[o].end])}let n=[];for(let[r,i]of t){let o=n.at(-1);o!==void 0&&r<=o[1]?o[1]=Math.max(o[1],i):n.push([r,i])}return n}function tL(e,t){let n=e;for(let[r,i]of[...t].reverse())n=n.slice(0,r)+n.slice(i);return t[0]?.[0]===0&&(n=n.replace(/^(?:[ \t]*\r?\n)+/,"")),n}function nL(e,t){let n;try{n=uk(t)}catch{return!1}if(!Tt(n))return!1;let r={...e.mcp_servers};delete r.maind;let i={...e,mcp_servers:r};return Zu(lk(i),lk(n))}function lk(e){if(!Tt(e.mcp_servers)||Object.keys(e.mcp_servers).length>0)return e;let t={...e};return delete t.mcp_servers,t}function Zu(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&JSON.stringify(e)===JSON.stringify(t);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>Zu(n,t[r]));if(Tt(e)||Tt(t)){if(!Tt(e)||!Tt(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>r in t&&Zu(e[r],t[r]))}return Object.is(e,t)}function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function rL(e){let t=[],n=null,r=0;for(let i=0;i<e.length;){let o=e.indexOf(`
787
+ `,i),a=o===-1?e.length:o+1,c=e.slice(i,o===-1?e.length:o).replace(/\r$/,"");if(n!==null||r>0){let l=dk(c,0,n,r);if(l===null)return null;({open:n,depth:r}=l),t.push({start:i,end:a,kind:"continuation",comment:l.comment})}else{let l=c.search(/[^ \t]/);if(l===-1)t.push({start:i,end:a,kind:"blank",comment:!1});else if(c[l]==="#")t.push({start:i,end:a,kind:"comment",comment:!0});else if(c[l]==="["){let d=iL(c,l);if(d===null)return null;let u=c.slice(d.end).trimStart();if(u.length>0&&!u.startsWith("#"))return null;t.push({start:i,end:a,kind:"header",comment:u.length>0,path:d.path})}else{let d=dk(c,l,null,0);if(d===null)return null;({open:n,depth:r}=d),t.push({start:i,end:a,kind:"keyval",comment:d.comment})}}i=a}return n===null&&r===0?t:null}function dk(e,t,n,r){let i=t;for(;i<e.length;){if(n!==null){let a=Qu(e,i,n);if(a===-1)return{open:n,depth:r,comment:!1};n=null,i=a;continue}let o=e[i];if(o==="#")return{open:n,depth:r,comment:!0};if(o==='"'||o==="'"){if(e.startsWith(o.repeat(3),i)){n=o==='"'?'"""':"'''",i+=3;continue}let a=Qu(e,i+1,o);if(a===-1)return null;i=a;continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r<0))return null;i++}return{open:n,depth:r,comment:!1}}function Qu(e,t,n){if(n==="'"||n==="'''"){let r=e.indexOf(n,t);if(r===-1)return-1;let i=r+n.length;if(n==="'''")for(;i<r+5&&e[i]==="'";)i++;return i}for(let r=t;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(n==='"'&&e[r]==='"')return r+1;if(n==='"""'&&e.startsWith('"""',r)){let i=r+3;for(;i<r+5&&e[i]==='"';)i++;return i}r++}return-1}function iL(e,t){let n=e[t+1]==="[",r=n?"]]":"]",i=t+(n?2:1),o=[];for(;;){for(;e[i]===" "||e[i]===" ";)i++;let a=oL(e,i);if(a===null)return null;for(o.push(a.value),i=a.end;e[i]===" "||e[i]===" ";)i++;if(e[i]==="."){i++;continue}return e.startsWith(r,i)?{path:o,end:i+r.length}:null}}function oL(e,t){if(e[t]==='"'){let r=Qu(e,t+1,'"');if(r===-1)return null;try{return{value:JSON.parse(e.slice(t,r)),end:r}}catch{return null}}if(e[t]==="'"){let r=e.indexOf("'",t+1);return r===-1?null:{value:e.slice(t+1,r),end:r+1}}let n=/^[A-Za-z0-9_-]+/.exec(e.slice(t));return n===null?null:{value:n[0],end:t+n[0].length}}var fk=v(()=>{"use strict";s(pk,"planTomlPhantomRemoval");s(eL,"maindTableRanges");s(tL,"applyCut");s(nL,"sameWithoutMaind");s(lk,"dropEmptyServers");s(Zu,"sameValue");s(Tt,"isTable");s(rL,"scanLines");s(dk,"scanValue");s(Qu,"closeOf");s(iL,"parseHeader");s(oL,"readKey")});import{findNodeAtLocation as sL,parse as mk,parseTree as aL,stripComments as cL}from"jsonc-parser";function hk(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||Xu(n)===null)continue;if(n.kind==="toml"){let f=lL(n,n.raw);f!==null&&t.push(f);continue}let r=[],i=mk(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!ep(i))continue;let o=ep(i.servers)&&"maind"in i.servers?"servers":"mcpServers",a=i[o];if(!ep(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(i).filter(f=>f!==o),d=cL(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=dL(n.raw,[o,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${o}.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 ${o}.maind; stays: ${u}`})}return t}function lL(e,t){let n=pk(t);if(n===null)return null;let r={label:e.label,path:e.path,raw:t},i=n.stays.length>0?`; stays: ${n.stays.join(", ")}`:"";switch(n.action){case"delete":return{...r,action:"delete",next:null,keeps:null};case"edit":return{...r,action:"edit",next:n.next,keeps:`remove [mcp_servers.maind]${i}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove [mcp_servers.maind] by hand \u2014 it cannot be cut out cleanly${i}`}}}function dL(e,t){let n=aL(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:sL(n,[...t])?.parent,i=r?.parent?.children;if(r===void 0||r.type!=="property"||i===void 0)return null;let o=i.indexOf(r),a=r.offset,c=r.offset+r.length;if(o+1<i.length)c=i[o+1].offset;else if(o>0){let u=i[o-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 mk(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function gk(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
784
788
  `;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(`
785
789
  `)+`
786
- `}function Lu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Gv=_(()=>{"use strict";xa();o(Hv,"planPhantomRemovals");o(o$,"withoutProperty");o(Bv,"renderPhantomPlan");o(Lu,"isObject")});var qv={};ee(qv,{contextProbe:()=>zv,realProbe:()=>Yi,resolveNvmAlias:()=>Vv,runDoctor:()=>b$});import{execFileSync as a$}from"node:child_process";import{existsSync as qi,readFileSync as c$,readdirSync as Fu,realpathSync as l$,unlinkSync as d$}from"node:fs";import{homedir as Ji,platform as Ea}from"node:os";import{delimiter as u$,dirname as Kv,join as ce}from"node:path";function yt(e){try{return qi(e)?c$(e,"utf8"):null}catch{return null}}function f$(){try{let e=a$(Ea()==="win32"?"npm.cmd":"npm",["view",Wv,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function ju(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ce(Ji(),".nvm")}function p$(){let e=ce(ju(),"versions","node"),t=[];try{t=Fu(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=yt(ce(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 Vv(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 m$(e){let t=yt(ce(ju(),"alias","default"));return t===null?null:Vv(t,e.map(n=>n.node),n=>{let r=yt(ce(ju(),"alias",n));return r===null?null:r})}function h$(){let e=Ea()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(u$))if(t)for(let n of e){let r=ce(t,n);if(qi(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function g$(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Ea()==="win32"?ce(process.env.LOCALAPPDATA??ce(Ji(),"AppData","Local"),"npm-cache"):ce(Ji(),".npm"),t=ce(e,"_npx"),n=[],r=[];try{r=Fu(t)}catch{return[]}for(let i of r)try{let s=Fu(ce(t,i,"node_modules"));s.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:ce(t,i),maind:s.includes("@maind-dev")})}catch{}return n}function y$(e){let t;try{t=Kv(l$(e))}catch{return null}for(let n=0;n<6;n++){let r=yt(ce(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===Wv)return s.version??null}catch{}let i=Kv(t);if(i===t)break;t=i}return null}function zv(e){let t=Bt(e),n=!1;try{let i=yt(Pr);n=i!==null&&typeof JSON.parse(i).conventions=="string"}catch{n=!1}let r=Ko();return{repoRoot:t,indexPresent:t!==null&&qi(ce(t,Ht)),conventionsCached:n||t!==null&&qi(ce(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function Yi(e=process.cwd(),t={}){let n=p$(),r=yt(ce(je(),"device-id")),i=Ni({projectRoot:e,homeDir:Ji(),platform:Ea(),env:process.env}),s=null;try{s=q()}catch{s=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=Ne(),l=ye({entryPath:_e(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:G,latestVersion:t.offline===!0?null:f$(),nodeTrees:n,nvmDefault:m$(n),pathWinner:h$(),clientConfigs:Ii(i).map(d=>({label:d.label,path:d.path,kind:d.kind,raw:yt(d.path),present:d.presence===void 0?null:vo(d.presence,Sr)})),npxStaleDirs:g$(),connection:Xy(),claudeSettings:yt(ce(Ji(),".claude","settings.json")),fileExists:o(d=>qi(d),"fileExists"),installVersionOf:y$,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:a.length>0?a:null,guardMode:oe(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?Xe(l):null,context:t.offline===!0?null:zv(e)}}async function _$(e){let t=Hv(Yi(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(Bv(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
787
- `);continue}if(yt(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
788
- `),n++;continue}try{r.action==="delete"?d$(r.path):await z(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
790
+ `}function ep(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var yk=v(()=>{"use strict";Ba();fk();s(hk,"planPhantomRemovals");s(lL,"tomlRemoval");s(dL,"withoutProperty");s(gk,"renderPhantomPlan");s(ep,"isObject")});var kk={};Q(kk,{contextProbe:()=>wk,realProbe:()=>co,resolveNvmAlias:()=>vk,runDoctor:()=>SL});import{execFileSync as uL}from"node:child_process";import{existsSync as so,readFileSync as pL,readdirSync as tp,realpathSync as fL,unlinkSync as mL}from"node:fs";import{homedir as ao,platform as Ga}from"node:os";import{delimiter as hL,dirname as _k,join as ue}from"node:path";function Rt(e){try{return so(e)?pL(e,"utf8"):null}catch{return null}}function gL(){try{let e=uL(Ga()==="win32"?"npm.cmd":"npm",["view",bk,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function np(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ue(ao(),".nvm")}function yL(){let e=ue(np(),"versions","node"),t=[];try{t=tp(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Rt(ue(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 vk(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 o=r.startsWith("v")?r:`v${r}`;if(t.includes(o))return o;let a=o.endsWith(".")?o:`${o}.`;return i.filter(c=>c.startsWith(a)).at(-1)??null}function _L(e){let t=Rt(ue(np(),"alias","default"));return t===null?null:vk(t,e.map(n=>n.node),n=>{let r=Rt(ue(np(),"alias",n));return r===null?null:r})}function bL(){let e=Ga()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(hL))if(t)for(let n of e){let r=ue(t,n);if(so(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function vL(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Ga()==="win32"?ue(process.env.LOCALAPPDATA??ue(ao(),"AppData","Local"),"npm-cache"):ue(ao(),".npm"),t=ue(e,"_npx"),n=[],r=[];try{r=tp(t)}catch{return[]}for(let i of r)try{let o=tp(ue(t,i,"node_modules"));o.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:ue(t,i),maind:o.includes("@maind-dev")})}catch{}return n}function wL(e){let t;try{t=_k(fL(e))}catch{return null}for(let n=0;n<6;n++){let r=Rt(ue(t,"package.json"));if(r!==null)try{let o=JSON.parse(r);if(o.name===bk)return o.version??null}catch{}let i=_k(t);if(i===t)break;t=i}return null}function wk(e){let t=qt(e),n=!1;try{let i=Rt(Kr);n=i!==null&&typeof JSON.parse(i).conventions=="string"}catch{n=!1}let r=oa();return{repoRoot:t,indexPresent:t!==null&&so(ue(t,zt)),conventionsCached:n||t!==null&&so(ue(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function co(e=process.cwd(),t={}){let n=yL(),r=Rt(ue(Be(),"device-id")),i=Hi({projectRoot:e,homeDir:ao(),platform:Ga(),env:process.env,bridgeEntry:he()}),o=null;try{o=J()}catch{o=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=te(),l=ke({entryPath:he(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:K,latestVersion:t.offline===!0?null:gL(),nodeTrees:n,nvmDefault:_L(n),pathWinner:bL(),clientConfigs:ji(i).map(d=>({label:d.label,path:d.path,kind:d.kind,raw:Rt(d.path),present:d.presence===void 0?null:Dr(d.presence,Wt)})),npxStaleDirs:vL(),connection:m_(),claudeSettings:Rt(ue(ao(),".claude","settings.json")),fileExists:s(d=>so(d),"fileExists"),installVersionOf:wL,deviceId:r===null?null:r.trim(),apiKey:o,envApiKey:a.length>0?a:null,guardMode:le(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?rt(l):null,context:t.offline===!0?null:wk(e),foreignHookHosts:kL(i)}}function kL(e){let t=[];try{Dr(Nn(e),Wt)&&t.push("cursor"),Dr(Os(e),Wt)&&t.push("devin")}catch{}return t}async function xL(e){let t=hk(co(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(gk(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
791
+ `);continue}if(Rt(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
792
+ `),n++;continue}try{r.action==="delete"?mL(r.path):await z(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
789
793
  `)}catch(i){process.stdout.write(` failed ${r.path}: ${i instanceof Error?i.message:String(i)}
790
- `),n++}}return n>0?1:0}async function b$(e){if(e.includes("--remove-phantoms"))return _$(e.includes("--yes"));let t=Sa(Yi());return e.includes("--json")?process.stdout.write(JSON.stringify({version:G,findings:t},null,2)+`
791
- `):process.stdout.write(jv(t)),t.some(n=>n.level==="error")?1:0}var Wv,Uu=_(()=>{"use strict";Ut();ud();Mn();Ao();Vt();ie();et();Mt();be();En();ko();Ue();xa();Gv();Wv="@maind-dev/mcp-bridge";o(yt,"readOrNull");o(f$,"latestVersion");o(ju,"nvmDir");o(p$,"nodeTrees");o(Vv,"resolveNvmAlias");o(m$,"nvmDefault");o(h$,"pathWinner");o(g$,"npxStaleDirs");o(y$,"installVersionOf");o(zv,"contextProbe");o(Yi,"realProbe");o(_$,"removePhantoms");o(b$,"runDoctor")});function w$(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":re()}}async function Jv(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:w$(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 Ta,Hu=_(()=>{"use strict";ie();br();Ta=process.env.MAIND_ENDPOINT??_r("mcp-client-metrics-ingest");o(w$,"ingestHeaders");o(Jv,"postMetrics")});function Yv(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Zv(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 Hn(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 Xi(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Qv(e,t,n){let r=n.maxAgeMs??Xv,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,a=Zv(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)Yv(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 ${Xi(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Xi(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Yv(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Xi(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Xi(s)} ago, advisory \u2014 never a lock):
794
+ `),n++}}return n>0?1:0}async function SL(e){if(e.includes("--remove-phantoms"))return xL(e.includes("--yes"));let t=Ua(co());return e.includes("--json")?process.stdout.write(JSON.stringify({version:K,findings:t},null,2)+`
795
+ `):process.stdout.write(ck(t)),t.some(n=>n.level==="error")?1:0}var bk,rp=v(()=>{"use strict";We();Cd();Vn();Gs();Zt();se();ct();Gt();xe();On();Ls();Ge();Ba();yk();bk="@maind-dev/mcp-bridge";s(Rt,"readOrNull");s(gL,"latestVersion");s(np,"nvmDir");s(yL,"nodeTrees");s(vk,"resolveNvmAlias");s(_L,"nvmDefault");s(bL,"pathWinner");s(vL,"npxStaleDirs");s(wL,"installVersionOf");s(wk,"contextProbe");s(co,"realProbe");s(kL,"foreignHookHosts");s(xL,"removePhantoms");s(SL,"runDoctor")});function EL(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":oe()}}async function xk(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:EL(t),body:JSON.stringify({metrics:n})});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:o.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 Ka,ip=v(()=>{"use strict";se();Ar();Ka=process.env.MAIND_ENDPOINT??Cr("mcp-client-metrics-ingest");s(EL,"ingestHeaders");s(xk,"postMetrics")});function Sk(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Tk(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,o=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of o){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 Qn(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 lo(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Rk(e,t,n){let r=n.maxAgeMs??Ek,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=Tk(e,o),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)Sk(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 ${lo(l.last_seen_seconds+o)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${lo(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Sk(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${lo(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${lo(o)} ago, advisory \u2014 never a lock):
792
796
  `+c.map(l=>` \u2022 ${l}`).join(`
793
797
  `)+`
794
- 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 ek(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 tk(e,t,n,r=Xv,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=Zv(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 ${Xi(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
795
- ${h}`:h}var Xv,Bu=_(()=>{"use strict";o(Yv,"prefixConflict");Xv=10*6e4;o(Zv,"parsePeers");o(Hn,"selectOwnSnapshot");o(Xi,"ageDisplay");o(Qv,"adviseOnPath");o(ek,"claimedIdentity");o(tk,"sessionStartSummary")});function rk(e){let t=[];for(let n of ik(e)){let r=R$(n);r&&!t.includes(r)&&t.push(r)}return t}function ik(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===`
796
- `){if(s.length>0){let d=e.slice(i+1).split(`
797
- `),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 R$(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(k$.test(a)){n+=1;continue}if(x$.has(a)){n+=1;continue}if(E$.has(a))return null;let c=a.split("/").pop()??a;if(S$.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!nk.test(i))return null;if(!v$.test(i))return Gu;if(!T$.has(i))return i;let s=t[n+1];return s&&nk.test(s)?`${i} ${s}`:i}function Ku(e){let t=rk(e).filter(n=>n!==Gu&&!sk.has(n));return t.length>0?t[t.length-1]:null}var nk,v$,Gu,k$,S$,x$,E$,T$,sk,Wu=_(()=>{"use strict";nk=/^[A-Za-z][A-Za-z0-9._-]*$/,v$=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,Gu="?",k$=/^[A-Za-z_][A-Za-z0-9_]*=/,S$=new Set(["sudo","env","time","nohup","nice","command","exec"]),x$=new Set(["do","then","else","elif","if","while","until","!","{","("]),E$=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),T$=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(rk,"shellPrograms");o(ik,"commandSegments");o(R$,"programOf");sk=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(Ku,"primaryVerb")});function ok(e){let t=e.length>Vu?e.slice(-Vu):e;return A$.some(n=>n.test(t))}function zu(e){return e.includes("maind")?C$.some(t=>e.includes(t)):!1}function ak(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function ck(e,t){if(!ak(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?Ku(n):null}function qu(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=ck(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&ok(e.output)?"fail":"ok",verb:t}}var Vu,A$,C$,lk=_(()=>{"use strict";Wu();Vu=8192,A$=[/\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(ok,"outputShowsFailure");C$=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];o(zu,"isConsultationTool");o(ak,"isCountedTool");o(ck,"verbOfCall");o(qu,"observe")});function dk(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 Ju(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(dk(i)),i=[]),i.push(s);return i.length>0&&r.push(dk(i)),r}function Yu(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 uk(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function Gr(e,t,n){let r=uk(e,t),i=Ju(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=Yu(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 Xu(e){return e.open&&!e.nudged}function Zu(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=Ju(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=Yu(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function Zi(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 Qu=_(()=>{"use strict";o(dk,"chainOf");o(Ju,"failureChains");o(Yu,"succeededAfter");o(uk,"resetPoint");o(Gr,"difficultyStatus");o(Xu,"shouldNudge");o(Zu,"captureCandidate");o(Zi,"verbSummary")});function N$(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"&&I$.has(i)?i:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:s,enabled:a}}function Aa(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return es;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let s=N$(i);s!==null&&(s.id===Qi?n=s:s.id===Ra&&(r=s))}return{difficulty:n,capture:r}}function Kr(e){return e!==null&&e.enabled}function ef(e){return Kr(e)&&e.severity==="required"}var Qi,Ra,es,I$,tf=_(()=>{"use strict";Qi="conv_consult_on_difficulty",Ra="conv_learning_capture_offer",es={difficulty:null,capture:null},I$=new Set(["required","recommended","info"]);o(N$,"ruleOf");o(Aa,"extractTriggerPolicy");o(Kr,"isActive");o(ef,"isDenyCapable")});function O$(e){return Math.max(1,Math.round(e/6e4))}function ts(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${Zi(e)}) and no maind consultation since they started (${Qi}). 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 nf(e){return`difficulty episode (${e.failures.length} failed attempts: ${Zi(e)}) without a maind consultation since it started (${Qi}, required)`}function rf(e,t="guard"){let n=O$(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${Ra}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${Zi(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 fk=_(()=>{"use strict";Qu();tf();o(O$,"minutes");o(ts,"nudgeText");o(nf,"difficultyDenyHead");o(rf,"captureText")});var Wr=_(()=>{"use strict";Wu();lk();Qu();tf();fk()});function Bn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function Pe(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function Ca(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function mk(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function hk(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Jt=_(()=>{"use strict";o(Bn,"denyPayload");o(Pe,"advisoryPayload");o(Ca,"postAdvisoryPayload");o(mk,"postFailureAdvisoryPayload");o(hk,"promptAdvisoryPayload")});import{realpathSync as D$}from"node:fs";import{basename as gk,dirname as yk,join as P$}from"node:path";function Gn(e){let t=yk(e),n=[gk(e)];for(;;)try{let r=D$(t);return P$(r,...n.reverse())}catch{let r=yk(t);if(r===t)return e;n.push(gk(t)),t=r}}var Ia=_(()=>{"use strict";o(Gn,"realpathOfUnwritten")});import{execFileSync as M$}from"node:child_process";import{existsSync as $$}from"node:fs";import{join as _k}from"node:path";function L$(e){try{let t=M$("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?vr(t):null}catch{return null}}function bk(e,t){try{if(!(t.isCheckoutRoot??(i=>$$(_k(i,".git"))))(e)||Vi(t.memoryPath).has(e))return!1;let r=(t.keyOf??L$)(e);return zi(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var ns,sf=_(()=>{"use strict";Un();De();ge();ns=_k(ke,"checkout-roots.json");o(L$,"originKey");o(bk,"rememberEditCheckout")});import{existsSync as F$,realpathSync as j$,statSync as U$}from"node:fs";import{dirname as wk,isAbsolute as H$,join as B$}from"node:path";function W$(e,t){let n=e.filter(i=>vk.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
798
+ 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 Ck(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 Ak(e,t,n,r=Ek,i=null){if(!e)return null;let o=n-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let a=o/1e3,c=Tk(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`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${lo(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
799
+ ${m}`:m}var Ek,op=v(()=>{"use strict";s(Sk,"prefixConflict");Ek=10*6e4;s(Tk,"parsePeers");s(Qn,"selectOwnSnapshot");s(lo,"ageDisplay");s(Rk,"adviseOnPath");s(Ck,"claimedIdentity");s(Ak,"sessionStartSummary")});function Nk(e){let t=[];for(let n of Ok(e)){let r=OL(n);r&&!t.includes(r)&&t.push(r)}return t}function Ok(e){let t=[],n="",r=null,i=0,o=[],a=s(()=>{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){o.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
800
+ `){if(o.length>0){let d=e.slice(i+1).split(`
801
+ `),u=0;for(;o.length>0&&u<d.length;)d[u].trim()===o[0]&&o.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,f)=>p+f.length+1,0),o=[],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 OL(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(RL.test(a)){n+=1;continue}if(AL.has(a)){n+=1;continue}if(IL.has(a))return null;let c=a.split("/").pop()??a;if(CL.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!Ik.test(i))return null;if(!TL.test(i))return sp;if(!NL.has(i))return i;let o=t[n+1];return o&&Ik.test(o)?`${i} ${o}`:i}function ap(e){let t=Nk(e).filter(n=>n!==sp&&!Dk.has(n));return t.length>0?t[t.length-1]:null}var Ik,TL,sp,RL,CL,AL,IL,NL,Dk,cp=v(()=>{"use strict";Ik=/^[A-Za-z][A-Za-z0-9._-]*$/,TL=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,sp="?",RL=/^[A-Za-z_][A-Za-z0-9_]*=/,CL=new Set(["sudo","env","time","nohup","nice","command","exec"]),AL=new Set(["do","then","else","elif","if","while","until","!","{","("]),IL=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),NL=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"]);s(Nk,"shellPrograms");s(Ok,"commandSegments");s(OL,"programOf");Dk=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"]);s(ap,"primaryVerb")});function Pk(e){let t=e.length>lp?e.slice(-lp):e;return DL.some(n=>n.test(t))}function dp(e){return e.includes("maind")?PL.some(t=>e.includes(t)):!1}function Mk(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function $k(e,t){if(!Mk(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?ap(n):null}function up(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=$k(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&Pk(e.output)?"fail":"ok",verb:t}}var lp,DL,PL,Lk=v(()=>{"use strict";cp();lp=8192,DL=[/\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];s(Pk,"outputShowsFailure");PL=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];s(dp,"isConsultationTool");s(Mk,"isCountedTool");s($k,"verbOfCall");s(up,"observe")});function Fk(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 pp(e,t=-1/0){let n=e.filter(o=>o.k==="fail"&&o.t>t).slice().sort((o,a)=>o.t-a.t),r=[],i=[];for(let o of n)i.length>0&&o.t-i[i.length-1].t>6e5&&(r.push(Fk(i)),i=[]),i.push(o);return i.length>0&&r.push(Fk(i)),r}function fp(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 jk(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function Zr(e,t,n){let r=jk(e,t),i=pp(e,r),o=i.length>0?i[i.length-1]:null,a=o!==null&&n-o.end<=6e5?o:null;if(a===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=fp(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 mp(e){return e.open&&!e.nudged}function hp(e,t){let n=-1/0;for(let o of e)o.k==="prompt"&&o.t>n&&(n=o.t);let r=Math.max(t,n),i=pp(e,r);for(let o=i.length-1;o>=0;o--){let a=i[o];if(a.failures.length<5||a.end-a.start<3e5)continue;let c=fp(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function uo(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 gp=v(()=>{"use strict";s(Fk,"chainOf");s(pp,"failureChains");s(fp,"succeededAfter");s(jk,"resetPoint");s(Zr,"difficultyStatus");s(mp,"shouldNudge");s(hp,"captureCandidate");s(uo,"verbSummary")});function $L(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,o=typeof i=="string"&&ML.has(i)?i:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:o,enabled:a}}function Va(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return fo;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let o=$L(i);o!==null&&(o.id===po?n=o:o.id===Wa&&(r=o))}return{difficulty:n,capture:r}}function Qr(e){return e!==null&&e.enabled}function yp(e){return Qr(e)&&e.severity==="required"}var po,Wa,fo,ML,_p=v(()=>{"use strict";po="conv_consult_on_difficulty",Wa="conv_learning_capture_offer",fo={difficulty:null,capture:null},ML=new Set(["required","recommended","info"]);s($L,"ruleOf");s(Va,"extractTriggerPolicy");s(Qr,"isActive");s(yp,"isDenyCapable")});function LL(e){return Math.max(1,Math.round(e/6e4))}function mo(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${uo(e)}) and no maind consultation since they started (${po}). 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 bp(e){return`difficulty episode (${e.failures.length} failed attempts: ${uo(e)}) without a maind consultation since it started (${po}, required)`}function vp(e,t="guard"){let n=LL(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${Wa}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${uo(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 Hk=v(()=>{"use strict";gp();_p();s(LL,"minutes");s(mo,"nudgeText");s(bp,"difficultyDenyHead");s(vp,"captureText")});var ei=v(()=>{"use strict";cp();Lk();gp();_p();Hk()});import{realpathSync as FL}from"node:fs";import{basename as Bk,dirname as Gk,join as jL}from"node:path";function er(e){let t=Gk(e),n=[Bk(e)];for(;;)try{let r=FL(t);return jL(r,...n.reverse())}catch{let r=Gk(t);if(r===t)return e;n.push(Bk(t)),t=r}}var za=v(()=>{"use strict";s(er,"realpathOfUnwritten")});import{execFileSync as HL}from"node:child_process";import{existsSync as UL}from"node:fs";import{join as Kk}from"node:path";function BL(e){try{let t=HL("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?Nr(t):null}catch{return null}}function Wk(e,t){try{if(!(t.isCheckoutRoot??(i=>UL(Kk(i,".git"))))(e)||io(t.memoryPath).has(e))return!1;let r=(t.keyOf??BL)(e);return oo(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var ho,wp=v(()=>{"use strict";Xn();$e();we();ho=Kk(Ce,"checkout-roots.json");s(BL,"originKey");s(Wk,"rememberEditCheckout")});import{existsSync as GL,realpathSync as KL,statSync as WL}from"node:fs";import{dirname as Vk,isAbsolute as VL,join as zL}from"node:path";function YL(e,t){let n=e.filter(i=>zk.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let o=i.hint?`
798
802
  \u2192 ${i.hint}`:"";return` \u2022 ${i.title}
799
- ${i.detail}${s}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
803
+ ${i.detail}${o}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
800
804
 
801
805
  `+r.join(`
802
806
 
803
807
  `)+`
804
808
 
805
- 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 V$(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function z$(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 of(e){let t=wk(e);for(;;){try{if(U$(t).isDirectory())return t}catch{}let n=wk(t);if(n===t)return t;t=n}}async function q$(e,t,n){let r=await n.load();if(V$(r,e,t))return null;z$(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=>vk.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:G$,metric_value:1},{session_id:e,metric_key:K$,metric_value:s}),await n.save(a),W$(i,t)}async function kk(){try{let e=await K(),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=Oe(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=H$(r)?r:B$(i,r),a=F$(s)?j$(s):Gn(s),c=ft(of(a));try{bk(c,{memoryPath:ns})}catch{}let l=await q$(n,c,{load:Q,save:tt,check:o(async d=>(await pi(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(Pe(l)),0}catch{return 0}}var vk,G$,K$,af=_(()=>{"use strict";Ot();Dt();sf();Jt();pe();Ia();De();vk=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],G$="repo_health_hook_runs",K$="repo_health_hook_findings";o(W$,"formatRepoHealth");o(V$,"alreadySeen");o(z$,"markSeen");o(of,"nearestExistingDir");o(q$,"repoHealthForEdit");o(kk,"runOnRepoHealth")});import{existsSync as J$,readFileSync as Y$,realpathSync as X$}from"node:fs";import{isAbsolute as xk,join as Ek,posix as Z$,relative as Q$,sep as eL}from"node:path";function Sk(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function sL(e,t){return{contracts:t.filter(r=>Sk(r.spec)===e||Sk(r.impl)===e).map(r=>r.id),theme:rL.test(e),acl:iL.test(e)}}function oL(e){return e.contracts.length===0&&!e.theme&&!e.acl}function aL(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 cL(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:
809
+ 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 XL(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function ZL(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},o=i[t]??{};o[n]=new Date(r).toISOString(),i[t]=o,e.repo_health_seen=i}function kp(e){let t=Vk(e);for(;;){try{if(WL(t).isDirectory())return t}catch{}let n=Vk(t);if(n===t)return t;t=n}}async function QL(e,t,n){let r=await n.load();if(XL(r,e,t))return null;ZL(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let o=i.filter(c=>zk.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:qL,metric_value:1},{session_id:e,metric_key:JL,metric_value:o}),await n.save(a),YL(i,t)}async function qk(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=re(e);if(!ye(n,{kind:"context",event:"PreToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return 0;let i=Me(e);if(!i)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=VL(i)?i:zL(o,i),c=GL(a)?KL(a):er(a),l=wt(kp(c));try{Wk(l,{memoryPath:ho})}catch{}let d=await QL(r,l,{load:ee,save:lt,check:s(async u=>(await ki(u,{includeRelease:!1})).findings,"check")});if(d!==null){let u=ce(n,{kind:"context",event:"PreToolUse",text:d});u!==null&&process.stdout.write(u)}return 0}catch{return 0}}var zk,qL,JL,xp=v(()=>{"use strict";Ut();Bt();wp();Re();ge();za();$e();zk=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],qL="repo_health_hook_runs",JL="repo_health_hook_findings";s(YL,"formatRepoHealth");s(XL,"alreadySeen");s(ZL,"markSeen");s(kp,"nearestExistingDir");s(QL,"repoHealthForEdit");s(qk,"runOnRepoHealth")});import{existsSync as eF,readFileSync as tF,realpathSync as nF}from"node:fs";import{isAbsolute as Yk,join as Xk,posix as rF,relative as iF,sep as oF}from"node:path";function Jk(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function dF(e,t){return{contracts:t.filter(r=>Jk(r.spec)===e||Jk(r.impl)===e).map(r=>r.id),theme:cF.test(e),acl:lF.test(e)}}function uF(e){return e.contracts.length===0&&!e.theme&&!e.acl}function pF(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[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]},o[t]=a,e.write_health_seen=o}return l}function fF(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:
806
810
 
807
811
  `+e.map(n=>` \u2022 ${n.line}`).join(`
808
812
  `)+`
809
813
 
810
- 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 lL(e,t){let n=Q$(e,t);return!n||n.startsWith("..")||xk(n)?null:n.split(eL).join(Z$.sep)}function dL(e){try{let t=Y$(Ek(e,Ws),"utf8"),{manifest:n}=Js(t);return n?.contracts??[]}catch{return[]}}async function Tk(){try{let e=await K(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=Oe(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=xk(r)?r:Ek(i,r),a=J$(s)?X$(s):Gn(s),c=ft(of(a)),l=lL(c,a);if(l===null)return 0;let d=sL(l,dL(c));if(oL(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await _n(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=wn(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=bn(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 Q(),p=aL(f,n,c,u);f.pending_metrics.push({session_id:n,metric_key:tL,metric_value:1},{session_id:n,metric_key:nL,metric_value:p.length}),await tt(f);let h=cL(p,l);return h!==null&&process.stdout.write(Ca(h)),0}catch{return 0}}var tL,nL,rL,iL,Rk=_(()=>{"use strict";Ot();Dt();Jt();pe();af();Ia();De();tL="write_health_hook_runs",nL="write_health_hook_findings",rL=/\.(tsx?|jsx?|css)$/,iL=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;o(Sk,"declPath");o(sL,"routesForPath");o(oL,"routesAreEmpty");o(aL,"takeUnreported");o(cL,"formatWriteHealth");o(lL,"repoRelative");o(dL,"readContracts");o(Tk,"runOnWriteHealth")});var Uk={};ee(Uk,{agentHostPidCandidates:()=>nt,closeTrackedSession:()=>Pk,effectiveConfig:()=>Kn,grandparentPid:()=>$k,isCaptureTool:()=>cf,recordGuardSignals:()=>Dk,runFlush:()=>RL,runHookStatus:()=>AL,runOnFileEdit:()=>xL,runOnFileWrite:()=>SL,runOnRepoHealth:()=>kk,runOnSessionStart:()=>yL,runOnToolUse:()=>wL,runOnWriteHealth:()=>Tk,runSessionEndMetrics:()=>df,runSyncConfig:()=>IL,writeIdentitySideChannel:()=>lf});import{execFileSync as Ck}from"node:child_process";import{existsSync as Da,readFileSync as Ik,realpathSync as uL}from"node:fs";import{writeFile as fL}from"node:fs/promises";import{homedir as Nk}from"node:os";import{isAbsolute as Oa,join as rs,relative as Ok}from"node:path";function Dk(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=zu(n),s=n.includes("review_changes")||n.includes("review_verdict"),a=cf(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 cf(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 Pk(e,t,n=Date.now()){gL(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 gL(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>Na&&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>Na&&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>Na&&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>Na&&delete e.sessions[n]}}function Kn(e){if(e.config)return e.config;let t=q();return t===null?null:{api_key:t,endpoint:Ta}}function Mk(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 yL(){try{let r=Fv(Sa(Yi(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
811
- `)}catch{}let e=await Q();if(Kn(e)===null)return 0;let t=await K(),n=jk(t);if(n===null)return 0;Mk(e,n),await tt(e);try{lf(t,n)}catch{}try{let r=Y();if(r!==null){let i=Fn(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=Hn(i,{hostPids:nt(),cwd:s}),c=ek(a?.snap??null,Bi(Dr(t)||null,n)),l=tk(a?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
812
- `);let d=hs(Va(n,Lk(a?.snap??null,i,Date.now()),Date.now()));d!==null&&process.stdout.write(`[maind] ${d}
813
- `)}}catch{}try{let r=Ie(_L());if(Sd(r)&&Ro(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).
814
- `)}}catch{}return 0}function _L(){try{let e=rs(Nk(),".claude","settings.json");return Da(e)?Ik(e,"utf8"):null}catch{return null}}function lf(e,t,n,r=Fr()){let i=n??nt();if(i.length===0)return;let s=Bi(Dr(e)||null,t);if(s===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=Dr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)Zw({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:a,transcriptPath:c,model:l})}function $k(){try{if(process.platform==="win32")return null;let e=Ck("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 nt(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=$k();return n!==null&&n>1&&n!==t&&e.push(n),e}async function wL(){let e=await Q();if(Kn(e)===null)return 0;let t=await K(),n=jk(t)??"unknown",r=Mk(e,n);r.tool_call_count+=1;try{let a=nt().filter(c=>Qw(Fr(),c,bL));n!=="unknown"&&a.length>0&&lf(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),Dk(e,n,i),cf(i)&&n!=="unknown"&&await Z({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 pu(r.transcript_path);a&&(r.token_count=a.total_tokens,await TL(e,r))}await tt(e);try{let a=Date.now();if(n!=="unknown"&&!Vf(n,a)){let c=Y();if(c!==null){let l=Fn(c),d=Hn(l,{hostPids:nt(),cwd:typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd()}),u=hs(Va(n,Lk(d?.snap??null,l,a),a));u!==null&&process.stdout.write(Pe(`[maind] ${u}`)+`
815
- `)}}}catch{}return 0}function Lk(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)<vL)?.assigned_to_you??[]}function kL(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
814
+ 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 mF(e,t){let n=iF(e,t);return!n||n.startsWith("..")||Yk(n)?null:n.split(oF).join(rF.sep)}function hF(e){try{let t=tF(Xk(e,ss),"utf8"),{manifest:n}=ds(t);return n?.contracts??[]}catch{return[]}}async function Zk(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=re(e);if(!ye(n,{kind:"context",event:"PostToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"",i=Me(e);if(!r||!i)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=Yk(i)?i:Xk(o,i),c=eF(a)?nF(a):er(a),l=wt(kp(c)),d=mF(l,c);if(d===null)return 0;let u=dF(d,hF(l));if(uF(u))return 0;let p=[];if(u.contracts.length>0)try{let y=await Sn(l,{contracts:u.contracts});for(let _ of y.findings)_.status==="open"&&p.push({key:`spec:${_.id}`,line:`spec-drift (${_.contract}): ${_.detail}`})}catch{}if(u.theme)try{let y=Tn(l);for(let _ of y.findings)_.status==="open"&&p.push({key:`theme:${_.file}:${_.klass}`,line:`theme-class-drift: \`${_.klass}\` in ${_.file} \u2014 no token \`--color-${_.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(u.acl)try{let y=En(l);for(let _ of y.findings)_.status==="open"&&p.push({key:`acl:${_.id}`,line:`table-acl-lint: \`${_.table}\` (created in ${_.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let f=await ee(),m=pF(f,r,l,p);f.pending_metrics.push({session_id:r,metric_key:sF,metric_value:1},{session_id:r,metric_key:aF,metric_value:m.length}),await lt(f);let g=fF(m,d);if(g!==null){let y=ce(n,{kind:"context",event:"PostToolUse",text:g});y!==null&&process.stdout.write(y)}return 0}catch{return 0}}var sF,aF,cF,lF,Qk=v(()=>{"use strict";Ut();Bt();Re();ge();xp();za();$e();sF="write_health_hook_runs",aF="write_health_hook_findings",cF=/\.(tsx?|jsx?|css)$/,lF=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(Jk,"declPath");s(dF,"routesForPath");s(uF,"routesAreEmpty");s(pF,"takeUnreported");s(fF,"formatWriteHealth");s(mF,"repoRelative");s(hF,"readContracts");s(Zk,"runOnWriteHealth")});var px={};Q(px,{agentHostPidCandidates:()=>dt,closeTrackedSession:()=>sx,effectiveConfig:()=>tr,grandparentPid:()=>cx,isCaptureTool:()=>Sp,recordGuardSignals:()=>ox,runFlush:()=>PF,runHookStatus:()=>MF,runOnFileEdit:()=>NF,runOnFileWrite:()=>IF,runOnRepoHealth:()=>qk,runOnSessionStart:()=>xF,runOnToolUse:()=>RF,runOnWriteHealth:()=>Zk,runSessionEndMetrics:()=>Tp,runSyncConfig:()=>LF,writeIdentitySideChannel:()=>Ep});import{execFileSync as tx}from"node:child_process";import{existsSync as Ya,readFileSync as nx,realpathSync as gF}from"node:fs";import{writeFile as yF}from"node:fs/promises";import{homedir as rx}from"node:os";import{isAbsolute as Ja,join as go,relative as ix}from"node:path";function ox(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=dp(n),o=n.includes("review_changes")||n.includes("review_verdict"),a=Sp(n);if(!i&&!o&&!a)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),o&&(l.reviewed_at=d),a&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function Sp(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 sx(e,t,n=Date.now()){wF(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 wF(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>qa&&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(o=>Date.parse(o)||0));t-i>qa&&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(o=>Date.parse(o.at)||0));t-i>qa&&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>qa&&delete e.sessions[n]}}function tr(e){if(e.config)return e.config;let t=J();return t===null?null:{api_key:t,endpoint:Ka}}function ax(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}function kF(e){let t=ye(e,{kind:"text",event:"SessionStart"});if(!en(e.host))return{speaks:t,line:s(r=>void process.stdout.write(r),"line"),flush:s(async()=>{},"flush")};let n=[];return{speaks:t,line:s(r=>{t&&n.push(r)},"line"),flush:s(async()=>{if(n.length===0)return;let r=ce(e,{kind:"text",event:"SessionStart",text:n.join("")});r!==null&&await aa(r)},"flush")}}async function xF(){let e=await G(),t=re(e),n=kF(t);try{return await SF(e,t,n)}finally{await n.flush()}}async function SF(e,t,n){if(n.speaks)try{let o=ak(Ua(co(process.cwd(),{offline:!0})));o!==null&&n.line(o+`
815
+ `)}catch{}let r=await ee();if(tr(r)===null)return 0;let i=ux(e);if(i===null)return 0;ax(r,i),await lt(r);try{Ep(e,i)}catch{}try{let o=n.speaks?Y():null;if(o!==null){let a=Jn(o),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=Qn(a,{hostPids:dt(),cwd:c}),d=Ck(l?.snap??null,eo(Gr(e)||null,i)),u=Ak(l?.snap??a[0]??null,d.id,Date.now(),void 0,d.announceError);u!==null&&n.line(u+`
816
+ `);let p=Io(lc(i,lx(l?.snap??null,a,Date.now()),Date.now()));p!==null&&n.line(`[maind] ${p}
817
+ `)}}catch{}try{let o=en(t.host)?[]:Te(EF());if(jd(o)&&Bs(o)){let a=s(u=>o.filter(p=>p.remedy==="run-install"&&p.status===u).map(p=>p.subcommand).join(", "),"pick"),c=a("missing"),l=a("superseded"),d=[c?`not yet wired: ${c}`:null,l?`old form to replace: ${l}`:null].filter(u=>u!==null).join("; ");process.stderr.write(`[maind] New bridge capability (${d}) \u2014 run \`maind-mcp-bridge install --hooks-only\` once (asks consent per hook; adds what is missing and rewrites no entry of yours but the reminder's old \`cat\`).
818
+ `)}}catch{}return 0}function EF(){try{let e=go(rx(),".claude","settings.json");return Ya(e)?nx(e,"utf8"):null}catch{return null}}function Ep(e,t,n,r=qr()){let i=n??dt();if(i.length===0)return;let o=eo(Gr(e)||null,t);if(o===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=Gr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)ww({dir:r,agentPid:d,sessionId:t,transcriptStem:o,cwd:a,transcriptPath:c,model:l})}function cx(){try{if(process.platform==="win32")return null;let e=tx("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 dt(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=cx();return n!==null&&n>1&&n!==t&&e.push(n),e}async function RF(){let e=await ee();if(tr(e)===null)return 0;let t=await G(),n=ux(t)??"unknown",r=ax(e,n);r.tool_call_count+=1;try{let c=dt().filter(l=>kw(qr(),l,TF));n!=="unknown"&&c.length>0&&Ep(t,n,c)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),ox(e,n,i),Sp(i)&&n!=="unknown"&&await Z({event:"capture_taken",session_id:n,detail:i});let o=t.transcript_path;if(typeof o=="string"&&o&&!r.transcript_path&&(r.transcript_path=o),r.transcript_path){let c=await Cu(r.transcript_path);c&&(r.token_count=c.total_tokens,await DF(e,r))}await lt(e);let a=re(t);try{let c=Date.now();if(n!=="unknown"&&ye(a,{kind:"context",event:"PreToolUse"})&&!lf(n,c)){let l=Y();if(l!==null){let d=Jn(l),u=Qn(d,{hostPids:dt(),cwd:typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd()}),p=Io(lc(n,lx(u?.snap??null,d,c),c)),f=p===null?null:ce(a,{kind:"context",event:"PreToolUse",text:`[maind] ${p}`});f!==null&&process.stdout.write(f+`
819
+ `)}}}catch{}return 0}function lx(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)<CF)?.assigned_to_you??[]}function AF(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
816
820
  `);return`${t.prefix}${e.number} is already taken:
817
821
  ${n}
818
822
 
819
823
  Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
820
824
 
821
- 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 SL(){try{let e=await K();if((e.tool_name??"")!=="Write")return 0;let t=Oe(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=Oa(t)?t:rs(n,t);if(Da(r))return 0;let i=ft(n),s=Ok(i,Gn(r));if(s.length===0||s.startsWith("..")||Oa(s))return 0;let a=await yn(i,s);return!a.taken||a.namespace===null||process.stdout.write(Bn(kL(a,a.namespace))),0}catch{return 0}}async function xL(){try{let e=await K(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Oe(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Oa(n)?n:rs(r,n),s=Y();if(s===null)return 0;let a=Fn(s);if(a.length===0)return 0;let c=Hn(a,{hostPids:nt(),cwd:r});if(c===null)return 0;let l=ft(r),d=Da(i)?uL(i):Gn(i),u=Ok(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||Oa(u))return 0;let f=Qv(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?EL(r):null,nowMs:Date.now()});return f===null||process.stdout.write(Pe(f)),0}catch{return 0}}function EL(e){try{let n=Ck("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 TL(e,t){let n=Jd(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 fL(rs(ke,`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)}
822
- `)}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.
825
+ 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 IF(){try{let e=await G();if((e.tool_name??"")!=="Write")return 0;let t=re(e);if(!ye(t,{kind:"deny"}))return 0;let n=Me(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Ja(n)?n:go(r,n);if(Ya(i))return 0;let o=wt(r),a=ix(o,er(i));if(a.length===0||a.startsWith("..")||Ja(a))return 0;let c=await xn(o,a);if(!c.taken||c.namespace===null)return 0;let l=ce(t,{kind:"deny",reason:AF(c,c.namespace)});return l!==null&&process.stdout.write(l),0}catch{return 0}}async function NF(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=re(e);if(!ye(n,{kind:"context",event:"PreToolUse"}))return 0;let r=Me(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Ja(r)?r:go(i,r),a=Y();if(a===null)return 0;let c=Jn(a);if(c.length===0)return 0;let l=Qn(c,{hostPids:dt(),cwd:i});if(l===null)return 0;let d=wt(i),u=Ya(o)?gF(o):er(o),p=ix(d,u).replace(/\\/g,"/");if(p.length===0||p.startsWith("..")||Ja(p))return 0;let f=Rk(l.snap,p,{via:l.via,currentBranch:l.via==="cwd"?OF(i):null,nowMs:Date.now()});if(f===null)return 0;let m=ce(n,{kind:"context",event:"PreToolUse",text:f});return m!==null&&process.stdout.write(m),0}catch{return 0}}function OF(e){try{let n=tx("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 DF(e,t){let n=du(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,o="ok";if(i>=n.handoff_at_pct/100?o="handoff_recommended":i>=n.warn_at_pct/100&&(o="warn"),t.last_advisory_status===o||(t.last_advisory_status=o,o==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:o,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:o==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await yF(go(Ce,`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)}
826
+ `)}o==="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.
823
827
  `):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.
824
- `)}async function df(e){try{let t=await Q(),n=Kn(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Pk(t,r),await tt(t)),await Fk(n,mL)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
825
- `)}}async function RL(){let e=await Q(),t=Kn(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 Fk(t,hL);return process.stdout.write(JSON.stringify(n,null,2)+`
826
- `),n.ok?0:1}async function Fk(e,t){let n=await Q();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=Jv(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 Q();return c.pending_metrics=c.pending_metrics.slice(r.length),await tt(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 AL(){let e=await Q(),t=Kn(e),n=CL(),r=Sd(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:Jd(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})),...Ro(n.findings)?{remedy:Ak}:{}}},null,2)+`
828
+ `)}async function Tp(e){try{let t=await ee(),n=tr(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(sx(t,r),await lt(t)),await dx(n,bF)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
829
+ `)}}async function PF(){let e=await ee(),t=tr(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 dx(t,vF);return process.stdout.write(JSON.stringify(n,null,2)+`
830
+ `),n.ok?0:1}async function dx(e,t){let n=await ee();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=xk(e.endpoint,e.api_key,r),o=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,o]);if(a.ok){let c=await ee();return c.pending_metrics=c.pending_metrics.slice(r.length),await lt(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 MF(){let e=await ee(),t=tr(e),n=$F(),r=jd(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:du(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})),...Bs(n.findings)?{remedy:ex}:{}}},null,2)+`
827
831
  `),r){process.stderr.write(`
828
832
  [maind] Claude Code hook wiring is incomplete:
829
833
  `);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
830
- `);Ro(n.findings)&&process.stderr.write(` ${Ak}
831
- `)}return 0}function CL(){let e=rs(Nk(),".claude","settings.json"),t=null;try{Da(e)&&(t=Ik(e,"utf8"))}catch{}return{settingsPath:e,findings:Ie(t)}}async function IL(){let e=await Q(),t=Kn(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??pL,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)}
834
+ `);Bs(n.findings)&&process.stderr.write(` ${ex}
835
+ `)}return 0}function $F(){let e=go(rx(),".claude","settings.json"),t=null;try{Ya(e)&&(t=nx(e,"utf8"))}catch{}return{settingsPath:e,findings:Te(t)}}async function LF(){let e=await ee(),t=tr(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??_F,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)}
832
836
  `),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
833
837
  `);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
834
838
  `),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
835
- `),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
836
- `),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 tt(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
837
- `),0)}function jk(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var pL,mL,hL,Na,bL,vL,Ak,uf=_(()=>{"use strict";Un();Wr();Ot();Dt();gt();ie();jt();ca();Xr();ge();Hu();Bu();da();pe();Jt();Ia();De();br();xa();Uu();af();Rk();pL=process.env.MAIND_THRESHOLDS_ENDPOINT??_r("get-context-thresholds"),mL=1500,hL=1e4,Na=7*24*60*60*1e3;o(Dk,"recordGuardSignals");o(cf,"isCaptureTool");o(Pk,"closeTrackedSession");o(gL,"gcState");o(Kn,"effectiveConfig");o(Mk,"getOrCreateSession");o(yL,"runOnSessionStart");o(_L,"readSettingsRaw");o(lf,"writeIdentitySideChannel");bL=6e4;o($k,"grandparentPid");o(nt,"agentHostPidCandidates");o(wL,"runOnToolUse");vL=5*6e4;o(Lk,"assignedFrom");o(kL,"denyReason");o(SL,"runOnFileWrite");o(xL,"runOnFileEdit");o(EL,"currentGitBranch");o(TL,"maybeEmitAdvisory");o(df,"runSessionEndMetrics");o(RL,"runFlush");o(Fk,"flushPending");o(AL,"runHookStatus");Ak="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(CL,"readHookWiring");o(IL,"runSyncConfig");o(jk,"sessionIdOf")});function Hk(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Bk=_(()=>{"use strict";o(Hk,"resolveConnection")});function Kk(e,t,n,r=Date.now()){let i=t===null?null:Wi(t),s=typeof n=="object"&&n!==null?n:{repoRoot:n},a=Su(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,ff=_(()=>{"use strict";Un();Gk=2e3;o(Kk,"buildCostPayload")});function Vk(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!Wk.test(n))return null;let r=n.toLowerCase();return t!==null&&Wk.test(t)&&r!==t.toLowerCase()?null:r}var Wk,zk=_(()=>{"use strict";Wk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(Vk,"snapshotSessionId")});function OL(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();NL.test(r)&&!t.includes(r)&&t.push(r)}return t}async function qk(e){let t=e.now??Date.now,{turns:n,coordination_ids:r}=await Ki(e.transcriptPath),i=e.resolveRoot&&e.projectKeyOf?Tu({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:DL(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,s=i?Ru(n,i):null,a=s??e.projectKey,c=OL([e.coordSessionId,e.sessionId,...r]),[l,d,u]=await Promise.all([hu(e.transcriptPath,{turns:n}),Iu(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?Au(s,i):null,p=Kk(n,u,{repoRoot:e.repoRoot,relativize:f},t()),h=u===null?null:Wi(u)?.canonical_session_id??null,g=e.coordSessionId??h,y=_u(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 DL(e,t){try{return e()}catch{return t}}var NL,Jk=_(()=>{"use strict";Un();ff();NL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(OL,"sessionIdsFor");o(qk,"ingestSessionEnd");o(DL,"safe")});var Zk={};ee(Zk,{runOnSessionEnd:()=>KL});import{execFileSync as pf}from"node:child_process";import{statSync as PL}from"node:fs";function $L(e,t){try{let n=Y(),r=n!==null&&!au(process.env,Ne()),i=null;if(n!==null){let s=Hn(Fn(n),{hostPids:nt(),cwd:process.cwd()});if(s){let a=Date.parse(s.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return Hk({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function LL(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=Hn(Fn(r),{hostPids:nt(),cwd:process.cwd()}),s=Vk(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 FL(){try{let e=pf("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function jL(e){let t=Yk.get(e);if(t!==void 0)return t;let n=null;try{let r=pf("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 Yk.set(e,n),n}function UL(e){let t=Xk.get(e);if(t!==void 0)return t;let n=null;try{let r=pf("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=vr(r))}catch{n=null}return Xk.set(e,n),n}function HL(e){try{return PL(e).isDirectory()}catch{return!1}}async function BL(e,t,n,r){if(n===null)return null;let[i,...s]=r;try{return await pt("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:G,timeoutMs:Gk})}catch{return null}}async function GL(e,t,n,r,i){let s=fetch(ML,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":G},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=yu(gu(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
838
- `)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([s,a])}async function KL(){try{for(let i of nt())ev(Fr(),i)}catch{}let e=q();if(!e)return 0;let t=await K(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=Dr(t);if(r)try{let i=re(),s=LL(Bi(r,n)),a=Y();await qk({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:s,repoRoot:FL(),resolveRoot:jL,projectKeyOf:UL,knownCheckouts:o(()=>Vi(ns),"knownCheckouts"),isDir:HL,rememberCheckouts:o(c=>zi(ns,c),"rememberCheckouts"),fetchContext:o((c,l)=>BL(e,i,c,l),"fetchContext"),post:o((c,l)=>GL(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)}
839
- `)}return await df(n),0}var ML,Yk,Xk,Qk=_(()=>{"use strict";Un();Ut();ie();zt();Hu();Bu();pe();uf();cu();ca();ge();da();Ue();sf();Bk();ff();zk();Jk();ML=Ta;o($L,"connectionVerdict");o(LL,"presenceSessionId");o(FL,"sessionRepoRoot");Yk=new Map;o(jL,"gitRootOf");Xk=new Map;o(UL,"projectKeyOfRoot");o(HL,"isDirectory");o(BL,"fetchCostContext");o(GL,"postWithTimeout");o(KL,"runOnSessionEnd")});var eS={};ee(eS,{runOnSessionBriefing:()=>WL});async function WL(){try{return await Zo("core",await K())}catch{return 0}}var tS=_(()=>{"use strict";Mn();pe();o(WL,"runOnSessionBriefing")});var lS={};ee(lS,{CURSOR_BRIEFING_MARKER:()=>mf,CURSOR_DELIVERY_LOG:()=>nS,CURSOR_UNAVAILABLE_TEXT:()=>iS,appendDelivery:()=>aS,cursorProjectDir:()=>rS,deliverCursorSessionStart:()=>oS,formatCursorBriefing:()=>sS,runOnCursorSessionStart:()=>tF});import{appendFile as VL,mkdir as zL,readFile as qL,stat as JL,writeFile as YL}from"node:fs/promises";import{dirname as XL,join as ZL}from"node:path";function rS(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let i=r.find(s=>typeof s=="string"&&s.length>0);if(i)return i}return null}function sS(e,t,n){let i=`${mf}${n?" + project conventions":""}, delivered by the bridge's sessionStart hook (ADR-359)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`;return Jo(i,n,e)}async function oS(e,t={}){let n=t.write??cS,r=t.env??process.env,i=(t.apiKey??q)();if(i===null)return await n(`{}
840
- `),0;let s=rS(e,r),a=s===null?null:(t.projectKeyFor??Pt)(s),c=await Mr(a,i,{fetcher:o(f=>Or({...f,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=iS,d="none";else{let f=sS(c.text,c.via,c.conventions??null);l=f.text.trimEnd(),d=c.via,u=f.complete}return await n(JSON.stringify({additional_context:l})+`
841
- `),await aS(t.logFile??nS,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Vr(e.conversation_id)??Vr(e.session_id),transcript_path:Vr(e.transcript_path)??Vr(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Vr(e.cursor_version)??Vr(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function tF(){try{return await oS(await K())}catch{try{await cS(`{}
842
- `)}catch{}return 0}}async function aS(e,t){try{if(await zL(XL(e),{recursive:!0,mode:448}),await VL(e,JSON.stringify(t)+`
843
- `,{mode:384}),(await JL(e)).size>QL){let n=(await qL(e,"utf8")).split(`
844
- `).filter(r=>r.trim().length>0);await YL(e,n.slice(-eF).join(`
839
+ `),1}let o=i;return typeof o.warn_at_pct!="number"||typeof o.handoff_at_pct!="number"||typeof o.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
840
+ `),1):(e.thresholds={warn_at_pct:o.warn_at_pct,handoff_at_pct:o.handoff_at_pct,model_token_limit:o.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await lt(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
841
+ `),0)}function ux(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var _F,bF,vF,qa,TF,CF,ex,Rp=v(()=>{"use strict";Xn();ei();Ut();Bt();Et();se();at();Ta();si();we();ip();op();Ca();ge();Re();za();$e();Ar();Ba();rp();xp();Qk();_F=process.env.MAIND_THRESHOLDS_ENDPOINT??Cr("get-context-thresholds"),bF=1500,vF=1e4,qa=7*24*60*60*1e3;s(ox,"recordGuardSignals");s(Sp,"isCaptureTool");s(sx,"closeTrackedSession");s(wF,"gcState");s(tr,"effectiveConfig");s(ax,"getOrCreateSession");s(kF,"sessionStartOut");s(xF,"runOnSessionStart");s(SF,"sessionStartBody");s(EF,"readSettingsRaw");s(Ep,"writeIdentitySideChannel");TF=6e4;s(cx,"grandparentPid");s(dt,"agentHostPidCandidates");s(RF,"runOnToolUse");CF=5*6e4;s(lx,"assignedFrom");s(AF,"denyReason");s(IF,"runOnFileWrite");s(NF,"runOnFileEdit");s(OF,"currentGitBranch");s(DF,"maybeEmitAdvisory");s(Tp,"runSessionEndMetrics");s(PF,"runFlush");s(dx,"flushPending");s(MF,"runHookStatus");ex="Re-run `maind-mcp-bridge install --hooks-only` to add the missing hooks \u2014 it is idempotent: it adds only what is absent, asks consent per hook, and rewrites no entry you already have except the SessionStart reminder's old `cat`, which it replaces with on-session-reminder (MAIND-630).";s($F,"readHookWiring");s(LF,"runSyncConfig");s(ux,"sessionIdOf")});function fx(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var mx=v(()=>{"use strict";s(fx,"resolveConnection")});function gx(e,t,n,r=Date.now()){let i=t===null?null:ro(t),o=typeof n=="object"&&n!==null?n:{repoRoot:n},a=Fu(e,i,{repoRoot:o.repoRoot,...o.relativize?{relativize:o.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:i!==null}}var hx,Cp=v(()=>{"use strict";Xn();hx=2e3;s(gx,"buildCostPayload")});function _x(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!yx.test(n))return null;let r=n.toLowerCase();return t!==null&&yx.test(t)&&r!==t.toLowerCase()?null:r}var yx,bx=v(()=>{"use strict";yx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(_x,"snapshotSessionId")});function jF(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();FF.test(r)&&!t.includes(r)&&t.push(r)}return t}async function vx(e){let t=e.now??Date.now,{turns:n,coordination_ids:r}=await no(e.transcriptPath),i=e.resolveRoot&&e.projectKeyOf?Uu({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:HF(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,o=i?Bu(n,i):null,a=o??e.projectKey,c=jF([e.coordSessionId,e.sessionId,...r]),[l,d,u]=await Promise.all([Iu(e.transcriptPath,{turns:n}),Wu(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 p=o&&i?Gu(o,i):null,f=gx(n,u,{repoRoot:e.repoRoot,relativize:p},t()),m=u===null?null:ro(u)?.canonical_session_id??null,g=e.coordSessionId??m,y=Du(l,d,{client_session_id:g,client:"claude-code",coordination_session_ids:c},"live_bridge",f);return await e.post(y,f!==null),{posted:!0,contextOk:f?.context_ok??u!==null,sentSlices:f!==null}}function HF(e,t){try{return e()}catch{return t}}var FF,wx=v(()=>{"use strict";Xn();Cp();FF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(jF,"sessionIdsFor");s(vx,"ingestSessionEnd");s(HF,"safe")});var Ex={};Q(Ex,{runOnSessionEnd:()=>XF,transcriptToIngest:()=>Sx});import{execFileSync as Ap}from"node:child_process";import{statSync as UF}from"node:fs";function GF(e,t){try{let n=Y(),r=n!==null&&!ku(process.env,te()),i=null;if(n!==null){let o=Qn(Jn(n),{hostPids:dt(),cwd:process.cwd()});if(o){let a=Date.parse(o.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return fx({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function KF(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=Qn(Jn(r),{hostPids:dt(),cwd:process.cwd()}),o=_x(i?.snap,e);if(o!==null)return o}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function WF(){try{let e=Ap("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function VF(e){let t=kx.get(e);if(t!==void 0)return t;let n=null;try{let r=Ap("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 kx.set(e,n),n}function zF(e){let t=xx.get(e);if(t!==void 0)return t;let n=null;try{let r=Ap("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=Nr(r))}catch{n=null}return xx.set(e,n),n}function qF(e){try{return UF(e).isDirectory()}catch{return!1}}async function JF(e,t,n,r){if(n===null)return null;let[i,...o]=r;try{return await kt("get_session_cost_context",{project_key:n,...i?{session_id:i}:{},...o.length>0?{also_session_ids:o}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:K,timeoutMs:hx})}catch{return null}}async function YF(e,t,n,r,i){let o=fetch(BF,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":K},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=Ou(Nu(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
842
+ `)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([o,a])}function Sx(e,t=process.env){let n=Gr(e);return n&&!en(Yi(e,t))?n:""}async function XF(){try{for(let i of dt())xw(qr(),i)}catch{}let e=J();if(!e)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=Sx(t);if(r)try{let i=oe(),o=KF(eo(r,n)),a=Y();await vx({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:o,repoRoot:WF(),resolveRoot:VF,projectKeyOf:zF,knownCheckouts:s(()=>io(ho),"knownCheckouts"),isDir:qF,rememberCheckouts:s(c=>oo(ho,c),"rememberCheckouts"),fetchContext:s((c,l)=>JF(e,i,c,l),"fetchContext"),post:s((c,l)=>YF(e,i,c,1500,l),"post"),connection:GF})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
843
+ `)}return await Tp(n),0}var BF,kx,xx,Tx=v(()=>{"use strict";Xn();We();se();Qt();ip();op();ge();Re();Rp();xu();Ta();we();Ca();Ge();wp();mx();Cp();bx();wx();BF=Ka;s(GF,"connectionVerdict");s(KF,"presenceSessionId");s(WF,"sessionRepoRoot");kx=new Map;s(VF,"gitRootOf");xx=new Map;s(zF,"projectKeyOfRoot");s(qF,"isDirectory");s(JF,"fetchCostContext");s(YF,"postWithTimeout");s(Sx,"transcriptToIngest");s(XF,"runOnSessionEnd")});var Rx={};Q(Rx,{runOnSessionBriefing:()=>ZF});async function ZF(){try{return await ga("core",await G())}catch{return 0}}var Cx=v(()=>{"use strict";Vn();ge();s(ZF,"runOnSessionBriefing")});var Ix={};Q(Ix,{deliverSessionReminder:()=>Ax,runOnSessionReminder:()=>nj});import{readFile as QF}from"node:fs/promises";import{homedir as ej}from"node:os";import{join as tj}from"node:path";async function Ax(e,t={}){let n=t.target??re(e);if(!ye(n,{kind:"text",event:"SessionStart"}))return 0;let r;try{r=await QF(tj(t.homeDir??ej(),Fd),"utf8")}catch{return 0}if(r.length===0)return 0;let i=ce(n,{kind:"text",event:"SessionStart",text:r});return i!==null&&await(t.write??aa)(i),0}async function nj(){try{return await Ax(await G())}catch{return 0}}var Nx=v(()=>{"use strict";at();ge();Re();s(Ax,"deliverSessionReminder");s(nj,"runOnSessionReminder")});var jx={};Q(jx,{CURSOR_BRIEFING_MARKER:()=>Ip,CURSOR_DELIVERY_LOG:()=>Ox,CURSOR_UNAVAILABLE_TEXT:()=>Px,appendDelivery:()=>Lx,cursorProjectDir:()=>Dx,deliverCursorSessionStart:()=>$x,formatCursorBriefing:()=>Mx,runOnCursorSessionStart:()=>pj});import{appendFile as rj,mkdir as ij,readFile as oj,stat as sj,writeFile as aj}from"node:fs/promises";import{dirname as cj,join as lj}from"node:path";function Dx(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let i=r.find(o=>typeof o=="string"&&o.length>0);if(i)return i}return null}function Mx(e,t,n){let i=`${Ip}${n?" + project conventions":""}, delivered by the bridge's sessionStart hook (ADR-359)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`;return fa(i,n,e)}async function $x(e,t={}){let n=t.write??Fx,r=t.env??process.env,i=(t.apiKey??J)();if(i===null)return await n(`{}
844
+ `),0;let o=Dx(e,r),a=o===null?null:(t.projectKeyFor??nt)(o),c=await Wr(a,i,{fetcher:s(p=>Br({...p,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=Px,d="none";else{let p=Mx(c.text,c.via,c.conventions??null);l=p.text.trimEnd(),d=c.via,u=p.complete}return await n(JSON.stringify({additional_context:l})+`
845
+ `),await Lx(t.logFile??Ox,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:ti(e.conversation_id)??ti(e.session_id),transcript_path:ti(e.transcript_path)??ti(r.CURSOR_TRANSCRIPT_PATH),cursor_version:ti(e.cursor_version)??ti(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function pj(){try{return await $x(await G())}catch{try{await Fx(`{}
846
+ `)}catch{}return 0}}async function Lx(e,t){try{if(await ij(cj(e),{recursive:!0,mode:448}),await rj(e,JSON.stringify(t)+`
847
+ `,{mode:384}),(await sj(e)).size>dj){let n=(await oj(e,"utf8")).split(`
848
+ `).filter(r=>r.trim().length>0);await aj(e,n.slice(-uj).join(`
845
849
  `)+`
846
- `,{mode:384})}}catch{}}function cS(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var mf,nS,QL,eF,Vr,iS,dS=_(()=>{"use strict";ie();Mn();zt();Yo();ge();pe();De();mf="[maind] Cursor session briefing",nS=ZL(ke,"cursor","deliveries.jsonl"),QL=512*1024,eF=2e3,Vr=o(e=>typeof e=="string"&&e.length>0?e:null,"str");o(rS,"cursorProjectDir");iS=`${mf} 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.`;o(sS,"formatCursorBriefing");o(oS,"deliverCursorSessionStart");o(tF,"runOnCursorSessionStart");o(aS,"appendDelivery");o(cS,"writeStdout")});function nF(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 uS(e,t,n=process.stdout){let r=nF(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
847
- `),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 Tr)s.push(await Id(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
848
- `);let a=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
850
+ `,{mode:384})}}catch{}}function Fx(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var Ip,Ox,dj,uj,ti,Px,Hx=v(()=>{"use strict";se();Vn();Qt();ma();we();ge();$e();Ip="[maind] Cursor session briefing",Ox=lj(Ce,"cursor","deliveries.jsonl"),dj=512*1024,uj=2e3,ti=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Dx,"cursorProjectDir");Px=`${Ip} 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.`;s(Mx,"formatCursorBriefing");s($x,"deliverCursorSessionStart");s(pj,"runOnCursorSessionStart");s(Lx,"appendDelivery");s(Fx,"writeStdout")});function fj(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 Ux(e,t,n=process.stdout){let r=fj(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
851
+ `),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of $r)o.push(await Kd(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
852
+ `);let a=o.some(l=>l.detail==="user declined"),c=o.some(l=>l.status==="failed");return r.dryRun?(n.write(`
849
853
  [dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
850
- `),0):(await Dn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
854
+ `),0):(await Kn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
851
855
  Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
852
856
  flip: maind-mcp-bridge guard mode <warn|block>
853
857
  disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
854
858
  check: maind-mcp-bridge guard status
855
859
  Takes effect for NEW Claude Code sessions (hooks are read at session start).
856
860
  `),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
857
- `),c?1:0)}var fS=_(()=>{"use strict";jt();Od();et();o(nF,"parseGuardInstallFlags");o(uS,"runGuardInstall")});import{existsSync as pS}from"node:fs";import{appendFile as rF,mkdir as iF,readFile as sF}from"node:fs/promises";import{join as oF}from"node:path";function hf(e,t=Pa){return oF(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function zr(e,t=Pa){return pS(hf(e,t))}async function Yt(e,t,n=Pa){try{await iF(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await rF(hf(e,n),r+`
858
- `,{mode:384})}catch{}}async function Wn(e,t=Pa){try{let n=hf(e,t);if(!pS(n))return[];let r=[];for(let i of(await sF(n,"utf8")).split(`
859
- `))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"||!aF.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var Pa,aF,is=_(()=>{"use strict";ht();Pa=Xd,aF=new Set(["fail","ok","nudge","skip","prompt"]);o(hf,"triggerLogPath");o(zr,"hasTriggerLog");o(Yt,"appendTriggerEvent");o(Wn,"loadTriggerEvents")});import{existsSync as cF}from"node:fs";import{mkdir as lF,readFile as dF,rename as uF,writeFile as fF}from"node:fs/promises";import{dirname as pF,join as mF}from"node:path";function ss(e=process.env){let t=q();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??Li,keyFp:gr(t)}}async function gf(e,t=Date.now(),n=Ma){try{if(!cF(n))return null;let r=JSON.parse(await dF(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:Aa([s?.difficulty,s?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<hF}}catch{return null}}async function yF(e,t,n,r){try{await lF(pF(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 fF(s,JSON.stringify(i,null,2),{mode:384}),await uF(s,r)}catch{}}async function _F(){let e=q();if(e===null)return null;let t=null;try{t=Y()}catch{t=null}let n=await pt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:bF(),projectKey:t,bridgeVersion:G,timeoutMs:gF});if(n===null)return null;try{return Aa(JSON.parse(n))}catch{return null}}async function qr(e,t={}){let n=t.nowMs??Date.now(),r=t.file??Ma,i=t.identity===void 0?ss():t.identity;if(i===null)return es;let s=await gf(i,n,r);if(s?.fresh)return s.policy;if(e){let a=await(t.fetcher??_F)();if(a!==null)return await yF(i,a,n,r),a}return s?.policy??es}function bF(){try{return re()}catch{return null}}var Ma,hF,gF,Jr=_(()=>{"use strict";Wr();Dt();ie();ge();Ue();zt();ht();Ma=mF(Be,"trigger-policy.json"),hF=12*60*60*1e3,gF=3e3;o(ss,"currentIdentity");o(gf,"readCachedPolicy");o(yF,"writeCachedPolicy");o(_F,"fetchTriggerPolicy");o(qr,"resolveTriggerPolicy");o(bF,"safeDeviceId")});var hS={};ee(hS,{runGuard:()=>xF});import{existsSync as wF,readFileSync as vF}from"node:fs";import{homedir as mS}from"node:os";import{join as kF}from"node:path";async function xF(e){let t=e[0],n=e.slice(1);switch(t){case"install":return uS(n,mS());case"status":return TF();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
860
- `),1):(await Dn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
861
- `),0)}case"off":return await Dn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
861
+ `),c?1:0)}var Bx=v(()=>{"use strict";at();Vd();ct();s(fj,"parseGuardInstallFlags");s(Ux,"runGuardInstall")});import{existsSync as Gx}from"node:fs";import{appendFile as mj,mkdir as hj,readFile as gj}from"node:fs/promises";import{join as yj}from"node:path";function Np(e,t=Xa){return yj(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function ni(e,t=Xa){return Gx(Np(e,t))}async function nn(e,t,n=Xa){try{await hj(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await mj(Np(e,n),r+`
862
+ `,{mode:384})}catch{}}async function nr(e,t=Xa){try{let n=Np(e,t);if(!Gx(n))return[];let r=[];for(let i of(await gj(n,"utf8")).split(`
863
+ `))if(i.trim())try{let o=JSON.parse(i),a=o.t,c=o.k,l=o.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!_j.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var Xa,_j,yo=v(()=>{"use strict";St();Xa=pu,_j=new Set(["fail","ok","nudge","skip","prompt"]);s(Np,"triggerLogPath");s(ni,"hasTriggerLog");s(nn,"appendTriggerEvent");s(nr,"loadTriggerEvents")});import{existsSync as bj}from"node:fs";import{mkdir as vj,readFile as wj,rename as kj,writeFile as xj}from"node:fs/promises";import{dirname as Sj,join as Ej}from"node:path";function _o(e=process.env){let t=J();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??zi,keyFp:Tr(t)}}async function Op(e,t=Date.now(),n=Za){try{if(!bj(n))return null;let r=JSON.parse(await wj(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 o=r.policy;return{policy:Va([o?.difficulty,o?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<Tj}}catch{return null}}async function Cj(e,t,n,r){try{await vj(Sj(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},o=`${r}.tmp`;await xj(o,JSON.stringify(i,null,2),{mode:384}),await kj(o,r)}catch{}}async function Aj(){let e=J();if(e===null)return null;let t=null;try{t=Y()}catch{t=null}let n=await kt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:Ij(),projectKey:t,bridgeVersion:K,timeoutMs:Rj});if(n===null)return null;try{return Va(JSON.parse(n))}catch{return null}}async function ri(e,t={}){let n=t.nowMs??Date.now(),r=t.file??Za,i=t.identity===void 0?_o():t.identity;if(i===null)return fo;let o=await Op(i,n,r);if(o?.fresh)return o.policy;if(e){let a=await(t.fetcher??Aj)();if(a!==null)return await Cj(i,a,n,r),a}return o?.policy??fo}function Ij(){try{return oe()}catch{return null}}var Za,Tj,Rj,ii=v(()=>{"use strict";ei();Bt();se();we();Ge();Qt();St();Za=Ej(ze,"trigger-policy.json"),Tj=12*60*60*1e3,Rj=3e3;s(_o,"currentIdentity");s(Op,"readCachedPolicy");s(Cj,"writeCachedPolicy");s(Aj,"fetchTriggerPolicy");s(ri,"resolveTriggerPolicy");s(Ij,"safeDeviceId")});var Wx={};Q(Wx,{runGuard:()=>Mj});import{existsSync as Nj,readFileSync as Oj}from"node:fs";import{homedir as Kx}from"node:os";import{join as Dj}from"node:path";async function Mj(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Ux(n,Kx());case"status":return Lj();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
864
+ `),1):(await Kn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
865
+ `),0)}case"off":return await Kn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
862
866
  `),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>
863
- `),1):(await Dn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
867
+ `),1):(await Kn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
864
868
  `),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>
865
- `),1):(await Dn(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.
869
+ `),1):(await Kn(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.
866
870
  `:`${t} trigger disabled on this machine (your convention prefs are unchanged).
867
- `),0)}case"skip":return EF(n);default:return process.stdout.write(SF),t===void 0||t==="--help"||t==="-h"?0:1}}async function EF(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]
868
- `),1;let i=n.trim().slice(0,500);if(r!=="consult")return await Yt(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await Z({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
869
- logged (auditable) in ${Pn}
870
- `),0;let s=await mt(t);return await ve(t,{...s,override_reason:i}),await Z({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.
871
- logged (auditable) in ${Pn}
872
- `),0}async function TF(){let e=oe(),t=kF(mS(),".claude","settings.json"),n=null;try{wF(t)&&(n=vF(t,"utf8"))}catch{}let r=Ie(n,{},Tr),i=await Yb(),s=ss(),a=s?await gf(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:Wo(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:Ma},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:Pn},null,2)+`
871
+ `),0)}case"skip":return $j(n);default:return process.stdout.write(Pj),t===void 0||t==="--help"||t==="-h"?0:1}}async function $j(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]
872
+ `),1;let i=n.trim().slice(0,500);if(r!=="consult")return await nn(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await Z({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
873
+ logged (auditable) in ${Wn}
874
+ `),0;let o=await xt(t);return await Ee(t,{...o,override_reason:i}),await Z({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.
875
+ logged (auditable) in ${Wn}
876
+ `),0}async function Lj(){let e=le(),t=Dj(Kx(),".claude","settings.json"),n=null;try{Nj(t)&&(n=Oj(t,"utf8"))}catch{}let r=Te(n,{},$r),i=await bv(),o=_o(),a=o?await Op(o):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:la(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:Za},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:Wn},null,2)+`
873
877
  `);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(`
874
878
  [maind] guard hook wiring is incomplete:
875
879
  `);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
876
- `);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 SF,gS=_(()=>{"use strict";Vo();jt();et();fS();gt();ht();is();Jr();SF=["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(`
877
- `);o(xF,"runGuard");o(EF,"runGuardSkip");o(TF,"runGuardStatus")});var bS={};ee(bS,{bashOutputOf:()=>yS,consultedAtOf:()=>$a,outcomeFromHook:()=>_S,runGuardDifficulty:()=>AF});function yS(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(`
878
- `):null,interrupted:t.interrupted===!0}}function _S(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"?yS(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 $a(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 RF(e,t,n){if(!zr(e))return;let r=await Wn(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let i=Gr(r,null,n);await Yt(e,{t:n,k:"ok",v:t});let s=i.chain;s!==null&&s.failures.length>=4&&!i.resolved&&s.lastVerb===t&&await Z({event:"difficulty_resolved",session_id:e,detail:String(s.failures.length)})}async function AF(){try{let e=oe();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await K(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=_S(t);if(r===null)return 0;let i=qu(r.outcome);if(i===null)return 0;let s=Date.now();if(i.kind==="ok")return await RF(n,i.verb,s),0;await Yt(n,{t:s,k:"fail",v:i.verb});let a=await Wn(n),c=Gr(a,$a(await Q(),n),s);if(!Xu(c)||c.chain===null)return 0;let l=await qr(!0);if(!e.difficulty||!Kr(l.difficulty))return 0;await Yt(n,{t:s,k:"nudge"});let d=ts(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?mk(d):Ca(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await Z({event:"difficulty_nudge",session_id:n,cwd:u,project_key:Y()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var yf=_(()=>{"use strict";Wr();pe();Jt();De();ge();et();gt();is();Jr();o(yS,"bashOutputOf");o(_S,"outcomeFromHook");o($a,"consultedAtOf");o(RF,"recordSuccess");o(AF,"runGuardDifficulty")});var SS={};ee(SS,{decideDifficultyGate:()=>kS,decideGate:()=>vS,runGuardGate:()=>NF});function vS(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:wS(n)}:(n.deny_count??0)>=La?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. "+wS(n)}:{kind:"deny",reason:CF(e.sessionId,n)}}function wS(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 CF(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:
880
+ `);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 Pj,Vx=v(()=>{"use strict";da();at();ct();Bx();Et();St();yo();ii();Pj=["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(`
881
+ `);s(Mj,"runGuard");s($j,"runGuardSkip");s(Lj,"runGuardStatus")});var Jx={};Q(Jx,{bashOutputOf:()=>zx,consultedAtOf:()=>Qa,outcomeFromHook:()=>qx,runGuardDifficulty:()=>jj});function zx(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(`
882
+ `):null,interrupted:t.interrupted===!0}}function qx(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"?zx(e.tool_response):{output:null,interrupted:!1},o=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 o=="string"&&o.length>0}}}function Qa(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 Fj(e,t,n){if(!ni(e))return;let r=await nr(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let i=Zr(r,null,n);await nn(e,{t:n,k:"ok",v:t});let o=i.chain;o!==null&&o.failures.length>=4&&!i.resolved&&o.lastVerb===t&&await Z({event:"difficulty_resolved",session_id:e,detail:String(o.failures.length)})}async function jj(){try{let e=le();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await G();if(Ve(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=qx(t);if(r===null)return 0;let i=up(r.outcome);if(i===null)return 0;let o=Date.now();if(i.kind==="ok")return await Fj(n,i.verb,o),0;await nn(n,{t:o,k:"fail",v:i.verb});let a=await nr(n),c=Zr(a,Qa(await ee(),n),o);if(!mp(c)||c.chain===null)return 0;let l=await ri(!0);if(!e.difficulty||!Qr(l.difficulty))return 0;await nn(n,{t:o,k:"nudge"});let d=mo(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?sa(d):qi(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await Z({event:"difficulty_nudge",session_id:n,cwd:u,project_key:Y()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Dp=v(()=>{"use strict";ei();ge();Re();Ji();$e();we();ct();Et();yo();ii();s(zx,"bashOutputOf");s(qx,"outcomeFromHook");s(Qa,"consultedAtOf");s(Fj,"recordSuccess");s(jj,"runGuardDifficulty")});var Qx={};Q(Qx,{decideDifficultyGate:()=>Zx,decideGate:()=>Xx,runGuardGate:()=>Bj});function Xx(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:Yx(n)}:(n.deny_count??0)>=ec?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. "+Yx(n)}:{kind:"deny",reason:Hj(e.sessionId,n)}}function Yx(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 Hj(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:
879
883
  1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
880
884
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
881
- After ${La} denies this gate downgrades itself to warn.`}function kS(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)>=La?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. "+ts(n.chain)}:{kind:"deny",reason:IF(n,e.sessionId)}}function IF(e,t){return`[maind guard | block] Edit denied \u2014 ${nf(e.chain)}. Two exits:
885
+ After ${ec} denies this gate downgrades itself to warn.`}function Zx(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)>=ec?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. "+mo(n.chain)}:{kind:"deny",reason:Uj(n,e.sessionId)}}function Uj(e,t){return`[maind guard | block] Edit denied \u2014 ${bp(e.chain)}. Two exits:
882
886
  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.
883
887
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
884
- After ${La} denies this gate downgrades itself to warn.`}async function NF(){try{let e=oe();if(e.mode==="off")return 0;let t=await K(),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 mt(r),s=$a(await Q(),r),a=s!==null,c=vS({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(Bn(c.reason)),await ve(r,{...i,deny_count:(i.deny_count??0)+1}),await Z({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(Pe(c.context)),await ve(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await Z({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&zr(r)){let u=Gr(await Wn(r),s,Date.now()),f=u.open?kS({mode:e.mode,enabled:e.difficulty,denyCapable:ef((await qr(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(f.kind==="deny")return process.stdout.write(Bn(f.reason)),await ve(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await Z({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(Pe(f.context)),await ve(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await ve(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var La,xS=_(()=>{"use strict";Wr();pe();Jt();De();ge();et();yf();gt();ht();is();Jr();La=3;o(vS,"decideGate");o(wS,"warnText");o(CF,"denyText");o(kS,"decideDifficultyGate");o(IF,"difficultyDenyText");o(NF,"runGuardGate")});var TS={};ee(TS,{decideStopGate:()=>ES,runGuardStop:()=>DF});function ES(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function DF(){try{let e=oe();if(e.mode==="off"||!e.stopGate)return 0;let t=await K(),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 mt(n),i=(await Q()).guard_signals?.[n]?.reviewed_at!==void 0;return ES({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:OF})),await ve(n,{...r,stop_blocked:!0}),await Z({event:"stop_block",session_id:n})),0}catch{return 0}}var OF,RS=_(()=>{"use strict";pe();De();et();gt();ht();o(ES,"decideStopGate");OF="[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(DF,"runGuardStop")});var IS={};ee(IS,{capturedAtOf:()=>AS,decideCapture:()=>CS,runGuardCapture:()=>PF});function AS(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 CS(e){if(e.stopHookActive||!Kr(e.policy.capture))return null;let t=Zu(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:rf(t)}}async function PF(){try{let e=oe();if(e.mode==="off"||!e.capture)return 0;let t=await K(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!zr(n))return 0;let r=CS({events:await Wn(n),capturedAtMs:AS(await Q(),n),policy:await qr(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await Yt(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await Z({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var NS=_(()=>{"use strict";Wr();pe();De();et();gt();is();Jr();o(AS,"capturedAtOf");o(CS,"decideCapture");o(PF,"runGuardCapture")});import{appendFile as MF,mkdir as $F,readFile as DS,rename as PS,writeFile as MS}from"node:fs/promises";import{homedir as $S}from"node:os";import{join as LS}from"node:path";function FS(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 Vn(){return LS($S(),".maind","gateway","attest-spool.jsonl")}async function _f(e){let t=q();if(t===null)return!1;let n=await pt("gateway_attest",{...e},{apiKey:t,deviceId:re(),projectKey:e.project_key??null,bridgeVersion:G,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function jS(e){try{await $F(LS($S(),".maind","gateway"),{recursive:!0}),await MF(Vn(),JSON.stringify(e)+`
885
- `,{mode:384}),await LF()}catch{}}async function LF(){try{let t=(await DS(Vn(),"utf8")).split(`
886
- `).filter(r=>r.trim());if(t.length<=OS)return;let n=`${Vn()}.${process.pid}.tmp`;await MS(n,t.slice(-OS).join(`
888
+ After ${ec} denies this gate downgrades itself to warn.`}async function Bj(){try{let e=le();if(e.mode==="off")return 0;let t=await G();if(Ve(t))return 0;let 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 xt(r),o=Qa(await ee(),r),a=o!==null,c=Xx({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(Un(c.reason)),await Ee(r,{...i,deny_count:(i.deny_count??0)+1}),await Z({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(Bn(c.context)),await Ee(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await Z({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&ni(r)){let u=Zr(await nr(r),o,Date.now()),p=u.open?Zx({mode:e.mode,enabled:e.difficulty,denyCapable:yp((await ri(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(Un(p.reason)),await Ee(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await Z({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(Bn(p.context)),await Ee(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await Ee(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var ec,eS=v(()=>{"use strict";ei();ge();Re();Ji();$e();we();ct();Dp();Et();St();yo();ii();ec=3;s(Xx,"decideGate");s(Yx,"warnText");s(Hj,"denyText");s(Zx,"decideDifficultyGate");s(Uj,"difficultyDenyText");s(Bj,"runGuardGate")});var nS={};Q(nS,{decideStopGate:()=>tS,runGuardStop:()=>Kj});function tS(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function Kj(){try{let e=le();if(e.mode==="off"||!e.stopGate)return 0;let t=await G();if(Ve(t))return 0;let 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 xt(n),i=(await ee()).guard_signals?.[n]?.reviewed_at!==void 0;return tS({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:Gj})),await Ee(n,{...r,stop_blocked:!0}),await Z({event:"stop_block",session_id:n})),0}catch{return 0}}var Gj,rS=v(()=>{"use strict";ge();Re();$e();ct();Et();St();s(tS,"decideStopGate");Gj="[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.";s(Kj,"runGuardStop")});var sS={};Q(sS,{capturedAtOf:()=>iS,decideCapture:()=>oS,runGuardCapture:()=>Wj});function iS(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 oS(e){if(e.stopHookActive||!Qr(e.policy.capture))return null;let t=hp(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:vp(t)}}async function Wj(){try{let e=le();if(e.mode==="off"||!e.capture)return 0;let t=await G();if(Ve(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!ni(n))return 0;let r=oS({events:await nr(n),capturedAtMs:iS(await ee(),n),policy:await ri(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await nn(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await Z({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var aS=v(()=>{"use strict";ei();ge();Re();$e();ct();Et();yo();ii();s(iS,"capturedAtOf");s(oS,"decideCapture");s(Wj,"runGuardCapture")});import{appendFile as Vj,mkdir as zj,readFile as lS,rename as dS,writeFile as uS}from"node:fs/promises";import{homedir as pS}from"node:os";import{join as fS}from"node:path";function mS(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=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=o.get(d.convention_id);(p===void 0||d.convention_version>p)&&o.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:[...o.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function rr(){return fS(pS(),".maind","gateway","attest-spool.jsonl")}async function Pp(e){let t=J();if(t===null)return!1;let n=await kt("gateway_attest",{...e},{apiKey:t,deviceId:oe(),projectKey:e.project_key??null,bridgeVersion:K,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function hS(e){try{await zj(fS(pS(),".maind","gateway"),{recursive:!0}),await Vj(rr(),JSON.stringify(e)+`
889
+ `,{mode:384}),await qj()}catch{}}async function qj(){try{let t=(await lS(rr(),"utf8")).split(`
890
+ `).filter(r=>r.trim());if(t.length<=cS)return;let n=`${rr()}.${process.pid}.tmp`;await uS(n,t.slice(-cS).join(`
887
891
  `)+`
888
- `,{mode:384}),await PS(n,Vn())}catch{}}async function US(){let e;try{e=(await DS(Vn(),"utf8")).split(`
889
- `).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 _f(i)||(n=!0,t.push(r))}try{let r=`${Vn()}.${process.pid}.tmp`;await MS(r,t.length>0?t.join(`
892
+ `,{mode:384}),await dS(n,rr())}catch{}}async function gS(){let e;try{e=(await lS(rr(),"utf8")).split(`
893
+ `).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 Pp(i)||(n=!0,t.push(r))}try{let r=`${rr()}.${process.pid}.tmp`;await uS(r,t.length>0?t.join(`
890
894
  `)+`
891
- `:"",{mode:384}),await PS(r,Vn())}catch{}}var OS,HS=_(()=>{"use strict";ie();zt();Ue();OS=256;o(FS,"aggregateWindow");o(Vn,"attestSpoolPath");o(_f,"postAttestation");o(jS,"spoolAttestation");o(LF,"capSpool");o(US,"flushAttestSpool")});function os(e=process.env,t=Ne()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Fa(e=process.env,t=Ne()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function BS(e,t=He()){let n={};try{let i=await X(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)+`
892
- `,384)}async function GS(e,t=He()){await BS({gateway_mode:e},t)}async function KS(e,t=He()){await BS({gateway_attest:e},t)}function WS(e=process.env,t=Ne()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var bf=_(()=>{"use strict";Ut();be();o(os,"resolveGatewayMode");o(Fa,"resolveGatewayAttest");o(BS,"writeGatewayConfigPatch");o(GS,"writeGatewayMode");o(KS,"writeGatewayAttest");o(WS,"resolveShaProofMode")});function zS(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"&&FF.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 jF(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function qS(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)jF(s,e,t)&&(i===null||VS[s.severity]>VS[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function JS(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 FF,VS,wf=_(()=>{"use strict";FF=new Set(["required","recommended","info"]);o(zS,"extractGatewayRules");VS={required:2,recommended:1,info:0};o(jF,"ruleMatches");o(qS,"decideToolCall");o(JS,"policyDenyText")});import{mkdirSync as UF,readFileSync as HF,renameSync as BF,writeFileSync as GF}from"node:fs";import{homedir as KF}from"node:os";import{dirname as WF,join as VF}from"node:path";function YS(){return VF(KF(),".maind","gateway","policy-cache.json")}function ja(e,t,n=new Date().toISOString()){try{let r={version:vf,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=YS();UF(WF(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;GF(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),BF(s,i)}catch{}}function Ua(e){try{let t=HF(YS(),"utf8"),n=JSON.parse(t);return n.version!==vf||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:vf,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var vf,kf=_(()=>{"use strict";vf=1;o(YS,"policyCachePath");o(ja,"writePolicyCache");o(Ua,"readPolicyCache")});function as(e=process.env){let t=e.MAIND_MCP_URL??Li,n=q();return{mcpUrl:t,keyFp:n?gr(n):"anon"}}async function Ha(e=6e3){let t=q();if(t===null)return null;let n=null;try{n=Y()}catch{n=null}let r=await pt("get_conventions",{},{apiKey:t,deviceId:re(),projectKey:n,bridgeVersion:G,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return zS(i)}var Sf=_(()=>{"use strict";Dt();ie();zt();ge();Ue();wf();o(as,"policyIdentity");o(Ha,"fetchGatewayRules")});function cs(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 zF(e){if(cs(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 qF(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:cs(e)?{action:"skip",reason:"already-wrapped"}:zF(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function XS(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 ZS(e){if(!cs(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 QS(e){return Object.entries(e).map(([t,n])=>{let r=qF(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var ex=_(()=>{"use strict";o(cs,"isGatewayWrapped");o(zF,"isMaindProxyEntry");o(qF,"classifyServer");o(XS,"wrapServerEntry");o(ZS,"unwrapServerEntry");o(QS,"planRewrites")});var ox={};ee(ox,{runGatewayInstall:()=>ej,runGatewayUninstall:()=>tj});import{existsSync as JF,readFileSync as YF}from"node:fs";import{homedir as XF}from"node:os";import{join as tx}from"node:path";import{createInterface as ZF}from"node:readline";function nx(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 rx(){return[{label:"Claude Code (project .mcp.json)",path:tx(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:tx(XF(),".claude.json")}]}async function ix(e){let t=ZF({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 sx(e){let t=QF(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 QF(e){try{return JF(e)?YF(e,"utf8"):null}catch{return null}}async function ej(e){let t=nx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
893
- `),2;let n=ye({entryPath:_e(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of rx()){let s=sx(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
894
- `);continue}let a=QS(s.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
895
- `);continue}if(!(t.yes||await ix(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
895
+ `:"",{mode:384}),await dS(r,rr())}catch{}}var cS,yS=v(()=>{"use strict";se();Qt();Ge();cS=256;s(mS,"aggregateWindow");s(rr,"attestSpoolPath");s(Pp,"postAttestation");s(hS,"spoolAttestation");s(qj,"capSpool");s(gS,"flushAttestSpool")});function bo(e=process.env,t=te()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function tc(e=process.env,t=te()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function _S(e,t=Ke()){let n={};try{let i=await X(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await z(t,JSON.stringify(r,null,2)+`
896
+ `,384)}async function bS(e,t=Ke()){await _S({gateway_mode:e},t)}async function vS(e,t=Ke()){await _S({gateway_attest:e},t)}function wS(e=process.env,t=te()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Mp=v(()=>{"use strict";We();xe();s(bo,"resolveGatewayMode");s(tc,"resolveGatewayAttest");s(_S,"writeGatewayConfigPatch");s(bS,"writeGatewayMode");s(vS,"writeGatewayAttest");s(wS,"resolveShaProofMode")});function xS(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,o=i.gateway_gate;if(typeof o!="object"||o===null)continue;let a=o;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"&&Jj.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function Yj(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function SS(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)Yj(o,e,t)&&(i===null||kS[o.severity]>kS[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function ES(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 Jj,kS,$p=v(()=>{"use strict";Jj=new Set(["required","recommended","info"]);s(xS,"extractGatewayRules");kS={required:2,recommended:1,info:0};s(Yj,"ruleMatches");s(SS,"decideToolCall");s(ES,"policyDenyText")});import{mkdirSync as Xj,readFileSync as Zj,renameSync as Qj,writeFileSync as e1}from"node:fs";import{homedir as t1}from"node:os";import{dirname as n1,join as r1}from"node:path";function TS(){return r1(t1(),".maind","gateway","policy-cache.json")}function nc(e,t,n=new Date().toISOString()){try{let r={version:Lp,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=TS();Xj(n1(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;e1(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),Qj(o,i)}catch{}}function rc(e){try{let t=Zj(TS(),"utf8"),n=JSON.parse(t);return n.version!==Lp||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Lp,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Lp,Fp=v(()=>{"use strict";Lp=1;s(TS,"policyCachePath");s(nc,"writePolicyCache");s(rc,"readPolicyCache")});function vo(e=process.env){let t=e.MAIND_MCP_URL??zi,n=J();return{mcpUrl:t,keyFp:n?Tr(n):"anon"}}async function ic(e=6e3){let t=J();if(t===null)return null;let n=null;try{n=Y()}catch{n=null}let r=await kt("get_conventions",{},{apiKey:t,deviceId:oe(),projectKey:n,bridgeVersion:K,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return xS(i)}var jp=v(()=>{"use strict";Bt();se();Qt();we();Ge();$p();s(vo,"policyIdentity");s(ic,"fetchGatewayRules")});function wo(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 i1(e){if(wo(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 o1(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:wo(e)?{action:"skip",reason:"already-wrapped"}:i1(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function RS(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],o=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=o||t.env?{...o??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function CS(e){if(!wo(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 AS(e){return Object.entries(e).map(([t,n])=>{let r=o1(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var IS=v(()=>{"use strict";s(wo,"isGatewayWrapped");s(i1,"isMaindProxyEntry");s(o1,"classifyServer");s(RS,"wrapServerEntry");s(CS,"unwrapServerEntry");s(AS,"planRewrites")});var $S={};Q($S,{runGatewayInstall:()=>u1,runGatewayUninstall:()=>p1});import{existsSync as s1,readFileSync as a1}from"node:fs";import{homedir as c1}from"node:os";import{join as NS}from"node:path";import{createInterface as l1}from"node:readline";function OS(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 DS(){return[{label:"Claude Code (project .mcp.json)",path:NS(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:NS(c1(),".claude.json")}]}async function PS(e){let t=l1({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 MS(e){let t=d1(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 d1(e){try{return s1(e)?a1(e,"utf8"):null}catch{return null}}async function u1(e){let t=OS(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
897
+ `),2;let n=ke({entryPath:he(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of DS()){let o=MS(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
898
+ `);continue}let a=AS(o.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
899
+ `);continue}if(!(t.yes||await PS(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
896
900
  Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
897
901
  The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
898
- `);continue}s.servers[c.key]=XS(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
899
- `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await z(i.path,JSON.stringify(s.raw,null,2)+`
902
+ `);continue}o.servers[c.key]=RS(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
903
+ `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await z(i.path,JSON.stringify(o.raw,null,2)+`
900
904
  `,384)}return process.stderr.write(r>0?`
901
905
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
902
906
  `:`
903
907
  Nothing to wrap.
904
- `),0}async function tj(e){let t=nx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
905
- `),2;let n=0;for(let r of rx()){let i=sx(r.path);if(i===null)continue;let s=!1;for(let[a,c]of Object.entries(i.servers)){if(!cs(c)||!(t.yes||await ix(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=ZS(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
906
- `);continue}i.servers[a]=d,s=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
907
- `)}!t.dryRun&&s&&await z(r.path,JSON.stringify(i.raw,null,2)+`
908
+ `),0}async function p1(e){let t=OS(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
909
+ `),2;let n=0;for(let r of DS()){let i=MS(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!wo(c)||!(t.yes||await PS(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=CS(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
910
+ `);continue}i.servers[a]=d,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
911
+ `)}!t.dryRun&&o&&await z(r.path,JSON.stringify(i.raw,null,2)+`
908
912
  `,384)}return process.stderr.write(n>0?`
909
913
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
910
914
  `:`
911
915
  Nothing wrapped \u2014 nothing to restore.
912
- `),0}var ax=_(()=>{"use strict";be();Mt();ex();o(nx,"parseFlags");o(rx,"targets");o(ix,"confirm");o(sx,"loadConfig");o(QF,"readFileSafeSync");o(ej,"runGatewayInstall");o(tj,"runGatewayUninstall")});var cx={};ee(cx,{runGatewayAttest:()=>rj,runGatewayMode:()=>nj,runGatewayPolicy:()=>oj});async function nj(e){let t=e[0];if(t===void 0){let n=os(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
916
+ `),0}var LS=v(()=>{"use strict";xe();Gt();IS();s(OS,"parseFlags");s(DS,"targets");s(PS,"confirm");s(MS,"loadConfig");s(d1,"readFileSafeSync");s(u1,"runGatewayInstall");s(p1,"runGatewayUninstall")});var FS={};Q(FS,{runGatewayAttest:()=>m1,runGatewayMode:()=>f1,runGatewayPolicy:()=>y1});async function f1(e){let t=e[0];if(t===void 0){let n=bo(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
913
917
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
914
- `),2):(await GS(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
918
+ `),2):(await bS(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
915
919
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
916
920
  `:`Convention policy is off; only explicit --deny-tool flags apply.
917
- `)),0)}async function rj(e){let t=e[0];if(t===void 0){let n=Fa(),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)":""}.
921
+ `)),0)}async function m1(e){let t=e[0];if(t===void 0){let n=tc(),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)":""}.
918
922
  `+(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.
919
923
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
920
- `),2):(await KS(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.
924
+ `),2):(await vS(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.
921
925
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
922
- `),0)}function ij(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
926
+ `),0)}function h1(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
923
927
  `;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})
924
- `}return t}function sj(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 oj(e){let t=e.includes("--refresh"),n=os(),r=as();if(t){let s=await Ha();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
925
- `):(ja(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
926
- `))}let i=Ua(r);return process.stdout.write(`maind: gateway mode '${n}'
928
+ `}return t}function g1(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 y1(e){let t=e.includes("--refresh"),n=bo(),r=vo();if(t){let o=await ic();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
929
+ `):(nc(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
930
+ `))}let i=rc(r);return process.stdout.write(`maind: gateway mode '${n}'
927
931
  `),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
928
- `),0):(process.stdout.write(`maind: policy from cache (${sj(i)}, ${r.mcpUrl}):
929
- `),process.stdout.write(ij(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.
930
- `),0)}var lx=_(()=>{"use strict";bf();kf();Sf();o(nj,"runGatewayMode");o(rj,"runGatewayAttest");o(ij,"renderRules");o(sj,"cacheAge");o(oj,"runGatewayPolicy")});var mx={};ee(mx,{gatewayEventsFile:()=>fx,parseGatewayArgs:()=>px,runGateway:()=>pj});import{spawn as aj}from"node:child_process";import{appendFile as cj,mkdir as lj}from"node:fs/promises";import{homedir as dx}from"node:os";import{basename as dj,join as ux}from"node:path";import{createInterface as uj}from"node:readline";function fx(){return ux(dx(),".maind","gateway","events.jsonl")}async function fj(e){try{let t=fx();await lj(ux(dx(),".maind","gateway"),{recursive:!0}),await cj(t,JSON.stringify(e)+`
931
- `,{mode:384})}catch{}}function px(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 pj(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:T,runGatewayUninstall:b}=await Promise.resolve().then(()=>(ax(),ox));return e[0]==="install"?T(e.slice(1)):b(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:T,runGatewayMode:b,runGatewayPolicy:S}=await Promise.resolve().then(()=>(lx(),cx));return e[0]==="mode"?b(e.slice(1)):e[0]==="attest"?T(e.slice(1)):S(e.slice(1))}let t=px(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
932
+ `),0):(process.stdout.write(`maind: policy from cache (${g1(i)}, ${r.mcpUrl}):
933
+ `),process.stdout.write(h1(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.
934
+ `),0)}var jS=v(()=>{"use strict";Mp();Fp();jp();s(f1,"runGatewayMode");s(m1,"runGatewayAttest");s(h1,"renderRules");s(g1,"cacheAge");s(y1,"runGatewayPolicy")});var KS={};Q(KS,{gatewayEventsFile:()=>BS,parseGatewayArgs:()=>GS,runGateway:()=>S1});import{spawn as _1}from"node:child_process";import{appendFile as b1,mkdir as v1}from"node:fs/promises";import{homedir as HS}from"node:os";import{basename as w1,join as US}from"node:path";import{createInterface as k1}from"node:readline";function BS(){return US(HS(),".maind","gateway","events.jsonl")}async function x1(e){try{let t=BS();await v1(US(HS(),".maind","gateway"),{recursive:!0}),await b1(t,JSON.stringify(e)+`
935
+ `,{mode:384})}catch{}}function GS(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let o=e[r+1];if(!o)return null;t.add(o),r+=2;continue}if(i==="--label"){let o=e[r+1];if(!o)return null;n=o,r+=2;continue}if(i==="--"){let o=e[r+1];return o?{denyTools:t,label:n,command:o,args:e.slice(r+2)}:null}return null}return null}async function S1(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:T,runGatewayUninstall:w}=await Promise.resolve().then(()=>(LS(),$S));return e[0]==="install"?T(e.slice(1)):w(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:T,runGatewayMode:w,runGatewayPolicy:x}=await Promise.resolve().then(()=>(jS(),FS));return e[0]==="mode"?w(e.slice(1)):e[0]==="attest"?T(e.slice(1)):x(e.slice(1))}let t=GS(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
932
936
  maind-mcp-bridge gateway install [--yes] [--dry-run]
933
937
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
934
938
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -938,59 +942,59 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
938
942
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
939
943
  install/uninstall rewrite Claude Code MCP configs (consent per server).
940
944
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
941
- `),2;let{denyTools:n,label:r,command:i,args:s}=t,a=r??dj(i),c=os(),l=WS(),d=l==="off"?null:ys(),u=c==="off"?[]:Ua(as())?.rules??[];c!=="off"&&Ha().then(T=>{T!==null&&(u=T,ja(as(),T))}).catch(()=>{});let f=[],p=Fa()&&q()!==null&&c!=="off",h=null;try{h=Y()}catch{h=null}let g=o(T=>{fj(T),p&&f.push(T)},"record"),y=o(async()=>{if(!p)return;let T=FS(f.splice(0),c,a,h);T!==null&&(await _f(T)||await jS(T))},"attestAndReset");p&&US().catch(()=>{});let w=setInterval(()=>{y()},30*6e4);w.unref();let v=aj(i,s,{stdio:["pipe","pipe","inherit"]});v.stdout.pipe(process.stdout),v.on("error",T=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(T)}
942
- `),process.exitCode=1});let k=uj({input:process.stdin,terminal:!1});k.on("line",T=>{let b=Xf(T);if(b.kind==="request"&&b.method==="tools/call"&&b.toolName){if(n.has(b.toolName)&&b.id!==void 0){process.stdout.write(qn(b.id,b.toolName)+`
943
- `),g(Ja("deny",a,b.toolName,Date.now()));return}let S=qS(b.toolName,a,u,c);if(S.kind==="deny"&&b.id!==void 0){process.stdout.write(qn(b.id,b.toolName,JS(b.toolName,S.rule))+`
944
- `),g(Ya("policy_deny",a,b.toolName,Date.now(),S.rule.conventionId,S.rule.conventionVersion));return}(S.kind==="warn"||S.kind==="deny")&&g(Ya("policy_warn",a,b.toolName,Date.now(),S.rule.conventionId,S.rule.conventionVersion));let N=_s(T,d);if(N.length>0){let M=N.find(F=>F.verdict==="fabricated");if(M!==void 0&&l==="enforce"&&c==="enforce"&&b.id!==void 0&&M!==void 0&&b.id!==void 0){process.stdout.write(qn(b.id,b.toolName,Jn(M,!0))+`
945
- `),g(Xa("sha_deny",a,b.toolName,Date.now()));return}let P=M??N[0];process.stderr.write(`[maind gateway] ${Jn(P,!1)}
946
- `),g(Xa("sha_warn",a,b.toolName,Date.now()))}g(Ja("tool_call",a,b.toolName,Date.now()))}v.stdin.write(T+`
947
- `)}),k.on("close",()=>{v.stdin.end()});let x=await new Promise(T=>{v.on("exit",(b,S)=>{T(b??(S?1:0))})});return clearInterval(w),await y(),x}var hx=_(()=>{"use strict";Za();HS();bf();wf();Qa();kf();Sf();ie();ge();o(fx,"gatewayEventsFile");o(fj,"logEvent");o(px,"parseGatewayArgs");o(pj,"runGateway")});var If={};ee(If,{MAX_ENTRIES:()=>xf,TTL_MS:()=>Rf,crossSessionDir:()=>Af,decideCrossSession:()=>_x,parseSessionDb:()=>yx,pruneDb:()=>Cf,runGuardCrossCheck:()=>kj,runGuardCrossObserve:()=>vj,staleReason:()=>Ef});import{mkdir as mj,readFile as hj,readdir as gj,stat as gx,unlink as yj,writeFile as _j}from"node:fs/promises";import{homedir as bj}from"node:os";import{join as Tf}from"node:path";function Af(){return Tf(bj(),".maind","cross-session")}function yx(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 Cf(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Rf);return n.length>xf&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-xf)),{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 Ef(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 bx(e){let t=Af();return await mj(t,{recursive:!0}),Tf(t,`${e}.json`)}async function wx(e,t){try{let n=await hj(await bx(e),"utf8");return Cf(yx(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function vx(e,t){try{await _j(await bx(e),JSON.stringify(t),{mode:384})}catch{}}async function wj(e){try{let t=Af();for(let n of await gj(t)){if(!n.endsWith(".json"))continue;let r=Tf(t,n),i=await gx(r).catch(()=>null);i&&e-i.mtimeMs>Rf&&await yj(r).catch(()=>{})}}catch{}}async function kx(e){try{return(await gx(e)).mtimeMs}catch{return}}async function vj(e,t=Date.now()){try{if(oe().mode==="off")return 0;let r=e??await K(),i=typeof r.session_id=="string"?r.session_id:"",s=Oe(r);if(!i||!s)return 0;let a=await kx(s);if(a===void 0)return 0;let c=await wx(i,t);return c.files[s]={m:a,t},delete c.warned[s],await vx(i,Cf(c,t)),await wj(t),0}catch{return 0}}async function kj(e,t=Date.now()){try{let n=oe();if(n.mode==="off")return 0;let r=e??await K(),i=typeof r.session_id=="string"?r.session_id:"",s=Oe(r);if(!i||!s)return 0;let a=await wx(i,t),c=_x(a.files[s]?.m,await kx(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Bn(Ef(s,c))+`
948
- `),await Z({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(Pe(Ef(s,c))+`
949
- `),a.warned[s]=c.current,await vx(i,a),await Z({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var Rf,xf,Nf=_(()=>{"use strict";pe();Jt();et();gt();Rf=48*3600*1e3,xf=500;o(Af,"crossSessionDir");o(yx,"parseSessionDb");o(Cf,"pruneDb");o(_x,"decideCrossSession");o(Ef,"staleReason");o(bx,"dbPath");o(wx,"loadDb");o(vx,"saveDb");o(wj,"sweepStaleSessionFiles");o(kx,"fileMtime");o(vj,"runGuardCrossObserve");o(kj,"runGuardCrossCheck")});var Of={};ee(Of,{INDEX_REFRESH_WORKER:()=>Sx,acquireLock:()=>ra,releaseLock:()=>Ui,runIndexRefreshWorker:()=>Aj,runOnIndexRefresh:()=>Rj});import{spawn as Sj}from"node:child_process";import{existsSync as xj}from"node:fs";import{join as Ej}from"node:path";function Tj(e){return Ej(e,".maind","code-index.sqlite")}async function Rj(){try{let e=await K(),t=we(typeof e.cwd=="string"?e.cwd:process.cwd());if(!xj(Tj(t))||!ra(t))return 0;let n=process.argv[1];if(n===void 0)return Ui(t),0;Sj(process.execPath,[n,Sx,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function Aj(){let e=process.argv[3]??we();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Bo(),Vd)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Ui(e)}return 0}var Sx,Df=_(()=>{"use strict";pe();Vt();eu();Sx="index-refresh-run";o(Tj,"indexDbPath");o(Rj,"runOnIndexRefresh");o(Aj,"runIndexRefreshWorker")});function Ka(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 Ba(e){return e.length<3||/^\d+$/.test(e)||xx.has(e)||xx.has(Ka(e))}function Nj(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function Oj(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function Tx(e){let t=new Set,n=new Set,r=[];for(let i of e.matchAll(Dj)){let s=i[0],a=s.toLowerCase();if(r.push(a),/[._-]/.test(s)){let c=Oj(a);c.length>=4&&!Ex.has(c)&&n.add(c)}for(let c of Nj(s)){let l=c.toLowerCase();Ba(l)||t.add(Ka(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]}`;Ex.has(s)||n.add(s)}return{words:t,compounds:n}}function Pj(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 Mf(e){if(!e)return[];let t=[];for(let n of e.split(`
950
- `)){let r=Mj.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 $j(e){let t=e.shortId.split("-"),n=new Set;for(let s of t)Ba(s)||n.add(Ka(s));let r=new Set;for(let s=0;s+1<t.length;s++)!Ba(t[s])&&!Ba(t[s+1])&&r.add(`${t[s]}-${t[s+1]}`);let i=Tx(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 Ax(e,t,n=3,r=[]){if(t.length===0)return[];let i=new Set([...r].map(p=>Ka(p.toLowerCase()))),s=t.map($j),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=Tx(Pj(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 w=[...h].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),v=h.size>=1&&h.size+g.size>=2&&y>=Lj;!w&&!v||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 Uj(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function Cx(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("/")||Fj.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!Uj(u))return;let f=u.split("."),p=f[f.length-1];p.length<(l||d?3:4)||jj.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 Pf(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Nx(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 Ga(t-Ix);if(!i.tryAdd(`${Cj} 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}): ${Pf(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 w=y.qualifiedName===u.candidate.name?y.kind:`${y.kind} ${y.qualifiedName}`;return`${y.filePath}:${y.startLine} (${w})${y.signature?` '${Pf(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+=`
951
- (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:s,symbolNames:a}}function Bj(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>Hj}function Gj(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 Kj(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function Ox(e,t=1500){let n=new Map;for(let g of e.callers){let y=n.get(g.calleeKey)??[];y.some(w=>w.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=Bj(e.range,s)&&a.length>0;if(i.length===0&&e.importers.length===0&&!c)return null;let l=Gj([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new Ga(t-Ix),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${Ij} ${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 v of a){let k=`${v.qualifiedName} L${v.startLine}`,x=g.length===0?k:`${g} \xB7 ${k}`;if(x.length>500)break;g=x,y++}let w=a.length-y;d.tryAdd(w>0?`${g} \xB7 +${w} 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)??[],w=y.slice(0,3).map(T=>`${Kj(T.caller,l)}${T.kind==="calls"?"":` [${T.kind}]`}`),v=y.length-w.length,k=g.signature?` '${Pf(g.signature,80)}'`:"",x=`- ${g.qualifiedName} L${g.startLine}${k} \u2190 ${w.join(", ")}${v>0?` +${v} more`:""}`;if(!d.tryAdd(x)){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,w=e.importers.length,v=`Imported by ${w} file${w===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(v)||(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+=`
952
- (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),h}var Cj,Ij,xx,Ex,Dj,Mj,Lj,Fj,jj,Ga,Ix,Hj,Dx=_(()=>{"use strict";Cj="[maind context \xB7 prompt]",Ij="[maind context \xB7 read]",xx=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+/)),Ex=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);o(Ka,"stem");o(Ba,"isNoise");o(Nj,"splitParts");o(Oj,"normalizeCompound");Dj=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;o(Tx,"termsOf");o(Pj,"promptForMatching");o(Rx,"repoNameWords");Mj=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;o(Mf,"parseConventionLines");o($j,"profileOf");Lj=4.5;o(Ax,"matchConventions");Fj=/\.(?: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,jj=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(Uj,"looksLikeCode");o(Cx,"extractSymbolCandidates");o(Pf,"clip");Ga=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(`
953
- `)}},Ix=90;o(Nx,"renderPromptContext");Hj=2e3;o(Bj,"isPartialRead");o(Gj,"commonDir");o(Kj,"callerLabel");o(Ox,"renderReadContext")});import{createHash as Wj}from"node:crypto";import{existsSync as Px,mkdirSync as Vj,readdirSync as zj,rmSync as qj,statSync as Jj,writeFileSync as Yj}from"node:fs";import{join as Wa}from"node:path";function $f(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function Qj(e,t,n=null,r=Zj){try{for(let i of zj(e)){let s=Wa(e,i);if(s!==n)try{t-Jj(s).mtimeMs>r&&qj(s,{recursive:!0,force:!0})}catch{}}}catch{}}var Xj,Zj,ls,Mx=_(()=>{"use strict";De();Xj=Wa(ke,"context"),Zj=7*24*60*60*1e3;o($f,"safe");ls=class e{constructor(t,n){this.root=t;this.dir=n}static{o(this,"SeenMarks")}static forScope(t,n,r=Xj){let i=n?`${$f(t)}__${$f(n)}`:$f(t);return new e(r,Wa(r,i))}fileFor(t){return Wa(this.dir,Wj("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return Px(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{Px(this.dir)||(Vj(this.dir,{recursive:!0,mode:448}),Qj(this.root,n,this.dir));for(let r of t)try{Yj(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};o(Qj,"sweepStaleScopes")});var jf={};ee(jf,{INDEX_RELPATH:()=>Ht,SOFT_BUDGET_MS:()=>Fx,findRepoRoot:()=>Bt,isMachinePrompt:()=>Bx,loadCachedConventions:()=>Ux,promptContextFor:()=>Kx,promptTextOf:()=>Hx,readContextFor:()=>Wx,runOnPromptContext:()=>c1,runOnReadContext:()=>d1});import{existsSync as $x,readFileSync as e1,realpathSync as t1,statSync as n1}from"node:fs";import{dirname as r1,isAbsolute as Lx,join as ds,relative as i1,sep as s1}from"node:path";function o1(e,t){let n=i1(e,t);return!n||n.startsWith("..")||Lx(n)?null:n.split(s1).join("/")}function Ff(e){try{let t=n1(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function jx(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Bo(),Vd));return t(e)}function Ux(e,t={}){try{let n=t.identity===void 0?ss():t.identity;if(e!==null&&n!==null){let r=co(e,n),i=qo(r?.result.instructions??null),s=Mf(i);if(s.length>0)return s}}catch{}try{let n=JSON.parse(e1(t.briefingCacheFile??Pr,"utf8"));if(typeof n.conventions=="string")return Mf(n.conventions)}catch{}return[]}function Hx(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function Bx(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 Gx(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 a1(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,Lf)),c=new Set;for(let[d,u]of a){let f=Ff(ds(t,d));f!==null&&Ei(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 Kx(e,t={}){let n=t.now??Date.now,r=n();if(ji(e,t.env??process.env))return null;let i=Hx(e);if(i.trim().length===0||Bx(e,i))return null;let s=Gx(e);if(s===null)return null;let a=ls.forScope(s.sessionId,s.agentId,t.seenRoot),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=Bt(c),d=Ax(i,(t.loadConventions??Ux)(l),6,Rx(l)).filter(y=>!a.has(`conv:${y.convention.id}@${y.convention.version}`)).slice(0,3),u=Cx(i).filter(y=>!a.has(`sym:${l??""}:${y.name}`)),f=l===null?null:ds(l,Ht),p=u.length>0&&f!==null&&l!==null&&$x(f)&&n()-r<Fx?await a1(u,l,f,t.openReader??jx):[],h=Nx({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 c1(){try{let e=await Kx(await K());e!==null&&process.stdout.write(hk(e))}catch{}return 0}function l1(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 Wx(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read"||ji(e,t.env??process.env))return null;let r=Oe(e);if(!r||ar(r)===null||ci(r))return null;let i=Gx(e);if(i===null)return null;let s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=Lx(r)?r:ds(s,r),c;try{c=t1(a)}catch{return null}let l=Bt(r1(c));if(l===null)return null;let d=ds(l,Ht);if(!$x(d))return null;let u=o1(l,c);if(u===null)return null;let f=await(t.openReader??jx)(d);try{let p=f.meta();if(!p.schemaCurrent)return null;let h=f.file(u);if(h===null)return null;let g=Ff(c);if(g===null||!Ei(h,g))return null;let y=ls.forScope(i.sessionId,i.agentId,t.seenRoot),w=`read:${l}:${u}@${h.contentHash}`;if(y.has(w))return null;let v=f.symbolsInFile(u),k=p.edgesDirty?[]:f.callersOfFile(u),x=p.edgesDirty?[]:f.importersOf(u),T=[...new Set([...k.map(J=>J.caller.filePath),...x])],b=T.slice(0,Lf),S=new Set(T.slice(Lf)),N=f.files(b),M=new Set;for(let J of b){let Se=N.get(J),zn=Se===void 0?null:Ff(ds(l,J));Se!==void 0&&zn!==null&&Ei(Se,zn)&&M.add(J)}let B=o(J=>k.filter(Se=>J.has(Se.caller.filePath)).length+x.filter(Se=>J.has(Se)).length,"countIn"),P=k.filter(J=>M.has(J.caller.filePath)).map(J=>({calleeKey:J.calleeKey,kind:J.kind,caller:{nodeKey:J.caller.nodeKey,kind:J.caller.kind,qualifiedName:J.caller.qualifiedName,filePath:J.caller.filePath,startLine:J.caller.startLine}})),F=x.filter(J=>M.has(J)),W=B(S),_t=k.length-P.length+(x.length-F.length)-W,Yr=Ox({relPath:u,symbols:v,callers:P,importers:F,hidden:_t,unchecked:W,range:l1(e)});return Yr===null?null:(y.mark([w],n()),Yr)}finally{f.close()}}async function d1(){try{let e=await Wx(await K());e!==null&&process.stdout.write(Pe(e))}catch{}return 0}var Fx,Lf,Uf=_(()=>{"use strict";Ot();Yo();Mn();Jr();Dt();Dx();Mx();Ao();pe();Jt();Fx=200,Lf=200;o(o1,"repoRelative");o(Ff,"diskStat");o(jx,"openReader");o(Ux,"loadCachedConventions");o(Hx,"promptTextOf");o(Bx,"isMachinePrompt");o(Gx,"scopeOf");o(a1,"locateSymbols");o(Kx,"promptContextFor");o(c1,"runOnPromptContext");o(l1,"readRangeOf");o(Wx,"readContextFor");o(d1,"runOnReadContext")});import{randomUUID as u1}from"node:crypto";Xr();import{createInterface as $C}from"node:readline";var aE=[["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 cE(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of aE)if(t.includes(n))return r;return null}o(cE,"mapClientInfoNameToFamily");function qf(e){let t;try{t=JSON.parse(e)}catch{return null}if(!za(t)||t.method!=="initialize")return null;let n=t.params;if(!za(n))return null;let r=n.clientInfo;if(!za(r))return null;let i=r.name,s=cE(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(qf,"tryExtractInitializeClient");function za(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(za,"isRecord");import{fileURLToPath as lE}from"node:url";var qa="maind-bridge-",dE=8,Jf=8e3;function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(bt,"isRecord");function uE(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!bt(t)||t.method!=="initialize"||!bt(t.params))return!1;let n=t.params.capabilities;return bt(n)&&bt(n.roots)}catch{return!1}}o(uE,"clientDeclaresRoots");function fE(e){if(!e.includes("notifications/initialized"))return!1;try{let t=JSON.parse(e);return t.method==="notifications/initialized"&&t.id===void 0}catch{return!1}}o(fE,"isInitializedNotification");function pE(e){if(!bt(e)||!bt(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!bt(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let i;try{i=lE(r.uri)}catch{continue}if(n.includes(i)||n.push(i),n.length>=dE)break}return n}o(pE,"rootPathsFrom");var gs=class{constructor(t,n=!1){this.writeLine=t;this.initialized=n}static{o(this,"ClientRequestChannel")}initialized;closed=!1;waiters=[];pending=new Map;seq=0;observe(t){if(t.includes(qa)){let n;try{n=JSON.parse(t)}catch{n=null}if(bt(n)&&typeof n.id=="string"&&n.id.startsWith(qa)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&fE(t)){this.initialized=!0;for(let n of this.waiters.splice(0))n(!0)}return!1}close(){if(!this.closed){this.closed=!0;for(let t of this.waiters.splice(0))t(!1);for(let t of[...this.pending.values()])t.settle(null)}}async request(t,n=Jf){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(c=>{let l=o(u=>{clearTimeout(d),this.waiters=this.waiters.filter(f=>f!==l),c(u)},"done"),d=setTimeout(()=>l(!1),n);this.waiters.push(l)})||this.closed))return null;let i=`${qa}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,s=new Promise(a=>{let c=o(d=>{clearTimeout(l),this.pending.delete(i),a(d)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(i,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:i,method:t})),s}};async function Yf(e,t,n=Jf){return uE(e)?pE(await t.request("roots/list",n)):null}o(Yf,"listClientRoots");Za();Qa();function ec(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(`
954
- `).trim();if(r=[],s.length!==0)try{n.push(JSON.parse(s))}catch{}},"flush");for(let s of t.split(`
955
- `)){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(ec,"rpcMessagesOf");function rp(e,t){for(let n of ec(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");Dt();var LC="https://mcp.maind.dev/mcp",Ti=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{o(this,"BridgeReauthNeeded")}},fo=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;clientChannel;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=gr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=FC(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=jC(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.clientChannel=new gs(a=>process.stdout.write(a+`
956
- `),s!==null&&s.initFrame!==null&&(s.pendingFrame===null||!yr(s.pendingFrame))),this.shaRepoRoot=ys(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??LC}async run(t=ad()){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){this.clientChannel.close();return}let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}listClientRoots(t){return Yf(this.initFrame,this.clientChannel,t)}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!n&&this.clientChannel.observe(t))return;if(!this.clientFamilyLocked&&this.clientFamily===null){let u=qf(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&yr(t)&&(this.initFrame=t);let r=BC(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=_s(t,this.shaRepoRoot);if(u.length>0){let f=u.find(h=>h.verdict==="fabricated"),p=f??u[0];if(f!==void 0&&tp(f)&&r.id!==null){let h=Jn(f,!0);process.stderr.write(`[maind] ${h}
957
- `);let g=r.params?.name;process.stdout.write(qn(r.id,typeof g=="string"?g:"unknown",h)+`
958
- `);return}i=Jn(p,!1),process.stderr.write(`[maind] ${i}
959
- `)}if(this.assignedInbox&&!zf(this.clientFamily)){let f=this.assignedInbox.takeNote();f!==null&&(i=i===null?f:`${i}
960
- [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+`
961
- `);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!yr(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=lo(t);if(this.serveInitializeFromCache(t,f))return;uo(f,-32603,`bridge network error: ${Ky(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&&!yr(t)){let u=await c.text().catch(()=>"");if(Gy(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let f=lo(t);uo(f,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=lo(t),f=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;uo(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 sd(c):await c.text(),f=this.localRouter.augmentToolsList(u);f.trim().length>0&&process.stdout.write(f+`
962
- `);return}if(yr(t)){let u=d.startsWith("text/event-stream")?await sd(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
963
- `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await sd(c):await c.text(),f=HC(u,i);f.trim().length>0&&process.stdout.write(f+`
964
- `);return}if(d.startsWith("text/event-stream"))await UC(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
965
- `)}}}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 Ti(KC(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=lo(n);uo(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 WC(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&&Gy(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:Ky(a),timedOut:GC(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=ft()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Hy(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!yr(t))return!1;let r=co(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(By(n,r)+`
966
- `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ao(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function ad(){return $C({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}o(ad,"stdinLines");function FC(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(FC,"normalizeClientFamily");function jC(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}o(jC,"normalizeClientVersion");async function UC(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(`
945
+ `),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??w1(i),c=bo(),l=wS(),d=l==="off"?null:Oo(),u=c==="off"?[]:rc(vo())?.rules??[];c!=="off"&&ic().then(T=>{T!==null&&(u=T,nc(vo(),T))}).catch(()=>{});let p=[],f=tc()&&J()!==null&&c!=="off",m=null;try{m=Y()}catch{m=null}let g=s(T=>{x1(T),f&&p.push(T)},"record"),y=s(async()=>{if(!f)return;let T=mS(p.splice(0),c,a,m);T!==null&&(await Pp(T)||await hS(T))},"attestAndReset");f&&gS().catch(()=>{});let _=setInterval(()=>{y()},30*6e4);_.unref();let b=_1(i,o,{stdio:["pipe","pipe","inherit"]});b.stdout.pipe(process.stdout),b.on("error",T=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(T)}
946
+ `),process.exitCode=1});let k=k1({input:process.stdin,terminal:!1});k.on("line",T=>{let w=mf(T);if(w.kind==="request"&&w.method==="tools/call"&&w.toolName){if(n.has(w.toolName)&&w.id!==void 0){process.stdout.write(ir(w.id,w.toolName)+`
947
+ `),g(pc("deny",a,w.toolName,Date.now()));return}let x=SS(w.toolName,a,u,c);if(x.kind==="deny"&&w.id!==void 0){process.stdout.write(ir(w.id,w.toolName,ES(w.toolName,x.rule))+`
948
+ `),g(fc("policy_deny",a,w.toolName,Date.now(),x.rule.conventionId,x.rule.conventionVersion));return}(x.kind==="warn"||x.kind==="deny")&&g(fc("policy_warn",a,w.toolName,Date.now(),x.rule.conventionId,x.rule.conventionVersion));let N=Do(T,d);if(N.length>0){let L=N.find(j=>j.verdict==="fabricated");if(L!==void 0&&l==="enforce"&&c==="enforce"&&w.id!==void 0&&L!==void 0&&w.id!==void 0){process.stdout.write(ir(w.id,w.toolName,or(L,!0))+`
949
+ `),g(mc("sha_deny",a,w.toolName,Date.now()));return}let P=L??N[0];process.stderr.write(`[maind gateway] ${or(P,!1)}
950
+ `),g(mc("sha_warn",a,w.toolName,Date.now()))}g(pc("tool_call",a,w.toolName,Date.now()))}b.stdin.write(T+`
951
+ `)}),k.on("close",()=>{b.stdin.end()});let S=await new Promise(T=>{b.on("exit",(w,x)=>{T(w??(x?1:0))})});return clearInterval(_),await y(),S}var WS=v(()=>{"use strict";hc();yS();Mp();$p();gc();Fp();jp();se();we();s(BS,"gatewayEventsFile");s(x1,"logEvent");s(GS,"parseGatewayArgs");s(S1,"runGateway")});var Vp={};Q(Vp,{MAX_ENTRIES:()=>Hp,TTL_MS:()=>Gp,crossSessionDir:()=>Kp,decideCrossSession:()=>qS,parseSessionDb:()=>zS,pruneDb:()=>Wp,runGuardCrossCheck:()=>D1,runGuardCrossObserve:()=>O1,staleReason:()=>Up});import{mkdir as E1,readFile as T1,readdir as R1,stat as VS,unlink as C1,writeFile as A1}from"node:fs/promises";import{homedir as I1}from"node:os";import{join as Bp}from"node:path";function Kp(){return Bp(I1(),".maind","cross-session")}function zS(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[o,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[o]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[o,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[o]=a);return{files:r,warned:i}}function Wp(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Gp);return n.length>Hp&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-Hp)),{files:Object.fromEntries(n),warned:e.warned}}function qS(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Up(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 JS(e){let t=Kp();return await E1(t,{recursive:!0}),Bp(t,`${e}.json`)}async function YS(e,t){try{let n=await T1(await JS(e),"utf8");return Wp(zS(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function XS(e,t){try{await A1(await JS(e),JSON.stringify(t),{mode:384})}catch{}}async function N1(e){try{let t=Kp();for(let n of await R1(t)){if(!n.endsWith(".json"))continue;let r=Bp(t,n),i=await VS(r).catch(()=>null);i&&e-i.mtimeMs>Gp&&await C1(r).catch(()=>{})}}catch{}}async function ZS(e){try{return(await VS(e)).mtimeMs}catch{return}}async function O1(e,t=Date.now()){try{if(le().mode==="off")return 0;let r=e??await G();if(Ve(r))return 0;let i=typeof r.session_id=="string"?r.session_id:"",o=Me(r);if(!i||!o)return 0;let a=await ZS(o);if(a===void 0)return 0;let c=await YS(i,t);return c.files[o]={m:a,t},delete c.warned[o],await XS(i,Wp(c,t)),await N1(t),0}catch{return 0}}async function D1(e,t=Date.now()){try{let n=le();if(n.mode==="off")return 0;let r=e??await G();if(Ve(r))return 0;let i=typeof r.session_id=="string"?r.session_id:"",o=Me(r);if(!i||!o)return 0;let a=await YS(i,t),c=qS(a.files[o]?.m,await ZS(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Un(Up(o,c))+`
952
+ `),await Z({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o}),0):(a.warned[o]===c.current||(process.stdout.write(Bn(Up(o,c))+`
953
+ `),a.warned[o]=c.current,await XS(i,a),await Z({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var Gp,Hp,zp=v(()=>{"use strict";ge();Re();Ji();ct();Et();Gp=48*3600*1e3,Hp=500;s(Kp,"crossSessionDir");s(zS,"parseSessionDb");s(Wp,"pruneDb");s(qS,"decideCrossSession");s(Up,"staleReason");s(JS,"dbPath");s(YS,"loadDb");s(XS,"saveDb");s(N1,"sweepStaleSessionFiles");s(ZS,"fileMtime");s(O1,"runGuardCrossObserve");s(D1,"runGuardCrossCheck")});var qp={};Q(qp,{INDEX_REFRESH_WORKER:()=>QS,acquireLock:()=>wa,releaseLock:()=>Zi,runIndexRefreshWorker:()=>j1,runOnIndexRefresh:()=>F1});import{spawn as P1}from"node:child_process";import{existsSync as M1}from"node:fs";import{join as $1}from"node:path";function L1(e){return $1(e,".maind","code-index.sqlite")}async function F1(){try{let e=await G(),t=Se(typeof e.cwd=="string"?e.cwd:process.cwd());if(!M1(L1(t))||!wa(t))return 0;let n=process.argv[1];if(n===void 0)return Zi(t),0;P1(process.execPath,[n,QS,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function j1(){let e=process.argv[3]??Se();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(ra(),su)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Zi(e)}return 0}var QS,Jp=v(()=>{"use strict";ge();Zt();hu();QS="index-refresh-run";s(L1,"indexDbPath");s(F1,"runOnIndexRefresh");s(j1,"runIndexRefreshWorker")});function ac(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 oc(e){return e.length<3||/^\d+$/.test(e)||eE.has(e)||eE.has(ac(e))}function B1(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function G1(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function nE(e){let t=new Set,n=new Set,r=[];for(let i of e.matchAll(K1)){let o=i[0],a=o.toLowerCase();if(r.push(a),/[._-]/.test(o)){let c=G1(a);c.length>=4&&!tE.has(c)&&n.add(c)}for(let c of B1(o)){let l=c.toLowerCase();oc(l)||t.add(ac(l))}}for(let i=0;i+1<r.length;i++){if(/[._-]/.test(r[i])||/[._-]/.test(r[i+1]))continue;let o=`${r[i]}-${r[i+1]}`;tE.has(o)||n.add(o)}return{words:t,compounds:n}}function W1(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 rE(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function Xp(e){if(!e)return[];let t=[];for(let n of e.split(`
954
+ `)){let r=V1.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 z1(e){let t=e.shortId.split("-"),n=new Set;for(let o of t)oc(o)||n.add(ac(o));let r=new Set;for(let o=0;o+1<t.length;o++)!oc(t[o])&&!oc(t[o+1])&&r.add(`${t[o]}-${t[o+1]}`);let i=nE(e.summary);for(let o of i.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(o)&&r.add(o);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:i.words}}function iE(e,t,n=3,r=[]){if(t.length===0)return[];let i=new Set([...r].map(f=>ac(f.toLowerCase()))),o=t.map(z1),a=new Map,c=new Map;for(let f of o){let m=new Set([...f.keyWords,...f.keyCompounds]);for(let g of m)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...m,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=o.length,d=s(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=nE(W1(e));for(let f of i)u.words.delete(f);let p=[];for(let f of o){let m=new Set;for(let k of u.words)f.keyWords.has(k)&&m.add(k);for(let k of u.compounds)f.keyCompounds.has(k)&&m.add(k);let g=new Set;for(let k of u.words)!m.has(k)&&f.summaryWords.has(k)&&g.add(k);if(m.size===0&&g.size===0)continue;let y=0;for(let k of m)y+=2*d(k);for(let k of g)y+=d(k);let _=[...m].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),b=m.size>=1&&m.size+g.size>=2&&y>=q1;!_&&!b||p.push({convention:f.convention,score:y,matched:[...m,...g]})}return p.sort((f,m)=>m.score-f.score||f.convention.id.localeCompare(m.convention.id)).slice(0,n)}function X1(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function oE(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],i=new Set,o=s((c,l)=>{if(r.length>=t)return;let d=c.endsWith("()"),u=d?c.slice(0,-2):c;if(u.includes("/")||J1.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!X1(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||Y1.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))o(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))o(c[1],!1);return r}function Yp(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function aE(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 sc(t-sE);if(!i.tryAdd(`${H1} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let o=[],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}): ${Yp(d.convention.summary,320)}`;if(!i.tryAdd(u)){c=!0;break}o.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 _=y.qualifiedName===u.candidate.name?y.kind:`${y.kind} ${y.qualifiedName}`;return`${y.filePath}:${y.startLine} (${_})${y.signature?` '${Yp(y.signature,70)}'`:""}`}).join("; "),m=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${m>0?` (+${m} more \u2014 codebase_search)`:""}`;if(!i.tryAdd(g)){c=!0;break}a.push(u.candidate.name)}}if(o.length===0&&a.length===0)return null;let l=i.toString();return c&&(l+=`
955
+ (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:o,symbolNames:a}}function Q1(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>Z1}function eH(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 tH(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function cE(e,t=1500){let n=new Map;for(let g of e.callers){let y=n.get(g.calleeKey)??[];y.some(_=>_.caller.nodeKey===g.caller.nodeKey)||y.push(g),n.set(g.calleeKey,y)}let r=s(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),o=e.symbols.reduce((g,y)=>Math.max(g,y.endLine),0),a=e.symbols.filter(g=>!g.qualifiedName.includes(".")&&g.kind!=="module"),c=Q1(e.range,o)&&a.length>0;if(i.length===0&&e.importers.length===0&&!c)return null;let l=eH([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new sc(t-sE),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${U1} ${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 b of a){let k=`${b.qualifiedName} L${b.startLine}`,S=g.length===0?k:`${g} \xB7 ${k}`;if(S.length>500)break;g=S,y++}let _=a.length-y;d.tryAdd(_>0?`${g} \xB7 +${_} 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)??[],_=y.slice(0,3).map(T=>`${tH(T.caller,l)}${T.kind==="calls"?"":` [${T.kind}]`}`),b=y.length-_.length,k=g.signature?` '${Yp(g.signature,80)}'`:"",S=`- ${g.qualifiedName} L${g.startLine}${k} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!d.tryAdd(S)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(k=>k.slice(l.length)),y=e.importers.length-g.length,_=e.importers.length,b=`Imported by ${_} file${_===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(b)||(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 m=d.toString();return p&&(m+=`
956
+ (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var H1,U1,eE,tE,K1,V1,q1,J1,Y1,sc,sE,Z1,lE=v(()=>{"use strict";H1="[maind context \xB7 prompt]",U1="[maind context \xB7 read]",eE=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+/)),tE=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(ac,"stem");s(oc,"isNoise");s(B1,"splitParts");s(G1,"normalizeCompound");K1=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(nE,"termsOf");s(W1,"promptForMatching");s(rE,"repoNameWords");V1=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(Xp,"parseConventionLines");s(z1,"profileOf");q1=4.5;s(iE,"matchConventions");J1=/\.(?: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,Y1=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()));s(X1,"looksLikeCode");s(oE,"extractSymbolCandidates");s(Yp,"clip");sc=class{constructor(t){this.budget=t}static{s(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(`
957
+ `)}},sE=90;s(aE,"renderPromptContext");Z1=2e3;s(Q1,"isPartialRead");s(eH,"commonDir");s(tH,"callerLabel");s(cE,"renderReadContext")});import{createHash as nH}from"node:crypto";import{existsSync as dE,mkdirSync as rH,readdirSync as iH,rmSync as oH,statSync as sH,writeFileSync as aH}from"node:fs";import{join as cc}from"node:path";function Zp(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function dH(e,t,n=null,r=lH){try{for(let i of iH(e)){let o=cc(e,i);if(o!==n)try{t-sH(o).mtimeMs>r&&oH(o,{recursive:!0,force:!0})}catch{}}}catch{}}var cH,lH,ko,uE=v(()=>{"use strict";$e();cH=cc(Ce,"context"),lH=7*24*60*60*1e3;s(Zp,"safe");ko=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=cH){let i=n?`${Zp(t)}__${Zp(n)}`:Zp(t);return new e(r,cc(r,i))}fileFor(t){return cc(this.dir,nH("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return dE(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{dE(this.dir)||(rH(this.dir,{recursive:!0,mode:448}),dH(this.root,n,this.dir));for(let r of t)try{aH(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(dH,"sweepStaleScopes")});var tf={};Q(tf,{INDEX_RELPATH:()=>zt,SOFT_BUDGET_MS:()=>mE,findRepoRoot:()=>qt,isMachinePrompt:()=>_E,loadCachedConventions:()=>gE,promptContextFor:()=>vE,promptTextOf:()=>yE,readContextFor:()=>wE,runOnPromptContext:()=>bH,runOnReadContext:()=>wH});import{existsSync as pE,readFileSync as uH,realpathSync as pH,statSync as fH}from"node:fs";import{dirname as mH,isAbsolute as fE,join as xo,relative as hH,sep as gH}from"node:path";function yH(e,t){let n=hH(e,t);return!n||n.startsWith("..")||fE(n)?null:n.split(gH).join("/")}function ef(e){try{let t=fH(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function hE(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(ra(),su));return t(e)}function gE(e,t={}){try{let n=t.identity===void 0?_o():t.identity;if(e!==null&&n!==null){let r=xs(e,n),i=pa(r?.result.instructions??null),o=Xp(i);if(o.length>0)return o}}catch{}try{let n=JSON.parse(uH(t.briefingCacheFile??Kr,"utf8"));if(typeof n.conventions=="string")return Xp(n.conventions)}catch{}return[]}function yE(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function _E(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 bE(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 _H(e,t,n,r){let i;try{i=await r(n)}catch{return[]}try{if(!i.meta().schemaCurrent)return[];let o=i.symbolsNamed(e.map(d=>d.name)),a=i.files([...o.values()].flat().map(d=>d.filePath).slice(0,Qp)),c=new Set;for(let[d,u]of a){let p=ef(xo(t,d));p!==null&&Pi(u,p)&&c.add(d)}let l=[];for(let d of e){let u=o.get(d.name)??[],p=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),f=p.length>0?p:u,m=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));m.length>0&&l.push({candidate:d,locations:m,total:f.length})}return l}catch{return[]}finally{try{i.close()}catch{}}}async function vE(e,t={}){let n=t.now??Date.now,r=n(),i=t.env??process.env,o=re(e,i,t.readConfig??te);if(!ye(o,{kind:"context",event:"UserPromptSubmit"}))return null;let a=yE(e);if(a.trim().length===0||_E(e,a))return null;let c=bE(e);if(c===null)return null;let l=ko.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:ca(o,i)??process.cwd(),u=qt(d),p=iE(a,(t.loadConventions??gE)(u),6,rE(u)).filter(b=>!l.has(`conv:${b.convention.id}@${b.convention.version}`)).slice(0,3),f=oE(a).filter(b=>!l.has(`sym:${u??""}:${b.name}`)),m=u===null?null:xo(u,zt),g=f.length>0&&m!==null&&u!==null&&pE(m)&&n()-r<mE?await _H(f,u,m,t.openReader??hE):[],y=aE({repoRoot:u,conventions:p,symbols:g});if(y===null)return null;let _=new Map(p.map(b=>[b.convention.id,b.convention.version]));return l.mark([...y.conventionIds.map(b=>`conv:${b}@${_.get(b)??0}`),...y.symbolNames.map(b=>`sym:${u??""}:${b}`)],n()),y.text}async function bH(){try{let e=await G(),t=await vE(e);if(t!==null){let n=ce(re(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function vH(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 wE(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=re(e,t.env??process.env,t.readConfig??te);if(!ye(r,{kind:"context",event:"PreToolUse"}))return null;let i=Me(e);if(!i||yr(i)===null||yi(i))return null;let o=bE(e);if(o===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=fE(i)?i:xo(a,i),l;try{l=pH(c)}catch{return null}let d=qt(mH(l));if(d===null)return null;let u=xo(d,zt);if(!pE(u))return null;let p=yH(d,l);if(p===null)return null;let f=await(t.openReader??hE)(u);try{let m=f.meta();if(!m.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=ef(l);if(y===null||!Pi(g,y))return null;let _=ko.forScope(o.sessionId,o.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let k=f.symbolsInFile(p),S=m.edgesDirty?[]:f.callersOfFile(p),T=m.edgesDirty?[]:f.importersOf(p),w=[...new Set([...S.map(q=>q.caller.filePath),...T])],x=w.slice(0,Qp),N=new Set(w.slice(Qp)),L=f.files(x),B=new Set;for(let q of x){let Le=L.get(q),Eo=Le===void 0?null:ef(xo(d,q));Le!==void 0&&Eo!==null&&Pi(Le,Eo)&&B.add(q)}let P=s(q=>S.filter(Le=>q.has(Le.caller.filePath)).length+T.filter(Le=>q.has(Le)).length,"countIn"),j=S.filter(q=>B.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}})),W=T.filter(q=>B.has(q)),ut=P(N),So=S.length-j.length+(T.length-W.length)-ut,oi=cE({relPath:p,symbols:k,callers:j,importers:W,hidden:So,unchecked:ut,range:vH(e)});return oi===null?null:(_.mark([b],n()),oi)}finally{f.close()}}async function wH(){try{let e=await G(),t=await wE(e);if(t!==null){let n=ce(re(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var mE,Qp,nf=v(()=>{"use strict";Ut();We();ma();Vn();ii();Bt();lE();uE();Gs();ge();Re();mE=200,Qp=200;s(yH,"repoRelative");s(ef,"diskStat");s(hE,"openReader");s(gE,"loadCachedConventions");s(yE,"promptTextOf");s(_E,"isMachinePrompt");s(bE,"scopeOf");s(_H,"locateSymbols");s(vE,"promptContextFor");s(bH,"runOnPromptContext");s(vH,"readRangeOf");s(wE,"readContextFor");s(wH,"runOnReadContext")});import{randomUUID as kH}from"node:crypto";si();import{createInterface as uI}from"node:readline";var $E=[["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 LE(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of $E)if(t.includes(n))return r;return null}s(LE,"mapClientInfoNameToFamily");function uf(e){let t;try{t=JSON.parse(e)}catch{return null}if(!dc(t)||t.method!=="initialize")return null;let n=t.params;if(!dc(n))return null;let r=n.clientInfo;if(!dc(r))return null;let i=r.name,o=LE(typeof i=="string"?i:null);if(o===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:o,version:c}}s(uf,"tryExtractInitializeClient");function dc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(dc,"isRecord");import{fileURLToPath as FE}from"node:url";var uc="maind-bridge-",jE=8,pf=8e3;function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ct,"isRecord");function HE(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Ct(t)||t.method!=="initialize"||!Ct(t.params))return!1;let n=t.params.capabilities;return Ct(n)&&Ct(n.roots)}catch{return!1}}s(HE,"clientDeclaresRoots");function UE(e){if(!e.includes("notifications/initialized"))return!1;try{let t=JSON.parse(e);return t.method==="notifications/initialized"&&t.id===void 0}catch{return!1}}s(UE,"isInitializedNotification");function BE(e){if(!Ct(e)||!Ct(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Ct(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let i;try{i=FE(r.uri)}catch{continue}if(n.includes(i)||n.push(i),n.length>=jE)break}return n}s(BE,"rootPathsFrom");var No=class{constructor(t,n=!1){this.writeLine=t;this.initialized=n}static{s(this,"ClientRequestChannel")}initialized;closed=!1;waiters=[];pending=new Map;seq=0;observe(t){if(t.includes(uc)){let n;try{n=JSON.parse(t)}catch{n=null}if(Ct(n)&&typeof n.id=="string"&&n.id.startsWith(uc)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&UE(t)){this.initialized=!0;for(let n of this.waiters.splice(0))n(!0)}return!1}close(){if(!this.closed){this.closed=!0;for(let t of this.waiters.splice(0))t(!1);for(let t of[...this.pending.values()])t.settle(null)}}async request(t,n=pf){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(c=>{let l=s(u=>{clearTimeout(d),this.waiters=this.waiters.filter(p=>p!==l),c(u)},"done"),d=setTimeout(()=>l(!1),n);this.waiters.push(l)})||this.closed))return null;let i=`${uc}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,o=new Promise(a=>{let c=s(d=>{clearTimeout(l),this.pending.delete(i),a(d)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(i,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:i,method:t})),o}};async function ff(e,t,n=pf){return HE(e)?BE(await t.request("roots/list",n)):null}s(ff,"listClientRoots");hc();gc();function yc(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let o=JSON.parse(t);return Array.isArray(o)?o:[o]}catch{return[]}let n=[],r=[],i=s(()=>{if(r.length===0)return;let o=r.join(`
958
+ `).trim();if(r=[],o.length!==0)try{n.push(JSON.parse(o))}catch{}},"flush");for(let o of t.split(`
959
+ `)){let a=o.endsWith("\r")?o.slice(0,-1):o;if(a===""){i();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return i(),n}s(yc,"rpcMessagesOf");function vf(e,t){for(let n of yc(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}s(vf,"parseCloudToolResponse");Bt();var pI="https://mcp.maind.dev/mcp",Mi=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},Ts=class{static{s(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;clientChannel;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=Tr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=fI(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=mI(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 o=t.carry??null;o!==null&&(this.initFrame=o.initFrame,this.clientFamily===null&&(this.clientFamily=o.clientFamily),this.clientVersion===null&&(this.clientVersion=o.clientVersion),this.replayFrame=o.pendingFrame),this.clientChannel=new No(a=>process.stdout.write(a+`
960
+ `),o!==null&&o.initFrame!==null&&(o.pendingFrame===null||!Rr(o.pendingFrame))),this.shaRepoRoot=Oo(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??pI}async run(t=Sd()){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){this.clientChannel.close();return}let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}listClientRoots(t){return ff(this.initFrame,this.clientChannel,t)}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!n&&this.clientChannel.observe(t))return;if(!this.clientFamilyLocked&&this.clientFamily===null){let u=uf(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Rr(t)&&(this.initFrame=t);let r=yI(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=Do(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&_f(p)&&r.id!==null){let m=or(p,!0);process.stderr.write(`[maind] ${m}
961
+ `);let g=r.params?.name;process.stdout.write(ir(r.id,typeof g=="string"?g:"unknown",m)+`
962
+ `);return}i=or(f,!1),process.stderr.write(`[maind] ${i}
963
+ `)}if(this.assignedInbox&&!df(this.clientFamily)){let p=this.assignedInbox.takeNote();p!==null&&(i=i===null?p:`${i}
964
+ [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+`
965
+ `);return}let o=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Rr(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=Ss(t);if(this.serveInitializeFromCache(t,p))return;Es(p,-32603,`bridge network error: ${a_(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&&!Rr(t)){let u=await c.text().catch(()=>"");if(s_(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=Ss(t);Es(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Ss(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;Es(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(o&&this.localRouter){let u=d.startsWith("text/event-stream")?await kd(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
966
+ `);return}if(Rr(t)){let u=d.startsWith("text/event-stream")?await kd(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
967
+ `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await kd(c):await c.text(),p=gI(u,i);p.trim().length>0&&process.stdout.write(p+`
968
+ `);return}if(d.startsWith("text/event-stream"))await hI(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
969
+ `)}}}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 Mi(bI(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=Ss(n);Es(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}),o=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return vI(o)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,o=await this.postCloudToolCall(t,n,i);if(o.kind!=="session_lost")return o;if(!await this.recoverSession())return{kind:"http_error",status:404,body:o.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}`,o=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:o,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&&s_(l)?{kind:"session_lost",body:l}:a.ok?vf(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:a_(a),timedOut:_I(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=wt()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&i_(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Rr(t))return!1;let r=xs(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(o_(n,r)+`
970
+ `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ks(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Sd(){return uI({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}s(Sd,"stdinLines");function fI(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}s(fI,"normalizeClientFamily");function mI(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(mI,"normalizeClientVersion");async function hI(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=s(()=>{if(i.length===0)return;let a=i.join(`
967
971
  `).trim();i=[],a.length>0&&process.stdout.write(a+`
968
972
  `)},"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(`
969
- `))!==-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(UC,"pipeSseToStdout");function HC(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(HC,"appendNoteToToolResult");function BC(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}o(BC,"parseRpc");async function sd(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(`
970
- `).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(`
971
- `))!==-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(`
972
- `)}o(sd,"collectSseText");function lo(e){try{return JSON.parse(e).id??null}catch{return null}}o(lo,"tryExtractId");function yr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}o(yr,"isInitializeRequest");function Gy(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(Gy,"isSessionLossBody");function Ky(e){return e instanceof Error?e.message:String(e)}o(Ky,"stringifyErr");function GC(e){return e?.name==="TimeoutError"}o(GC,"isTimeoutError");function uo(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
973
- `)}o(uo,"emitJsonRpcError");function KC(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}o(KC,"extractHint");function WC(e){try{let t=ec(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(WC,"parsePresenceToolResult");ie();ie();br();import{spawn as nI}from"node:child_process";import{platform as rI}from"node:os";async function wr(e,t=process.stderr){let n=Ai(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=mo(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 aI(l.verification_uri_complete).catch(()=>{}),oI(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await sI(u);let f=await iI(i,l.device_code).catch(p=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(p)}
974
- `),null));if(f){if(f.status==="approved")return Sn(f.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${f.plan}). API key saved to ~/.config/maind/api-key
975
- `),{apiKey:f.api_key,plan:f.plan};if(f.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
976
- `),null;if(f.status==="expired"||f.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${f.status}
973
+ `))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){o();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{o()}}s(hI,"pipeSseToStdout");function gI(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}}s(gI,"appendNoteToToolResult");function yI(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(yI,"parseRpc");async function kd(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],a=s(()=>{if(o.length===0)return;let c=o.join(`
974
+ `).trim();o=[],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(`
975
+ `))!==-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:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
976
+ `)}s(kd,"collectSseText");function Ss(e){try{return JSON.parse(e).id??null}catch{return null}}s(Ss,"tryExtractId");function Rr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Rr,"isInitializeRequest");function s_(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")}s(s_,"isSessionLossBody");function a_(e){return e instanceof Error?e.message:String(e)}s(a_,"stringifyErr");function _I(e){return e?.name==="TimeoutError"}s(_I,"isTimeoutError");function Es(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
977
+ `)}s(Es,"emitJsonRpcError");function bI(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(bI,"extractHint");function vI(e){try{let t=yc(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}}s(vI,"parsePresenceToolResult");se();se();Ar();import{spawn as NI}from"node:child_process";import{platform as OI}from"node:os";async function Ir(e,t=process.stderr){let n=Li(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=Cs(e),a=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:o})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await $I(l.verification_uri_complete).catch(()=>{}),MI(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await PI(u);let p=await DI(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
978
+ `),null));if(p){if(p.status==="approved")return An(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
979
+ `),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
980
+ `),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
977
981
  `),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
978
- `),null}o(wr,"runDeviceFlow");async function iI(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(iI,"pollOnce");function sI(e){return new Promise(t=>setTimeout(t,e))}o(sI,"sleep");function oI(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: ${Jy(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Jy(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(`
982
+ `),null}s(Ir,"runDeviceFlow");async function DI(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()}s(DI,"pollOnce");function PI(e){return new Promise(t=>setTimeout(t,e))}s(PI,"sleep");function MI(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: ${p_(e.verification_uri,56)} \u2502`,` \u2502 Code: ${p_(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(`
979
983
  `)+`
980
- `)}o(oI,"printAuthInstructions");function Jy(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}o(Jy,"pad");async function aI(e){let t,n;switch(rI()){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=nI(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}o(aI,"openExternalBrowser");ud();Ue();ge();Ue();import*as pw from"node:os";En();var _o={devin:"windsurf"};function hd(){return md.map(e=>{let t=Object.keys(_o).filter(n=>_o[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}o(hd,"familyChoices");function l_(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 Ce("--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 Ce("--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 Ce("--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 Ce("--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 Ce(`--client requires a family argument (${hd()})`);let s=i.trim().toLowerCase(),a=Object.hasOwn(_o,s)?_o[s]:s;if(!md.includes(a))throw new Ce(`--client "${i}" is not a known client family. Known: ${hd()}`);t.client=a,n++;break}default:throw new Ce(`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 Ce(`--hooks-only wires the Claude Code hooks and nothing else \u2014 drop ${n.join(", ")}`)}return t}o(l_,"parseInstallFlags");var Ce=class extends Error{static{o(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function d_(){process.stdout.write(PI())}o(d_,"printInstallHelp");function PI(){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 / Devin Desktop (formerly 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:",` ${hd()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --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 hooks: Claude Code's in ~/.claude/settings.json and,"," where Cursor is installed, Cursor's in ~/.cursor/hooks.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(`
981
- `)}o(PI,"installHelpText");var Oi=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_
982
- `;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(`
984
+ `)}s(MI,"printAuthInstructions");function p_(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(p_,"pad");async function $I(e){let t,n;switch(OI()){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 o=NI(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s($I,"openExternalBrowser");Cd();Ge();we();Ge();import*as $v from"node:os";On();var Ps={devin:"windsurf"};function Id(){return Ad.map(e=>{let t=Object.keys(Ps).filter(n=>Ps[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}s(Id,"familyChoices");function O_(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 Pe("--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 Pe("--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 Pe("--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 Pe("--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 Pe(`--client requires a family argument (${Id()})`);let o=i.trim().toLowerCase(),a=Object.hasOwn(Ps,o)?Ps[o]:o;if(!Ad.includes(a))throw new Pe(`--client "${i}" is not a known client family. Known: ${Id()}`);t.client=a,n++;break}default:throw new Pe(`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 Pe(`--hooks-only wires the Claude Code hooks and nothing else \u2014 drop ${n.join(", ")}`)}return t}s(O_,"parseInstallFlags");var Pe=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function D_(){process.stdout.write(yN())}s(D_,"printInstallHelp");function yN(){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 / Devin Desktop (formerly 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:",` ${Id()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --skip-codex Skip Codex's config.toml even where Codex is installed",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only wire the hooks: Claude Code's in ~/.claude/settings.json and,"," where Cursor is installed, Cursor's in ~/.cursor/hooks.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(`
985
+ `)}s(yN,"installHelpText");var Ui=class{static{s(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_
986
+ `;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)),o=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),a=s((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),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??"",o)} |`);return l.join(`
983
987
  `)+`
984
988
  `}print(t){let n=this.summary();t.write(`
985
989
  `),t.write(this.toMarkdownTable()),t.write(`
986
990
  Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
987
- `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};gd();En();Mt();be();ko();be();En();import{applyEdits as BI,modify as GI,parse as KI,printParseErrorCode as WI}from"jsonc-parser";var Tn="maind";async function S_(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=c_(e),i=r.serversKey==="servers",s;try{s=await X(e.path)}catch(h){return _d(e,"read",h)}let a,c="create";if(s===null||s.trim().length===0)a={};else{c="merge";try{a=i?VI(s):JSON.parse(s)}catch(h){return e.refreshOnly!==void 0?k_(e,`not valid JSON: ${h instanceof Error?h.message:String(h)}`):_d(e,"parse",h)}}if(!Lt(a))return e.refreshOnly!==void 0?k_(e,"not a JSON object at root"):{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};if(e.refreshOnly!==void 0){let h=a[r.serversKey];if(s===null||!Lt(h)||!(Tn in h))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&qI(a),d,u,f=!1;if(l){let h=a[Tn];f=v_(h,t,r),u=w_(h,t,r),d={...a,[Tn]:u}}else{let h=a[r.serversKey],g=Lt(h)?h:{},y=g[Tn];f=v_(y,t,r),u=w_(y,t,r),d={...a,[r.serversKey]:{...g,[Tn]:u}}}if(f&&s!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let p=i&&!l?zI(s??"",[r.serversKey,Tn],u):JSON.stringify(d,null,2)+`
988
- `;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 _d(e,"write",h)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}o(S_,"mergeJsonConfig");function w_(e,t,n){let r=Lt(e)&&Lt(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(Lt(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(w_,"mergeEntry");function VI(e){let t=[],n=KI(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${WI(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}o(VI,"parseJsoncStrict");function zI(e,t,n){let r=GI(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
989
- `}}),i=BI(e,r);return i.endsWith(`
991
+ `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};Nd();On();Gt();xe();Ls();xe();On();import{applyEdits as TN,modify as RN,parse as CN,printParseErrorCode as AN}from"jsonc-parser";var Dn="maind";async function V_(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=N_(e),i=r.serversKey==="servers",o;try{o=await X(e.path)}catch(m){return Dd(e,"read",m)}let a,c="create";if(o===null||o.trim().length===0)a={};else{c="merge";try{a=i?IN(o):JSON.parse(o)}catch(m){return e.refreshOnly!==void 0?W_(e,`not valid JSON: ${m instanceof Error?m.message:String(m)}`):Dd(e,"parse",m)}}if(!Vt(a))return e.refreshOnly!==void 0?W_(e,"not a JSON object at root"):{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};if(e.refreshOnly!==void 0){let m=a[r.serversKey];if(o===null||!Vt(m)||!(Dn in m))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&ON(a),d,u,p=!1;if(l){let m=a[Dn];p=K_(m,t,r),u=G_(m,t,r),d={...a,[Dn]:u}}else{let m=a[r.serversKey],g=Vt(m)?m:{},y=g[Dn];p=K_(y,t,r),u=G_(y,t,r),d={...a,[r.serversKey]:{...g,[Dn]:u}}}if(p&&o!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=i&&!l?NN(o??"",[r.serversKey,Dn],u):JSON.stringify(d,null,2)+`
992
+ `;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,f)}catch(m){return Dd(e,"write",m)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}s(V_,"mergeJsonConfig");function G_(e,t,n){let r=Vt(e)&&Vt(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 o={command:t.command,args:[...t.args],env:i},a=n.entryType===void 0?o:{type:n.entryType,...o};if(n.clientKeys===void 0)return a;let{defaults:c,drop:l}=n.clientKeys,d={};if(Vt(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)}}s(G_,"mergeEntry");function IN(e){let t=[],n=CN(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${AN(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}s(IN,"parseJsoncStrict");function NN(e,t,n){let r=RN(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
993
+ `}}),i=TN(e,r);return i.endsWith(`
990
994
  `)?i:i+`
991
- `}o(zI,"editInPlace");function qI(e){return!("mcpServers"in e||!(Tn in e))}o(qI,"hasRootShape");function v_(e,t,n){if(!Lt(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||!JI(e.args,t.args)||!Lt(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}o(v_,"serverEntriesEqual");function JI(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(JI,"arrayEquals");function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Lt,"isObject");function k_(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}o(k_,"leftAlone");function _d(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(_d,"failed");be();import{parse as YI,stringify as XI}from"smol-toml";async function x_(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 X(e.path)}catch(g){return So(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=YI(r);if(!Rn(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return So(e,"parse",g)}}let a=Rn(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Rn(c)&&ZI(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Rn(c)&&Rn(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=XI(f),p.endsWith(`
992
- `)||(p+=`
993
- `)}catch(g){return So(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 So(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}o(x_,"mergeTomlConfig");function ZI(e,t){if(!Rn(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(!Rn(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(ZI,"tomlServerEntryEqual");function Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Rn,"isObject");function So(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(So,"failed");vd();Od();Td();jt();Ut();be();import*as M_ from"node:readline";var In="config:auto_working_paths",EN=`
995
+ `}s(NN,"editInPlace");function ON(e){return!("mcpServers"in e||!(Dn in e))}s(ON,"hasRootShape");function K_(e,t,n){if(!Vt(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||!DN(e.args,t.args)||!Vt(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}s(K_,"serverEntriesEqual");function DN(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}s(DN,"arrayEquals");function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Vt,"isObject");function W_(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}s(W_,"leftAlone");function Dd(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Dd,"failed");xe();import{parse as PN,stringify as MN}from"smol-toml";async function z_(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 X(e.path)}catch(g){return Fs(e,"read",g)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let g=PN(r);if(!Pn(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return Fs(e,"parse",g)}}let a=Pn(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Pn(c)&&$N(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Pn(c)&&Pn(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=MN(p),f.endsWith(`
996
+ `)||(f+=`
997
+ `)}catch(g){return Fs(e,"write",g)}let m=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await z(e.path,f)}catch(g){return Fs(e,"write",g)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(z_,"mergeTomlConfig");function $N(e,t){if(!Pn(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(!Pn(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s($N,"tomlServerEntryEqual");function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Pn,"isObject");function Fs(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Fs,"failed");$d();Vd();Bd();at();We();xe();import*as rb from"node:readline";var Fn="config:auto_working_paths",mO=`
994
998
  Enable presence enrichment (auto working_paths)?
995
999
  With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
996
1000
  locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
@@ -999,46 +1003,46 @@ before editing the same area. Directory names only: never file contents, never
999
1003
  absolute paths. Server-side these paths are account-private (org members never
1000
1004
  see them) and revocable any time on the dashboard consent page or via
1001
1005
  {"auto_working_paths": false} in the bridge config.
1002
- [y/N]: `;async function $_(e){let t=e.configPath??He(),n={};try{let a=await X(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:In,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:In,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??TN)(e.out,EN)}else return{target:In,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:In,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)+`
1003
- `;if(e.dryRun)return{target:In,action:"merge",status:"would-merge",detail:t};try{await z(t,s,384)}catch(a){return{target:In,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:In,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}o($_,"applyWorkingPathsConsent");async function TN(e,t){e.write(t);let n=M_.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(TN,"promptYesNoDefaultNo");Ao();import{existsSync as CN}from"node:fs";import{join as IN}from"node:path";function NN(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(NN,"readHookWired");function F_(e,t,n=CN){if(!NN(t))return null;let r=Bt(e,n)??e;return n(IN(r,Ht))?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(F_,"contextIndexRow");be();Mt();En();ko();import*as Md from"node:path";import*as U_ from"node:readline";var ON=Md.join(".cursor","hooks.json"),Dd=1,DN="on-cursor-session-start",j_=[{event:"sessionStart",subcommand:DN,label:"Cursor sessionStart hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-cursor-session-start' when a Cursor agent conversation starts and returns your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 as `additional_context` for the conversation's initial system context, kept under 10,000 characters. Delivery, not enforcement: it never blocks anything. It talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, the project key (a hash of the repository's git remote) and the client family 'cursor' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most starts add no network call. It records the conversation id, Cursor's transcript path and the size of what it returned in a local log (~/.maind/cursor/deliveries.jsonl), so `maind sessions scan-conventions --client cursor` can tell delivered from arrived; that log never leaves the machine. Cursor documents that it can drop sessionStart context in a race \u2014 the AGENTS.md block stays the reliable channel there."}];function H_(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}o(H_,"targetKeyFor");function Nn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Nn,"isObject");function PN(e,t,n){if(!Nn(e)||!Nn(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let i of r)if(Nn(i)&&typeof i.command=="string"&&i.command.includes(n))return i.command;return null}o(PN,"findCursorHookCommand");async function MN(e,t){let n=Md.join(e.homeDir,ON),r=H_(t),i=o((g,y,w="merge")=>({target:r,action:w,status:g,detail:y}),"row");if(e.skip)return i("skipped","--no-hook","skip");let s;try{s=await X(n)}catch(g){return i("failed",`read: ${Pd(g)}`)}let a={},c=s===null||s.trim().length===0;if(!c){let g;try{g=JSON.parse(s)}catch(w){return i("failed",`parse: ${Pd(w)} \u2014 ${n} left untouched`)}if(!Nn(g))return i("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==Dd)return i("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${Dd}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!Nn(a.hooks))return i("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=Nn(a.hooks)?a.hooks[t.event]:void 0;if(y!==void 0&&!Array.isArray(y))return i("failed",`"hooks.${t.event}" in ${n} is not an array \u2014 left untouched`)}let l=e.launch??ye({entryPath:_e(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=Xe(l),u=PN(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return i("skipped",kr(u)?`${g}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${d}`:g,"skip")}if(!e.full){if(!e.isInteractive)return i("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return i(c?"would-create":"would-merge",`${n} (would prompt for consent in real run)`);if(!await(e.prompt??$N)(e.out,`
1006
+ [y/N]: `;async function ib(e){let t=e.configPath??Ke(),n={};try{let a=await X(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:Fn,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:Fn,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??hO)(e.out,mO)}else return{target:Fn,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Fn,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},o=JSON.stringify(i,null,2)+`
1007
+ `;if(e.dryRun)return{target:Fn,action:"merge",status:"would-merge",detail:t};try{await z(t,o,384)}catch(a){return{target:Fn,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Fn,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(ib,"applyWorkingPathsConsent");async function hO(e,t){e.write(t);let n=rb.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}s(hO,"promptYesNoDefaultNo");Gs();import{existsSync as _O}from"node:fs";import{join as bO}from"node:path";function vO(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"}s(vO,"readHookWired");function sb(e,t,n=_O){if(!vO(t))return null;let r=qt(e,n)??e;return n(bO(r,zt))?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.`}}s(sb,"contextIndexRow");xe();Gt();On();Ls();import*as Jd from"node:path";import*as cb from"node:readline";var wO=Jd.join(".cursor","hooks.json"),zd=1,kO="on-cursor-session-start",ab=[{event:"sessionStart",subcommand:kO,label:"Cursor sessionStart hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-cursor-session-start' when a Cursor agent conversation starts and returns your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 as `additional_context` for the conversation's initial system context, kept under 10,000 characters. Delivery, not enforcement: it never blocks anything. It talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, the project key (a hash of the repository's git remote) and the client family 'cursor' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most starts add no network call. It records the conversation id, Cursor's transcript path and the size of what it returned in a local log (~/.maind/cursor/deliveries.jsonl), so `maind sessions scan-conventions --client cursor` can tell delivered from arrived; that log never leaves the machine. Cursor documents that it can drop sessionStart context in a race \u2014 the AGENTS.md block stays the reliable channel there."}];function lb(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}s(lb,"targetKeyFor");function jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(jn,"isObject");function xO(e,t,n){if(!jn(e)||!jn(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let i of r)if(jn(i)&&typeof i.command=="string"&&i.command.includes(n))return i.command;return null}s(xO,"findCursorHookCommand");async function SO(e,t){let n=Jd.join(e.homeDir,wO),r=lb(t),i=s((g,y,_="merge")=>({target:r,action:_,status:g,detail:y}),"row");if(e.skip)return i("skipped","--no-hook","skip");let o;try{o=await X(n)}catch(g){return i("failed",`read: ${qd(g)}`)}let a={},c=o===null||o.trim().length===0;if(!c){let g;try{g=JSON.parse(o)}catch(_){return i("failed",`parse: ${qd(_)} \u2014 ${n} left untouched`)}if(!jn(g))return i("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==zd)return i("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${zd}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!jn(a.hooks))return i("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=jn(a.hooks)?a.hooks[t.event]:void 0;if(y!==void 0&&!Array.isArray(y))return i("failed",`"hooks.${t.event}" in ${n} is not an array \u2014 left untouched`)}let l=e.launch??ke({entryPath:he(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=rt(l),u=xO(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return i("skipped",Or(u)?`${g}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${d}`:g,"skip")}if(!e.full){if(!e.isInteractive)return i("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return i(c?"would-create":"would-merge",`${n} (would prompt for consent in real run)`);if(!await(e.prompt??EO)(e.out,`
1004
1008
  Add a ${t.event} hook to ${n}?
1005
1009
  ${t.consentDescription}
1006
- [Y/n]: `))return i("skipped","user declined","skip")}let f=Nn(a.hooks)?a.hooks:{},p=Array.isArray(f[t.event])?f[t.event]:[],h={...a,version:a.version??Dd,hooks:{...f,[t.event]:[...p,{command:d,timeout:t.timeout}]}};if(e.dryRun)return i(c?"would-create":"would-merge",n,c?"write":"merge");try{await z(n,JSON.stringify(h,null,2)+`
1007
- `)}catch(g){return i("failed",`write: ${Pd(g)}`)}return i(c?"created":"merged",n,c?"write":"merge")}o(MN,"mergeCursorHook");async function $d(e){if(!e.explicit&&!e.skip&&!__(e.presence.ctx,e.presence.probe)){let n=Ci(e.presence.ctx).skipDetail;return j_.map(r=>({target:H_(r),action:"skip",status:"skipped",detail:n}))}let t=[];for(let n of j_)t.push(await MN(e,n));return t}o($d,"mergeCursorHooks");async function $N(e,t){e.write(t);let n=U_.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"}o($N,"promptYesNo");function Pd(e){return e instanceof Error?e.message:String(e)}o(Pd,"errMessage");ie();async function B_(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(B_,"exchangeOneClickToken");async function W_(e){let t="browser-pair";if(e.token!==null)try{let s=LN(e.token);return e.dryRun?{apiKey:s,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(Ri(),Sn(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:G_(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=mo(e.bridgeVersion),a=await B_({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:s.device_id,label:qy(),clientMeta:{...s}});if(a.ok)return Ri(),Sn(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,K_(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
1008
- `)}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 wr(e.bridgeVersion,K_(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:G_(s)}}}}o(W_,"pairOrUseToken");function LN(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(LN,"validateTokenShape");function G_(e){return e instanceof Error?e.message:String(e)}o(G_,"errMessage");function K_(e){return e.out??process.stdout}o(K_,"out");br();var FN="install-completed",jN=3e3;async function V_(e){if(!e.enabled||e.apiKey===null)return;let t=_r(FN),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:HN(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:UN(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),jN);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(V_,"postInstallTelemetry");function UN(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(UN,"countStatuses");function HN(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}o(HN,"parseNodeMajor");Vt();ea();ge();var SD="https://mcp.maind.dev/mcp";async function mw(e){let t=Date.now(),n;try{n=l_(e)}catch(b){if(b instanceof Ce)return process.stderr.write(`error: ${b.message}
1009
- `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw b}if(n.help)return d_(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=pw.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
1010
- `),2;if(n.hooksOnly)return xD({homeDir:s,isInteractive:i,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:Ni({projectRoot:s,homeDir:s,platform:process.platform,env:process.env}),probe:Sr});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let b=await bo(process.cwd());if(b.length===0)a=await p_(process.cwd());else if(b.length===1)a=b[0];else{let S=await h_(b,i);if(S===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
1011
- `);for(let N of b)process.stderr.write(` candidate: ${N}
1012
- `);return 2}a=S}}let c=new Oi,l=(process.env.MAIND_MCP_URL??"").trim()||SD;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1010
+ [Y/n]: `))return i("skipped","user declined","skip")}let p=jn(a.hooks)?a.hooks:{},f=Array.isArray(p[t.event])?p[t.event]:[],m={...a,version:a.version??zd,hooks:{...p,[t.event]:[...f,{command:d,timeout:t.timeout}]}};if(e.dryRun)return i(c?"would-create":"would-merge",n,c?"write":"merge");try{await z(n,JSON.stringify(m,null,2)+`
1011
+ `)}catch(g){return i("failed",`write: ${qd(g)}`)}return i(c?"created":"merged",n,c?"write":"merge")}s(SO,"mergeCursorHook");async function Yd(e){if(!e.explicit&&!e.skip&&!U_(e.presence.ctx,e.presence.probe)){let n=Nn(e.presence.ctx).skipDetail;return ab.map(r=>({target:lb(r),action:"skip",status:"skipped",detail:n}))}let t=[];for(let n of ab)t.push(await SO(e,n));return t}s(Yd,"mergeCursorHooks");async function EO(e,t){e.write(t);let n=cb.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}s(EO,"promptYesNo");function qd(e){return e instanceof Error?e.message:String(e)}s(qd,"errMessage");se();async function db(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}),o={};try{o=await i.json()}catch{}return i.ok?o.status!=="exchanged"||typeof o.api_key!="string"||!o.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:o.api_key,plan:o.plan??"unknown"}:{ok:!1,reason:o.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)}}s(db,"exchangeOneClickToken");async function fb(e){let t="browser-pair";if(e.token!==null)try{let o=TO(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:($i(),An(o),{apiKey:o,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(o){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:ub(o)}}}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 o=Cs(e.bridgeVersion),a=await db({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:u_(),clientMeta:{...o}});if(a.ok)return $i(),An(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,pb(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
1012
+ `)}let r=n===null?"":` (after exchange failure: ${n})`,i=J();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 o=await Ir(e.bridgeVersion,pb(e));return o===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:o.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${o.plan})${r}`}}}catch(o){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:ub(o)}}}}s(fb,"pairOrUseToken");function TO(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}s(TO,"validateTokenShape");function ub(e){return e instanceof Error?e.message:String(e)}s(ub,"errMessage");function pb(e){return e.out??process.stdout}s(pb,"out");Ar();var RO="install-completed",CO=3e3;async function mb(e){if(!e.enabled||e.apiKey===null)return;let t=Cr(RO),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:IO(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:AO(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),CO);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)}}s(mb,"postInstallTelemetry");function AO(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}s(AO,"countStatuses");function IO(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(IO,"parseNodeMajor");Zt();_a();we();var _P="https://mcp.maind.dev/mcp";async function Lv(e){let t=Date.now(),n;try{n=O_(e)}catch(w){if(w instanceof Pe)return process.stderr.write(`error: ${w.message}
1013
+ `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw w}if(n.help)return D_(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=$v.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
1014
+ `),2;if(n.hooksOnly)return bP({homeDir:o,isInteractive:i,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:Hi({projectRoot:o,homeDir:o,platform:process.platform,env:process.env}),probe:Wt});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let w=await Ms(process.cwd());if(w.length===0)a=await $_(process.cwd());else if(w.length===1)a=w[0];else{let x=await F_(w,i);if(x===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
1015
+ `);for(let N of w)process.stderr.write(` candidate: ${N}
1016
+ `);return 2}a=x}}let c=new Ui,l=(process.env.MAIND_MCP_URL??"").trim()||_P;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1013
1017
  `),process.stdout.write(`maind install \u2014 project root: ${a}
1014
1018
  `),process.stdout.write(` \u2014 mcp endpoint: ${l}
1015
1019
 
1016
- `);let d=Ni({projectRoot:a,homeDir:s,platform:process.platform,env:process.env}),u=Ii(d);if(u=a_(u,n.client),n.skipCodex&&(u=u.filter(b=>b.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.
1020
+ `);let d=Hi({projectRoot:a,homeDir:o,platform:process.platform,env:process.env,bridgeEntry:he()}),u=ji(d);if(u=I_(u,n.client),n.skipCodex&&(u=u.filter(w=>w.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.
1017
1021
  `:`error: no client targets selected (did you skip all of them?)
1018
- `),c.print(process.stdout),2;let f=await W_({bridgeVersion:G,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(`
1019
- pairing failed: ${f.result.detail??"unknown"}
1022
+ `),c.print(process.stdout),2;let p=await fb({bridgeVersion:K,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(`
1023
+ pairing failed: ${p.result.detail??"unknown"}
1020
1024
  Skipping remaining steps.
1021
- `),c.print(process.stdout),2;let p=new Set;for(let b of u){let S=b_({target:b,explicitFamily:n.client,probe:Sr});if(S!==null){c.add(S);continue}p.add(b.clientFamilyEnv);let N=n_({mcpUrl:l,clientFamily:b.clientFamilyEnv}),M;b.kind==="json"?M=await S_(b,N,n.dryRun):M=await x_(b,N,n.dryRun),c.add(M)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let b=[...p].find(N=>$r(N))??null,S=await C_({projectRoot:a,homeDir:s,...b!==null?{conventions:o(()=>Qo(f.apiKey,Pt(a),{allowFetch:!n.dryRun,clientFamily:b}),"conventions")}:{}},n.dryRun);for(let N of S)c.add(N);b===null&&c.add({target:Er,action:"upsert",status:"skipped",detail:"conventions block: skipped (no selected client uses the AGENTS.md block \u2014 Codex, Cursor, Devin Desktop, Copilot)"})}let h={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await P_(h));let g=await Nd(h);for(let b of g)c.add(b);n.dryRun||await Ed(Ft,g);let y=F_(a,g);if(y!==null&&c.add(y),c.add(await $_({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout})),u.some(b=>b.clientFamilyEnv==="cursor")){let b=await $d({...h,explicit:n.client==="cursor",presence:{ctx:d,probe:Sr}});for(let S of b)c.add(S)}let w=Ko();w.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${w.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await V_({enabled:n.telemetry||n.full,installerVersion:G,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:f.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let v=c.exitCode(),k=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
1025
+ `),c.print(process.stdout),2;let f=new Set;for(let w of u){let x=B_({target:w,explicitFamily:n.client,probe:Wt});if(x!==null){c.add(x);continue}f.add(w.clientFamilyEnv);let N=v_({mcpUrl:l,clientFamily:w.clientFamilyEnv}),L;w.kind==="json"?L=await V_(w,N,n.dryRun):L=await z_(w,N,n.dryRun),c.add(L)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let w=[...f].find(N=>Vr(N))??null,x=await Z_({projectRoot:a,homeDir:o,...w!==null?{conventions:s(()=>ya(p.apiKey,nt(a),{allowFetch:!n.dryRun,clientFamily:w}),"conventions")}:{}},n.dryRun);for(let N of x)c.add(N);w===null&&c.add({target:Mr,action:"upsert",status:"skipped",detail:"conventions block: skipped (no selected client uses the AGENTS.md block \u2014 Codex, Cursor, Devin Desktop, Copilot)"})}let m={homeDir:o,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},g=await Wd(m);for(let w of g)c.add(w);n.dryRun||await Ud(st,g);let y=sb(a,g);if(y!==null&&c.add(y),c.add(await ib({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout})),u.some(w=>w.clientFamilyEnv==="cursor")){let w=await Yd({...m,explicit:n.client==="cursor",presence:{ctx:d,probe:Wt}});for(let x of w)c.add(x)}let _=oa();_.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${_.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await mb({enabled:n.telemetry||n.full,installerVersion:K,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let b=c.exitCode(),k=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
1022
1026
  DRY RUN finished in ${k}s. No files were modified. Re-run without --dry-run to apply.
1023
1027
  `):process.stdout.write(`
1024
1028
  Finished in ${k}s. Restart your MCP client so it picks up the new server entry.
1025
- `);let x=ye({entryPath:_e(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),T=x.fallbackReason===null?`${Xe(x)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${T}
1026
- `),v===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.
1027
- `),v}o(mw,"runInstall");async function xD(e,t){let n=new Oi;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1029
+ `);let S=ke({entryPath:he(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),T=S.fallbackReason===null?`${rt(S)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${T}
1030
+ `),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.
1031
+ `),b}s(Lv,"runInstall");async function bP(e,t){let n=new Ui;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1028
1032
  `),e.out.write(`maind install --hooks-only \u2014 Claude Code hooks in ~/.claude/settings.json, and Cursor's in ~/.cursor/hooks.json where Cursor is installed
1029
- `);let r=await Nd(e);for(let i of r)n.add(i);e.dryRun||await Ed(Ft,r);for(let i of await $d({...e,explicit:!1,presence:t}))n.add(i);return n.print(e.out),e.out.write(e.dryRun?`
1033
+ `);let r=await Wd(e);for(let i of r)n.add(i);e.dryRun||await Ud(st,r);for(let i of await Yd({...e,explicit:!1,presence:t}))n.add(i);return n.print(e.out),e.out.write(e.dryRun?`
1030
1034
  DRY RUN finished. No files were modified.
1031
1035
  `:`
1032
1036
  Claude Code reads hooks when a session starts; Cursor reloads ~/.cursor/hooks.json by itself.
1033
- `),n.exitCode()}o(xD,"runHooksOnly");Vt();Vt();import{readFileSync as ED}from"node:fs";import{join as hw}from"node:path";function ta(e){return e?Math.ceil(e.length/4):0}o(ta,"estimateTokens");var gw=1e6,na=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 yw(e){try{let t=ED(e,"utf8");return t.length>gw?t.slice(0,gw):t}catch{return""}}o(yw,"readFileCapped");function TD(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(TD,"distinctFilePaths");function _w(e,t,n,r){try{let i=ta(n);if(e==="codebase_search"){let s=TD(t);if(s.length===0)return 0;let a=0;for(let c of s)a+=ta(yw(hw(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=ta(yw(hw(r,s)));return Math.max(0,a-i)}return 0}catch{return 0}}o(_w,"measureLocalToolSaved");Ot();Vt();import{createHash as zD}from"node:crypto";Ot();import{execFileSync as ID}from"node:child_process";import{createHash as ND}from"node:crypto";Vt();eu();import{realpathSync as xw}from"node:fs";function OD(e,t){try{return xw(e)===xw(t)}catch{return e===t}}o(OD,"samePath");var tu=30,DD=10,Ew=20,PD=new Map;function nu(e){return e instanceof Error?e.message:String(e)}o(nu,"msg");function ia(e){let t=e.split(`
1034
- `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}o(ia,"firstLine");var Tw=o(e=>e?e.slice(0,12):"?","short");async function MD(e,t,n,r){let i=await e.status(),s=!i.indexed||i.fileCount===0,a=await Sw(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:nu(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(MD,"refreshIndex");function $D(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}o($D,"isEmptyRange");function LD(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(LD,"localOnly");function FD(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(FD,"localGradeBlockers");function jD(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=ed(!1,e.projectKey,e.result);if(!t.persist)return t;let n=FD(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(jD,"bridgePersistDecision");function Rw(e,t){try{return ID("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}o(Rw,"git");function UD(e,t){let n=ui(e),r=n&&Rw(e,["merge-base",t,`origin/${n}`])||null,i=Rw(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}o(UD,"gitPersistFacts");function HD(e,t){return ND("sha256").update(`${e??""}
1035
- ${JSON.stringify(t)}`).digest("hex")}o(HD,"payloadKey");function Ge(e,t,n){return{kind:"error",error:e,message:t,hint:n}}o(Ge,"fail");var $n="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Aw(e){let t=nd(e);if(t!==null&&rd(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: ${ia(t?.detail??e)||"no detail"}`,$n)}o(Aw,"fromProtocolText");function BD(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. ${$n}`);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}`,$n);case"http_error":return e.status===401?Ge("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${ia(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}: ${ia(e.body)}`,$n);case"rpc_error":return Aw(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Aw(e.text);let r;try{r=JSON.parse(e.text)}catch{return Ge("cloud_unavailable",`review_verdict returned non-JSON text: ${ia(e.text)}`,$n)}return typeof r!="object"||r===null?Ge("cloud_unavailable","review_verdict returned no object",$n):{kind:"verdict",body:r}}}}o(BD,"interpretOutcome");var GD="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).",KD={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"},Cw=o(e=>e.map(t=>KD[t]??t).join("; "),"adviceFor");function WD(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: ${Cw(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 ${Tw(n)}, but this branch forks off ${i??"the default branch"} at ${Tw(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(WD,"skipText");function VD(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=Cw(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=WD(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(VD,"recordHint");async function Iw(e,t,n){let r=n.repoRoot??we(),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=Nr(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(!OD(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??PD,h=[],g=await MD(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(Zl(l,d)),w={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($D(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:w,warnings:h};let v;try{v=await s.reviewDetectorScopes({baseRef:l})}catch(te){let Hf=Re(dt(`reviewDetectorScopes failed: ${nu(te)}`));v={commit:Hf,local:Hf},h.push(`repo-health detectors unavailable (${nu(te)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:x}=Ql(y,v.commit);x>0&&h.push(`${x} symbol(s) exceed the server schema (name > ${so} or qualified name > ${oo} chars) and were left out \u2014 this run is not attestation-grade.`);let T=HD(a,k),b=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",S=jD({persistWanted:u,since:l,projectKey:a,result:y,payload:k,git:b?(n.persistFacts??UD)(i,y.headSha):null,recordedRunId:p.get(T)??null}),N={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:x,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:v.commit.coverage,findings:v.commit.local.slice(0,Ew),local_only:LD(v).slice(0,Ew)}},M=await n.callCloudTool("review_verdict",{attest:k,persist:S.persist,...a?{project_key:a}:{}},{timeoutMs:f}),B=BD(M,f,S.persist);if(B.kind==="error")return{ok:!1,error:B.error,message:B.message,hint:B.hint,base:w,local:N,warnings:h};let P=B.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?GD:P.hint??$n,base:w,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:w,local:N,warnings:h};let F=P.attest,W=P.run??null,_t=W&&typeof W.id=="string"?{persisted:!0,run_id:W.id,commit_sha:W.commit_sha??null,attestation_format:W.attestation_format??null}:{persisted:!1,reason:S.skipped??P.run_note??"not_persisted",...S.detail?{detail:S.detail}:{}};_t.persisted&&p.set(T,W.id);let Yr=typeof F?.attestation_grade=="boolean"?F.attestation_grade:null,J=Array.isArray(F?.grade_blockers)?F.grade_blockers:[],Se=P.counts??{},zn=Array.isArray(P.findings)?P.findings:[],Vx=`Verdict ${P.verdict??"?"}: ${Se.block??0} block, ${Se.warn??0} warn, ${Se.note??0} note`+(P.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:P.verdict??null,counts:Se,record:_t,attest:F?{attestation_grade:Yr,grade_blockers:J,attestation_format:F.attestation_format??null,input_hash:F.input_hash??null,policy_hash:F.policy_hash??null,evaluated_convention_count:F.evaluated_convention_count??null,detector_coverage:F.detector_coverage??null}:null,hint:`${Vx} ${VD(_t,Yr,J,y.headSha)}`,findings:zn.slice(0,tu).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,DD),matched_symbol_count:te.matched_symbols?.length??0})),...zn.length>tu?{findings_not_shown:zn.length-tu}:{},detector_findings:P.detector_findings??[],policy_source:P.policy_source??null,coverage_note:td(y,F?.evaluated_convention_count,x),base:w,local:N,warnings:h}}o(Iw,"runAttestReview");var Nw=(()=>{let e=Object.keys(gi),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function sa(e){return zD("sha256").update(e,"utf8").digest("hex")}o(sa,"nodeKeyHash");var qD=["module","class","interface","function","method","type_alias","enum","variable"],ru=[{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:qD,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 "+Nw+" \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 "+Nw+", 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."}}}}],iu=new Map([["codebase_review_verdict","attest_review_changes"]]),Pw=new Set([...ru.map(e=>e.name),...iu.keys()]),su=new Set(["attest_review_changes",...[...iu].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function Mw(e,t,n,r){if(!su.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 Iw(e,n,r),s=iu.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(Mw,"dispatchCloudBackedTool");function ae(e){return typeof e=="string"&&e.length>0?e:void 0}o(ae,"str");function Ln(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Ln,"num");function Ow(e){if(e===void 0)return{repoRoot:we(),scanDirs:void 0};let t=Nr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(Ow,"anchorRepo");function Dw(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(Dw,"dirNotFound");async function $w(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=ae(n.for_path);if(i!==void 0){let u=Db(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 yn(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 x of s){let T=Nr(x);if(T===null){f.push(x);continue}let b=u.get(T.repoRoot)??new Set;b.add(T.repoRelDir),u.set(T.repoRoot,b)}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[x,T]of u){let b=[...T],S=b.includes(""),N=await gn(x,{dirs:S?void 0:b,minFiles:r});p.push({repo_root:x,dirs:S?null:b}),h.push(...N.findings),g.push(...N.facts.namespaces.map(M=>({repo_root:x,dir:M.dir,prefix:M.prefix,file_count:M.fileCount}))),y.push(...N.facts.skipped)}let w=h.filter(x=>x.status==="open"),v=h.filter(x=>x.status==="info"),k=f.length>0?` ${f.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:w.length===0,open_count:w.length,preexisting_count:v.length,findings:w,preexisting:v.map(x=>`${x.namespace.prefix}${x.number}`),namespaces:g,skipped:y,scanned:p,...f.length>0?{unresolved_dirs:f}:{},hint:(w.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.":`${w.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=we(),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:ae(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=ae(n.dir),i,s;if(r!==void 0){let u=Nr(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=we(),s=void 0;let a=wn(i,{dirs:s,baseRef:ae(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=Ow(ae(n.dir));if(r===null)return Dw("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=bn(r.repoRoot,{dirs:r.scanDirs,baseRef:ae(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=Ow(ae(n.dir));if(r===null)return Dw("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Vl(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:ae(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=ae(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:ae(n.kind),limit:Ln(n.limit)})).map(s=>({...s,nodeKeyHash:sa(s.nodeKey)}))}case"codebase_trace":{let r=ae(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:Ln(n.max_depth),limit:Ln(n.limit)})}case"codebase_snippet":{let r=ae(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:sa(r)}}case"codebase_map":return e.getArchitecture({topN:Ln(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:ae(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ln(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:sa(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:ae(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ln(n.limit)}),i;if(n.include_history!==!1)try{i=Nc(await e.fileHistory({since:ae(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:ae(n.since)})}catch(l){s=Re(dt(`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:sa(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:ae(n.since),limit:Ln(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($w,"dispatchLocalTool");var oa=class{constructor(t=Mb,n=null,r=we,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return ru}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Pw.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=su.has(i)?await Mw(this.getEngine(),i,s,this.ctx??void 0):await $w(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=Nb(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=_w(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};br();var JD="/mcp-client-metrics-ingest",YD=4e3,XD="codebase_search_tokens_saved";async function Lw(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Ai()}${JD}`,n=new AbortController,r=setTimeout(()=>n.abort(),YD);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:XD,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)}
1036
- `),!1}finally{clearTimeout(r)}}o(Lw,"postSavingsMetric");cu();ca();Xr();da();Un();import{join as VM}from"node:path";var zM="<synthetic>";function Mv(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:VM(Ou,Du(e.cwd),`${e.transcript_stem}.jsonl`)}o(Mv,"transcriptPathFromSideChannel");var ka=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??Nu)(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!==zM&&(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 qM}from"node:child_process";var JM=8,YM=32;function XM(e){return e.split(`
1037
- `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,YM)}o(XM,"parsePorcelain");function ZM(e,t=JM){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(ZM,"condenseToDirs");async function $v(e=QM){let t=await e();if(t===null)return null;let n=ZM(XM(t));return n.length>0?n:null}o($v,"deriveWorkingPaths");async function QM(){return await new Promise(e=>{qM("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}o(QM,"defaultGitStatus");ea();var f1=1,p1=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function m1(e){return p1.includes(e)}o(m1,"isHookSubcommand");var h1=6e4;async function g1(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==q()&&Sn(e),e;let t=q();if(t!==null)return t;let n=await wr(G);return n===null&&(xn("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:G}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1038
- `),process.exit(1)),xn("paired",null,{version:G}),n.apiKey}o(g1,"ensureApiKey");async function y1(e){let t=await wr(G);return t===null&&(xn("auth_failed",`${e}; re-authorization did not complete`,{version:G}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1039
- `),process.exit(1)),xn("paired",null,{version:G}),t.apiKey}o(y1,"reauth");async function _1(){let e=process.argv.slice(2).find(b=>!b.startsWith("-"));if(e==="install"){let b=process.argv.indexOf("install"),S=process.argv.slice(b+1),N=await mw(S);process.exit(N)}if(e==="doctor"){let{runDoctor:b}=await Promise.resolve().then(()=>(Uu(),qv));process.exit(await b(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:b}=await Promise.resolve().then(()=>(Qk(),Zk));process.exit(await b())}if(e==="on-session-briefing"){let{runOnSessionBriefing:b}=await Promise.resolve().then(()=>(tS(),eS));process.exit(await b())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:b}=await Promise.resolve().then(()=>(dS(),lS));process.exit(await b())}if(e==="guard"){let b=process.argv.indexOf("guard"),{runGuard:S}=await Promise.resolve().then(()=>(gS(),hS));process.exit(await S(process.argv.slice(b+1)))}if(e==="guard-inject"){let{runGuardInject:b}=await Promise.resolve().then(()=>(Mn(),tw));process.exit(await b())}if(e==="guard-gate"){let{runGuardGate:b}=await Promise.resolve().then(()=>(xS(),SS));process.exit(await b())}if(e==="guard-stop"){let{runGuardStop:b}=await Promise.resolve().then(()=>(RS(),TS));process.exit(await b())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:b}=await Promise.resolve().then(()=>(yf(),bS));process.exit(await b())}if(e==="guard-capture"){let{runGuardCapture:b}=await Promise.resolve().then(()=>(NS(),IS));process.exit(await b())}if(e==="gateway"){let b=process.argv.indexOf("gateway"),{runGateway:S}=await Promise.resolve().then(()=>(hx(),mx));process.exit(await S(process.argv.slice(b+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:b}=await Promise.resolve().then(()=>(Nf(),If));process.exit(await b())}if(e==="guard-cross-check"){let{runGuardCrossCheck:b}=await Promise.resolve().then(()=>(Nf(),If));process.exit(await b())}if(e==="on-index-refresh"){let{runOnIndexRefresh:b}=await Promise.resolve().then(()=>(Df(),Of));process.exit(await b())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:b}=await Promise.resolve().then(()=>(Df(),Of));process.exit(await b())}if(e==="on-prompt-context"){let{runOnPromptContext:b}=await Promise.resolve().then(()=>(Uf(),jf));process.exit(await b())}if(e==="on-read-context"){let{runOnReadContext:b}=await Promise.resolve().then(()=>(Uf(),jf));process.exit(await b())}if(e!==void 0&&m1(e)){let b=await Promise.resolve().then(()=>(uf(),Uk)),S={"on-session-start":b.runOnSessionStart,"on-tool-use":b.runOnToolUse,"on-file-write":b.runOnFileWrite,"on-file-edit":b.runOnFileEdit,"on-repo-health":b.runOnRepoHealth,"on-write-health":b.runOnWriteHealth,"sync-config":b.runSyncConfig,flush:b.runFlush,status:b.runHookStatus}[e];process.exit(await S())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(G+`
1040
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(b1(),process.exit(0)),process.argv.includes("--reauth")&&(Ri(),await wr(G,process.stdout)===null&&process.exit(1),xn("paired",null,{version:G}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1041
- `),process.exit(0));let t=re(),n=await g1(),r=Y(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new na:null,a=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new oa(void 0,s,void 0,{callCloudTool:o((b,S,N)=>a===null?Promise.resolve({kind:"no_session"}):a.callCloudTool(b,S,N),"callCloudTool"),projectKey:r,engineFor:o(b=>{let S=c.get(b);return S===void 0&&(S=$b(b),c.set(b,S)),S},"engineFor"),projectKeyFor:Pt}),d=`bridge-${u1()}`,u=o(async()=>{if(!s)return;let b=s.takePending();b.tokens<=0||await Lw({apiKey:n,deviceId:t,sessionId:d,tokensSaved:b.tokens,bridgeVersion:G})},"flushSavings"),f=s?setInterval(()=>{u()},h1):null;f?.unref();let p=new la({projectKey:r}),h=new ka({resolvePath:o(()=>Mv(p.sideChannel()),"resolvePath"),fallbackModel:o(()=>p.sideChannel()?.model??null,"fallbackModel")}),g=new fs,y=new aa({projectKey:r,identity:p,sessionMeta:o(()=>h.read(),"sessionMeta"),postToolCall:o((b,S)=>a===null?Promise.reject(new Error("presence: no active forwarder")):a.postPresenceToolCall(b,S),"postToolCall"),deriveWorkingPaths:o(()=>$v(),"deriveWorkingPaths"),snapshot:r!==null?w1(qw({projectKey:r}),g):void 0}),w=y.isEnabled?setInterval(()=>{y.pollActivity()},Uw):null;if(w?.unref(),y.isEnabled){let b=o(S=>{y.end().finally(()=>process.exit(S))},"endAndExit");process.on("SIGTERM",()=>b(143)),process.on("SIGINT",()=>b(130))}let v=!1,k=o(b=>{if(v||!$r(b))return;v=!0,setTimeout(()=>{Promise.resolve().then(()=>(ea(),fw)).then(({refreshAgentsMdForSession:N})=>N(b,{apiKey:n,projectKey:r,listRoots:o(()=>a?.listClientRoots()??Promise.resolve(null),"listRoots")})).catch(()=>{})},0).unref()},"scheduleAgentsMdRefresh"),x=0,T=ad();try{for(;;){let b=a?.carryOver()??null,S=new fo({apiKey:n,deviceId:t,bridgeVersion:G,projectKey:r,localRouter:l,presence:y,onConnectionOutcome:o((N,M)=>xn(N,M,{version:G}),"onConnectionOutcome"),onSessionReady:o(({clientFamily:N})=>k(N),"onSessionReady"),assignedInbox:g,carry:b});a=S;try{await S.run(T);return}catch(N){if(N instanceof Ti&&x<f1){x+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${N.message}; re-authorizing\u2026
1042
- `),n=await y1(N.reason);continue}throw N}}}finally{f&&clearInterval(f),w&&clearInterval(w),await y.end(),await u()}}o(_1,"main");function b1(){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)","","Cursor hook subcommand (wired by `install` into ~/.cursor/hooks.json where Cursor is installed):"," on-cursor-session-start return the session briefing + project conventions as additional_context (MAIND-620)","","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 (Codex, Cursor, Windsurf, Copilot; 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(`
1043
- `))}o(b1,"printHelp");_1().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1044
- `),process.exit(1)});function w1(e,t){return{...e,write(n,r){try{t.update(n)}catch{}e.write(n,r)}}}o(w1,"withAssignedCapture");
1037
+ `),n.exitCode()}s(bP,"runHooksOnly");Zt();Zt();import{readFileSync as vP}from"node:fs";import{join as Fv}from"node:path";function ba(e){return e?Math.ceil(e.length/4):0}s(ba,"estimateTokens");var jv=1e6,va=class{static{s(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 Hv(e){try{let t=vP(e,"utf8");return t.length>jv?t.slice(0,jv):t}catch{return""}}s(Hv,"readFileCapped");function wP(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]}s(wP,"distinctFilePaths");function Uv(e,t,n,r){try{let i=ba(n);if(e==="codebase_search"){let o=wP(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=ba(Hv(Fv(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let a=ba(Hv(Fv(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Uv,"measureLocalToolSaved");Ut();Zt();import{createHash as BP}from"node:crypto";Ut();import{execFileSync as EP}from"node:child_process";import{createHash as TP}from"node:crypto";Zt();hu();import{realpathSync as zv}from"node:fs";function RP(e,t){try{return zv(e)===zv(t)}catch{return e===t}}s(RP,"samePath");var gu=30,CP=10,qv=20,AP=new Map;function yu(e){return e instanceof Error?e.message:String(e)}s(yu,"msg");function ka(e){let t=e.split(`
1038
+ `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(ka,"firstLine");var Jv=s(e=>e?e.slice(0,12):"?","short");async function IP(e,t,n,r){let i=await e.status(),o=!i.indexed||i.fileCount===0,a=await Vv(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:yu(c)}}},n);return a.locked?a.value.ok?o?(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}:(o||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:o}):(o||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:o})}s(IP,"refreshIndex");function NP(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(NP,"isEmptyRange");function OP(e){let t=s(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)))}s(OP,"localOnly");function DP(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}s(DP,"localGradeBlockers");function PP(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=yd(!1,e.projectKey,e.result);if(!t.persist)return t;let n=DP(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"}}s(PP,"bridgePersistDecision");function Yv(e,t){try{return EP("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(Yv,"git");function MP(e,t){let n=vi(e),r=n&&Yv(e,["merge-base",t,`origin/${n}`])||null,i=Yv(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}s(MP,"gitPersistFacts");function $P(e,t){return TP("sha256").update(`${e??""}
1039
+ ${JSON.stringify(t)}`).digest("hex")}s($P,"payloadKey");function qe(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(qe,"fail");var zn="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Xv(e){let t=bd(e);if(t!==null&&vd(t))return qe("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 qe("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 qe("cloud_unavailable",`review_verdict failed: ${ka(t?.detail??e)||"no detail"}`,zn)}s(Xv,"fromProtocolText");function LP(e,t,n){switch(e.kind){case"no_session":return qe("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. ${zn}`);case"transport_error":return e.timedOut?qe("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."):qe("cloud_unavailable",`network error: ${e.message}`,zn);case"http_error":return e.status===401?qe("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${ka(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?qe("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."):qe("cloud_unavailable",`HTTP ${e.status}: ${ka(e.body)}`,zn);case"rpc_error":return Xv(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Xv(e.text);let r;try{r=JSON.parse(e.text)}catch{return qe("cloud_unavailable",`review_verdict returned non-JSON text: ${ka(e.text)}`,zn)}return typeof r!="object"||r===null?qe("cloud_unavailable","review_verdict returned no object",zn):{kind:"verdict",body:r}}}}s(LP,"interpretOutcome");var FP="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).",jP={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"},Zv=s(e=>e.map(t=>jP[t]??t).join("; "),"adviceFor");function HP(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: ${Zv(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 ${Jv(n)}, but this branch forks off ${i??"the default branch"} at ${Jv(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}}s(HP,"skipText");function UP(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=Zv(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??"",o=HP(i,e.detail),a=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return o!==null?`Not recorded: ${o}${a}`:`Not recorded (${i||"the server gave no reason"}).${a}`}s(UP,"recordHint");async function Qv(e,t,n){let r=n.repoRoot??Se(),i=r,o=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let ne=Ur(c,r);if(ne===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(!RP(ne.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=ne.repoRoot,o=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??AP,m=[],g=await IP(o,i,n.lock,m);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:m};let y=await o.reviewChanges(hd(l,d)),_={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(NP(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:_,warnings:m};let b;try{b=await o.reviewDetectorScopes({baseRef:l})}catch(ne){let rf=Oe(bt(`reviewDetectorScopes failed: ${yu(ne)}`));b={commit:rf,local:rf},m.push(`repo-health detectors unavailable (${yu(ne)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:S}=gd(y,b.commit);S>0&&m.push(`${S} symbol(s) exceed the server schema (name > ${vs} or qualified name > ${ws} chars) and were left out \u2014 this run is not attestation-grade.`);let T=$P(a,k),w=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",x=PP({persistWanted:u,since:l,projectKey:a,result:y,payload:k,git:w?(n.persistFacts??MP)(i,y.headSha):null,recordedRunId:f.get(T)??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:b.commit.coverage,findings:b.commit.local.slice(0,qv),local_only:OP(b).slice(0,qv)}},L=await n.callCloudTool("review_verdict",{attest:k,persist:x.persist,...a?{project_key:a}:{}},{timeoutMs:p}),B=LP(L,p,x.persist);if(B.kind==="error")return{ok:!1,error:B.error,message:B.message,hint:B.hint,base:_,local:N,warnings:m};let P=B.body;if(P.ok!==!0){let ne=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:ne?FP:P.hint??zn,base:_,local:N,warnings:m}}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:_,local:N,warnings:m};let j=P.attest,W=P.run??null,ut=W&&typeof W.id=="string"?{persisted:!0,run_id:W.id,commit_sha:W.commit_sha??null,attestation_format:W.attestation_format??null}:{persisted:!1,reason:x.skipped??P.run_note??"not_persisted",...x.detail?{detail:x.detail}:{}};ut.persisted&&f.set(T,W.id);let So=typeof j?.attestation_grade=="boolean"?j.attestation_grade:null,oi=Array.isArray(j?.grade_blockers)?j.grade_blockers:[],q=P.counts??{},Le=Array.isArray(P.findings)?P.findings:[],Eo=`Verdict ${P.verdict??"?"}: ${q.block??0} block, ${q.warn??0} warn, ${q.note??0} note`+(P.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:P.verdict??null,counts:q,record:ut,attest:j?{attestation_grade:So,grade_blockers:oi,attestation_format:j.attestation_format??null,input_hash:j.input_hash??null,policy_hash:j.policy_hash??null,evaluated_convention_count:j.evaluated_convention_count??null,detector_coverage:j.detector_coverage??null}:null,hint:`${Eo} ${UP(ut,So,oi,y.headSha)}`,findings:Le.slice(0,gu).map(ne=>({convention_id:ne.convention_id,convention_version:ne.convention_version,severity:ne.severity,action:ne.action,...ne.downgrade_reason?{downgrade_reason:ne.downgrade_reason}:{},summary:ne.summary,matched_changed_symbols:(ne.matched_changed_symbols??[]).slice(0,CP),matched_symbol_count:ne.matched_symbols?.length??0})),...Le.length>gu?{findings_not_shown:Le.length-gu}:{},detector_findings:P.detector_findings??[],policy_source:P.policy_source??null,coverage_note:_d(y,j?.evaluated_convention_count,S),base:_,local:N,warnings:m}}s(Qv,"runAttestReview");var ew=(()=>{let e=Object.keys(Ei),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function xa(e){return BP("sha256").update(e,"utf8").digest("hex")}s(xa,"nodeKeyHash");var GP=["module","class","interface","function","method","type_alias","enum","variable"],_u=[{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:GP,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 "+ew+" \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 "+ew+", 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."}}}}],bu=new Map([["codebase_review_verdict","attest_review_changes"]]),rw=new Set([..._u.map(e=>e.name),...bu.keys()]),vu=new Set(["attest_review_changes",...[...bu].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function iw(e,t,n,r){if(!vu.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 Qv(e,n,r),o=bu.get(t);return o?{...i,renamed:{from:t,to:o,note:`${t} is ${o} since bridge 0.79.0 \u2014 call ${o}; the old name goes in a later minor.`}}:i}s(iw,"dispatchCloudBackedTool");function de(e){return typeof e=="string"&&e.length>0?e:void 0}s(de,"str");function qn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(qn,"num");function tw(e){if(e===void 0)return{repoRoot:Se(),scanDirs:void 0};let t=Ur(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(tw,"anchorRepo");function nw(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}.`}}s(nw,"dirNotFound");async function ow(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,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} 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=de(n.for_path);if(i!==void 0){let u=tv(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 xn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,m=s(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:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(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?`${m(p.number)} is already held (see held_by). Create the file as ${m(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.`:`${m(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 o=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(o!==void 0&&o.length>0){let u=new Map,p=[];for(let S of o){let T=Ur(S);if(T===null){p.push(S);continue}let w=u.get(T.repoRoot)??new Set;w.add(T.repoRelDir),u.set(T.repoRoot,w)}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=[],m=[],g=[],y=[];for(let[S,T]of u){let w=[...T],x=w.includes(""),N=await kn(S,{dirs:x?void 0:w,minFiles:r});f.push({repo_root:S,dirs:x?null:w}),m.push(...N.findings),g.push(...N.facts.namespaces.map(L=>({repo_root:S,dir:L.dir,prefix:L.prefix,file_count:L.fileCount}))),y.push(...N.facts.skipped)}let _=m.filter(S=>S.status==="open"),b=m.filter(S=>S.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.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.":`${_.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=Se(),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:de(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=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=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...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 ${o.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.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=de(n.dir),i,o;if(r!==void 0){let u=Ur(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,o=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=Se(),o=void 0;let a=Tn(i,{dirs:o,baseRef:de(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=tw(de(n.dir));if(r===null)return nw("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=En(r.repoRoot,{dirs:r.scanDirs,baseRef:de(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="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.`)+" "+o}}case"check_migration_ledger_drift":{let r=tw(de(n.dir));if(r===null)return nw("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=ld(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:de(n.remote_db_url)}),o=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=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=o.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:o,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=de(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:de(n.kind),limit:qn(n.limit)})).map(o=>({...o,nodeKeyHash:xa(o.nodeKey)}))}case"codebase_trace":{let r=de(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:qn(n.max_depth),limit:qn(n.limit)})}case"codebase_snippet":{let r=de(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:xa(r)}}case"codebase_map":return e.getArchitecture({topN:qn(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:de(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:qn(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:xa(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:de(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:qn(n.limit)}),i;if(n.include_history!==!1)try{i=qc(await e.fileHistory({since:de(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:de(n.since)})}catch(l){o=Oe(bt(`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:o.coverage},c=o.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:xa(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:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.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 ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.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(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:de(n.since),limit:qn(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.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(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.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}`)}}s(ow,"dispatchLocalTool");var Sa=class{constructor(t=rv,n=null,r=Se,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return _u}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&rw.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=vu.has(i)?await iw(this.getEngine(),i,o,this.ctx??void 0):await ow(this.getEngine(),i,o),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=Qb(a)?`${ev} (${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(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.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=Uv(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Ar();var KP="/mcp-client-metrics-ingest",WP=4e3,VP="codebase_search_tokens_saved";async function sw(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Li()}${KP}`,n=new AbortController,r=setTimeout(()=>n.abort(),WP);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:VP,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)}
1040
+ `),!1}finally{clearTimeout(r)}}s(sw,"postSavingsMetric");xu();Ta();si();Ca();Xn();import{join as U$}from"node:path";var B$="<synthetic>";function ik(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:U$(zu,qu(e.cwd),`${e.transcript_stem}.jsonl`)}s(ik,"transcriptPathFromSideChannel");var Ha=class{constructor(t){this.deps=t}static{s(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??Vu)(n,{start:this.offset});for(let o of i.events)if(o.kind==="title"){let a=o.title.trim();a.length>0&&(this.title=a)}else o.kind==="assistant"&&!o.isSidechain&&typeof o.model=="string"&&o.model.length>0&&o.model!==B$&&(this.model=o.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 G$}from"node:child_process";var K$=8,W$=32;function V$(e){return e.split(`
1041
+ `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,W$)}s(V$,"parsePorcelain");function z$(e,t=K$){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let o=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(o.length===0||n.includes(o))&&(n.push(o),n.length>=t))break}return n}s(z$,"condenseToDirs");async function ok(e=q$){let t=await e();if(t===null)return null;let n=z$(V$(t));return n.length>0?n:null}s(ok,"deriveWorkingPaths");async function q$(){return await new Promise(e=>{G$("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(q$,"defaultGitStatus");_a();var xH=1,SH=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function EH(e){return SH.includes(e)}s(EH,"isHookSubcommand");var TH=6e4;async function RH(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==J()&&An(e),e;let t=J();if(t!==null)return t;let n=await Ir(K);return n===null&&(In("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:K}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1042
+ `),process.exit(1)),In("paired",null,{version:K}),n.apiKey}s(RH,"ensureApiKey");async function CH(e){let t=await Ir(K);return t===null&&(In("auth_failed",`${e}; re-authorization did not complete`,{version:K}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1043
+ `),process.exit(1)),In("paired",null,{version:K}),t.apiKey}s(CH,"reauth");async function AH(){let e=process.argv.slice(2).find(w=>!w.startsWith("-"));if(e==="install"){let w=process.argv.indexOf("install"),x=process.argv.slice(w+1),N=await Lv(x);process.exit(N)}if(e==="doctor"){let{runDoctor:w}=await Promise.resolve().then(()=>(rp(),kk));process.exit(await w(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:w}=await Promise.resolve().then(()=>(Tx(),Ex));process.exit(await w())}if(e==="on-session-briefing"){let{runOnSessionBriefing:w}=await Promise.resolve().then(()=>(Cx(),Rx));process.exit(await w())}if(e==="on-session-reminder"){let{runOnSessionReminder:w}=await Promise.resolve().then(()=>(Nx(),Ix));process.exit(await w())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:w}=await Promise.resolve().then(()=>(Hx(),jx));process.exit(await w())}if(e==="guard"){let w=process.argv.indexOf("guard"),{runGuard:x}=await Promise.resolve().then(()=>(Vx(),Wx));process.exit(await x(process.argv.slice(w+1)))}if(e==="guard-inject"){let{runGuardInject:w}=await Promise.resolve().then(()=>(Vn(),Sv));process.exit(await w())}if(e==="guard-gate"){let{runGuardGate:w}=await Promise.resolve().then(()=>(eS(),Qx));process.exit(await w())}if(e==="guard-stop"){let{runGuardStop:w}=await Promise.resolve().then(()=>(rS(),nS));process.exit(await w())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:w}=await Promise.resolve().then(()=>(Dp(),Jx));process.exit(await w())}if(e==="guard-capture"){let{runGuardCapture:w}=await Promise.resolve().then(()=>(aS(),sS));process.exit(await w())}if(e==="gateway"){let w=process.argv.indexOf("gateway"),{runGateway:x}=await Promise.resolve().then(()=>(WS(),KS));process.exit(await x(process.argv.slice(w+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:w}=await Promise.resolve().then(()=>(zp(),Vp));process.exit(await w())}if(e==="guard-cross-check"){let{runGuardCrossCheck:w}=await Promise.resolve().then(()=>(zp(),Vp));process.exit(await w())}if(e==="on-index-refresh"){let{runOnIndexRefresh:w}=await Promise.resolve().then(()=>(Jp(),qp));process.exit(await w())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:w}=await Promise.resolve().then(()=>(Jp(),qp));process.exit(await w())}if(e==="on-prompt-context"){let{runOnPromptContext:w}=await Promise.resolve().then(()=>(nf(),tf));process.exit(await w())}if(e==="on-read-context"){let{runOnReadContext:w}=await Promise.resolve().then(()=>(nf(),tf));process.exit(await w())}if(e!==void 0&&EH(e)){let w=await Promise.resolve().then(()=>(Rp(),px)),x={"on-session-start":w.runOnSessionStart,"on-tool-use":w.runOnToolUse,"on-file-write":w.runOnFileWrite,"on-file-edit":w.runOnFileEdit,"on-repo-health":w.runOnRepoHealth,"on-write-health":w.runOnWriteHealth,"sync-config":w.runSyncConfig,flush:w.runFlush,status:w.runHookStatus}[e];process.exit(await x())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(K+`
1044
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(IH(),process.exit(0)),process.argv.includes("--reauth")&&($i(),await Ir(K,process.stdout)===null&&process.exit(1),In("paired",null,{version:K}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1045
+ `),process.exit(0));let t=oe(),n=await RH(),r=Y(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new va:null,a=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Sa(void 0,o,void 0,{callCloudTool:s((w,x,N)=>a===null?Promise.resolve({kind:"no_session"}):a.callCloudTool(w,x,N),"callCloudTool"),projectKey:r,engineFor:s(w=>{let x=c.get(w);return x===void 0&&(x=iv(w),c.set(w,x)),x},"engineFor"),projectKeyFor:nt}),d=`bridge-${kH()}`,u=s(async()=>{if(!o)return;let w=o.takePending();w.tokens<=0||await sw({apiKey:n,deviceId:t,sessionId:d,tokensSaved:w.tokens,bridgeVersion:K})},"flushSavings"),p=o?setInterval(()=>{u()},TH):null;p?.unref();let f=new Ra({projectKey:r}),m=new Ha({resolvePath:s(()=>ik(f.sideChannel()),"resolvePath"),fallbackModel:s(()=>f.sideChannel()?.model??null,"fallbackModel")}),g=new Ro,y=new Ea({projectKey:r,identity:f,sessionMeta:s(()=>m.read(),"sessionMeta"),postToolCall:s((w,x)=>a===null?Promise.reject(new Error("presence: no active forwarder")):a.postPresenceToolCall(w,x),"postToolCall"),deriveWorkingPaths:s(()=>ok(),"deriveWorkingPaths"),snapshot:r!==null?NH(yw({projectKey:r}),g):void 0}),_=y.isEnabled?setInterval(()=>{y.pollActivity()},lw):null;if(_?.unref(),y.isEnabled){let w=s(x=>{y.end().finally(()=>process.exit(x))},"endAndExit");process.on("SIGTERM",()=>w(143)),process.on("SIGINT",()=>w(130))}let b=!1,k=s(w=>{if(b||!Vr(w))return;b=!0,setTimeout(()=>{Promise.resolve().then(()=>(_a(),Mv)).then(({refreshAgentsMdForSession:N})=>N(w,{apiKey:n,projectKey:r,listRoots:s(()=>a?.listClientRoots()??Promise.resolve(null),"listRoots")})).catch(()=>{})},0).unref()},"scheduleAgentsMdRefresh"),S=0,T=Sd();try{for(;;){let w=a?.carryOver()??null,x=new Ts({apiKey:n,deviceId:t,bridgeVersion:K,projectKey:r,localRouter:l,presence:y,onConnectionOutcome:s((N,L)=>In(N,L,{version:K}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:N})=>k(N),"onSessionReady"),assignedInbox:g,carry:w});a=x;try{await x.run(T);return}catch(N){if(N instanceof Mi&&S<xH){S+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${N.message}; re-authorizing\u2026
1046
+ `),n=await CH(N.reason);continue}throw N}}}finally{p&&clearInterval(p),_&&clearInterval(_),await y.end(),await u()}}s(AH,"main");function IH(){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-reminder add ~/.claude/maind-session-start-reminder.md at session start (replaces `cat`; MAIND-630)"," 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)","","Cursor hook subcommand (wired by `install` into ~/.cursor/hooks.json where Cursor is installed):"," on-cursor-session-start return the session briefing + project conventions as additional_context (MAIND-620)","","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 (Codex, Cursor, Windsurf, Copilot; ADR-359 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," MAIND_DEVIN_HOOK_OUTPUT 'off' keeps every hook silent when Devin Local runs it (default on; or",' "devin_hook_output": false in config.json \u2014 MAIND-630, unmeasured there)'," 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(`
1047
+ `))}s(IH,"printHelp");AH().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1048
+ `),process.exit(1)});function NH(e,t){return{...e,write(n,r){try{t.update(n)}catch{}e.write(n,r)}}}s(NH,"withAssignedCapture");