@maind-dev/mcp-bridge 0.100.0 → 0.101.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,46 +1,46 @@
1
1
  #!/usr/bin/env node
2
- var Um=Object.defineProperty;var s=(e,t)=>Um(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var Z=(e,t)=>{for(var n in t)Um(e,n,{get:t[n],enumerable:!0})};import{homedir as OC}from"node:os";import{join as DC}from"node:path";function us(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=No(r.id),i=No(r.key),a=No(r.title),c=No(r.status);if(!o||!i||!a||!c)continue;let l=r.here===!1?!1:void 0,d=No(r.where);if(t.push({id:o,key:i,title:a,status:c,...l===!1?{here:l}:{},...d?{where:d}:{}}),t.length>=PC)break}return t}function dl(e){if(e.length===0)return null;let t=e.map(r=>`${r.key} "${r.title}"${r.status==="warn"?" (blocked)":""}`+(r.here===!1?` (in ${r.where?`${r.where}/`:"a repository below this one"})`:"")).join(", "),n=e.length===1;return`Assigned to your user 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 Bm(e=OC()){return DC(e,".maind","assigned-told")}function Km(e,t){if(!e||typeof e!="object")return e;let n=e;return Array.isArray(n.assigned_to_you)?{...n,assigned_to_you:n.assigned_to_you.map(r=>{if(!r||typeof r!="object")return r;let o=r;if(o.here!==!1||typeof o.project_key!="string")return r;let i=t(o.project_key);return i?{...o,where:i}:r})}:e}function Gm(e){return e==="claude-code"}var PC,No,ds,Oo=w(()=>{"use strict";PC=5,No=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(us,"parseAssignedList");s(dl,"assignedNoticeText");s(Bm,"assignedToldDir");ds=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=us(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 dl(t)}};s(Km,"labelNestedItems");s(Gm,"clientHasHooks")});function zm(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,o=typeof n.method=="string"?n.method:void 0;if(o!==void 0){let i={kind:r!==void 0?"request":"notification",method:o,id:r};if(o==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(i.toolName=c)}}return i}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function xr(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 fl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function ml(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function hl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var gl=w(()=>{"use strict";s(zm,"parseFrame");s(xr,"denyResult");s(fl,"toolEvent");s(ml,"policyEvent");s(hl,"shaEvent")});import{execFileSync as Xm}from"node:child_process";function Zm(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=WC}function VC(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 o=[];for(let i of BC){let a=r[i];typeof a=="string"&&Jm.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of KC){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Jm.test(l)&&o.push({field:`${i}.${a}`,sha:l})}return o}function qC(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,Ym);for(let o=Ym;o>=GC;o--){let i=r.slice(0,o),a=t(i);if(a!==null&&a.startsWith(i))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:o}}return{field:"",sha:e,verdict:"unknown"}}function Sr(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 Qm(){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 fs(e=process.cwd()){try{let n=Xm("git",["rev-parse","--show-toplevel"],{cwd:e,env:Qm(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function zC(e){return t=>{try{let r=Xm("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Qm(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function ms(e,t){if(t===null)return[];let n=VC(e);if(n.length===0)return[];let r=zC(t),o=[];for(let{field:i,sha:a}of n){let c=qC(a,r);c.verdict!=="proven"&&o.push({...c,field:i})}return o}var BC,KC,Jm,GC,Ym,WC,yl=w(()=>{"use strict";BC=["commit_sha","base_sha","head_sha"],KC=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Jm=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,GC=7,Ym=12,WC=10;s(Zm,"isDenyGrade");s(VC,"extractShaArgs");s(qC,"classifySha");s(Sr,"shaFindingText");s(Qm,"cleanGitEnv");s(fs,"resolveRepoRootForSha");s(zC,"gitShaResolver");s(ms,"inspectLineForShas")});var th=w(()=>{"use strict"});var G,bl,N,dt,Do=w(()=>{(function(e){e.assertEqual=o=>{};function t(o){}s(t,"assertIs"),e.assertIs=t;function n(o){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},e.getValidEnumValues=o=>{let i=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},e.find=(o,i)=>{for(let a of o)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(bl||(bl={}));N=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dt=s(e=>{switch(typeof e){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(e)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":return Array.isArray(e)?N.array:e===null?N.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?N.promise:typeof Map<"u"&&e instanceof Map?N.map:typeof Set<"u"&&e instanceof Set?N.set:typeof Date<"u"&&e instanceof Date?N.date:N.object;default:return N.unknown}},"getParsedType")});var C,JC,Ae,hs=w(()=>{Do();C=G.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"]),JC=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),Ae=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(i){return i.message},r={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(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 o(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,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ae.create=e=>new Ae(e)});var YC,St,wl=w(()=>{hs();Do();YC=s((e,t)=>{let n;switch(e.code){case C.invalid_type:e.received===N.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case C.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,G.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:n=`Unrecognized key(s) in object: ${G.joinValues(e.keys,", ")}`;break;case C.invalid_union:n="Invalid input";break;case C.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${G.joinValues(e.options)}`;break;case C.invalid_enum_value:n=`Invalid enum value. Expected ${G.joinValues(e.options)}, received '${e.received}'`;break;case C.invalid_arguments:n="Invalid function arguments";break;case C.invalid_return_type:n="Invalid function return type";break;case C.invalid_date:n="Invalid date";break;case C.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}"`:G.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case C.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 C.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 C.custom:n="Invalid input";break;case C.invalid_intersection_types:n="Intersection results could not be merged";break;case C.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case C.not_finite:n="Number must be finite";break;default:n=t.defaultError,G.assertNever(e)}return{message:n}},"errorMap"),St=YC});function XC(e){nh=e}function Er(){return nh}var nh,gs=w(()=>{wl();nh=St;s(XC,"setErrorMap");s(Er,"getErrorMap")});function A(e,t){let n=Er(),r=Po({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===St?void 0:St].filter(o=>!!o)});e.common.issues.push(r)}var Po,ZC,ue,M,xn,ye,ys,_s,Kt,Rr,vl=w(()=>{gs();wl();Po=s(e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:i,message:c}},"makeIssue"),ZC=[];s(A,"addIssueToContext");ue=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 o of n){if(o.status==="aborted")return M;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let i=await o.key,a=await o.value;r.push({key:i,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return M;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}},M=Object.freeze({status:"aborted"}),xn=s(e=>({status:"dirty",value:e}),"DIRTY"),ye=s(e=>({status:"valid",value:e}),"OK"),ys=s(e=>e.status==="aborted","isAborted"),_s=s(e=>e.status==="dirty","isDirty"),Kt=s(e=>e.status==="valid","isValid"),Rr=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var rh=w(()=>{});var O,oh=w(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}))});function j(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{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:o}}function ch(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 hT(e){return new RegExp(`^${ch(e)}$`)}function lh(e){let t=`${ah}T${ch(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 gT(e,t){return!!((t==="v4"||!t)&&cT.test(e)||(t==="v6"||!t)&&dT.test(e))}function yT(e,t){if(!oT.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,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function _T(e,t){return!!((t==="v4"||!t)&&lT.test(e)||(t==="v6"||!t)&&uT.test(e))}function bT(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return i%a/10**o}function Cr(e){if(e instanceof Ie){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ke.create(Cr(r))}return new Ie({...e._def,shape:s(()=>t,"shape")})}else return e instanceof Ct?new Ct({...e._def,type:Cr(e.element)}):e instanceof Ke?Ke.create(Cr(e.unwrap())):e instanceof pt?pt.create(Cr(e.unwrap())):e instanceof ut?ut.create(e.items.map(t=>Cr(t))):e}function xl(e,t){let n=dt(e),r=dt(t);if(e===t)return{valid:!0,data:e};if(n===N.object&&r===N.object){let o=G.objectKeys(t),i=G.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(let c of i){let l=xl(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===N.array&&r===N.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let a=e[i],c=t[i],l=xl(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===N.date&&r===N.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function dh(e,t){return new Pn({values:e,typeName:L.ZodEnum,...j(t)})}function sh(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function uh(e,t={},n){return e?Wt.create().superRefine((r,o)=>{let i=e(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=sh(t,r),l=c.fatal??n??!0;o.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=sh(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}}):Wt.create()}var Ge,ih,B,QC,eT,tT,nT,rT,oT,iT,sT,aT,kl,cT,lT,dT,uT,pT,fT,ah,mT,Gt,Sn,En,Rn,Cn,Tr,Tn,An,Wt,Rt,et,Ar,Ct,Ie,In,Et,bs,Nn,ut,ws,Ir,Nr,vs,On,Dn,Pn,Mn,Vt,We,Ke,pt,$n,Ln,Or,wT,Mo,$o,Fn,vT,L,kT,ph,fh,xT,ST,mh,ET,RT,CT,TT,AT,IT,NT,OT,DT,PT,MT,$T,LT,FT,jT,HT,UT,BT,KT,GT,WT,VT,qT,zT,JT,YT,XT,ZT,QT,eA,tA,nA,rA,oA,hh=w(()=>{hs();gs();oh();vl();Do();Ge=class{static{s(this,"ParseInputLazyPath")}constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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}},ih=s((e,t)=>{if(Kt(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 Ae(e.common.issues);return this._error=n,this._error}}},"handleResult");s(j,"processCreateParams");B=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return dt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:dt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ue,ctx:{common:t.parent.common,data:t.data,parsedType:dt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Rr(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:dt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ih(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Kt(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=>Kt(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:dt(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(Rr(o)?o:Promise.resolve(o));return ih(r,i)}refine(t,n){let r=s(o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n,"getIssueProperties");return this._refinement((o,i)=>{let a=t(o),c=s(()=>i.addIssue({code:C.custom,...r(o)}),"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,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new We({schema:this,typeName:L.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 Ke.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ct.create(this)}promise(){return Vt.create(this,this._def)}or(t){return In.create([this,t],this._def)}and(t){return Nn.create(this,t,this._def)}transform(t){return new We({...j(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new $n({...j(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new Mo({typeName:L.ZodBranded,type:this,...j(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ln({...j(this._def),innerType:this,catchValue:n,typeName:L.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return $o.create(this,t)}readonly(){return Fn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},QC=/^c[^\s-]{8,}$/i,eT=/^[0-9a-z]+$/,tT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nT=/^[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,rT=/^[a-z0-9_-]{21}$/i,oT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,iT=/^[-+]?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)?)??$/,sT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cT=/^(?:(?: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])$/,lT=/^(?:(?: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])$/,dT=/^(([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]))$/,uT=/^(([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])$/,pT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ah="((\\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])))",mT=new RegExp(`^${ah}$`);s(ch,"timeRegexSource");s(hT,"timeRegex");s(lh,"datetimeRegex");s(gT,"isValidIP");s(yT,"isValidJWT");s(_T,"isValidCidr");Gt=class e extends B{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==N.string){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_type,expected:N.string,received:i.parsedType}),M}let r=new ue,o;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?A(o,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&A(o,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")sT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"email",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")kl||(kl=new RegExp(aT,"u")),kl.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"emoji",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")nT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"uuid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")rT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"nanoid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")QC.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"cuid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")eT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"cuid2",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")tT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"ulid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),A(o,{validation:"url",code:C.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"regex",code:C.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?lh(i).test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?mT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?hT(i).test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?iT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"duration",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?gT(t.data,i.version)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"ip",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?yT(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"jwt",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?_T(t.data,i.version)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"cidr",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?pT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"base64",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?fT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"base64url",code:C.invalid_string,message:i.message}),r.dirty()):G.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:C.invalid_string,...O.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...O.errToObj(t)})}url(t){return this._addCheck({kind:"url",...O.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...O.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...O.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...O.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...O.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...O.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...O.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...O.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...O.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...O.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...O.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...O.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...O.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...O.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...O.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...O.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...O.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...O.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...O.errToObj(n)})}nonempty(t){return this.min(1,O.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}};Gt.create=e=>new Gt({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...j(e)});s(bT,"floatSafeRemainder");Sn=class e extends B{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)!==N.number){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_type,expected:N.number,received:i.parsedType}),M}let r,o=new ue;for(let i of this._def.checks)i.kind==="int"?G.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:C.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?bT(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:C.not_finite,message:i.message}),o.dirty()):G.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:O.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:O.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.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"&&G.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)}};Sn.create=e=>new Sn({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...j(e)});En=class e extends B{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)!==N.bigint)return this._getInvalidInput(t);let r,o=new ue;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):G.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return A(n,{code:C.invalid_type,expected:N.bigint,received:n.parsedType}),M}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(o)}]})}_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:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.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}};En.create=e=>new En({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...j(e)});Rn=class extends B{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==N.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.boolean,received:r.parsedType}),M}return ye(t.data)}};Rn.create=e=>new Rn({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...j(e)});Cn=class e extends B{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==N.date){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_type,expected:N.date,received:i.parsedType}),M}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_date}),M}let r=new ue,o;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):G.assertNever(i);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:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.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:L.ZodDate,...j(e)});Tr=class extends B{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==N.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.symbol,received:r.parsedType}),M}return ye(t.data)}};Tr.create=e=>new Tr({typeName:L.ZodSymbol,...j(e)});Tn=class extends B{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==N.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.undefined,received:r.parsedType}),M}return ye(t.data)}};Tn.create=e=>new Tn({typeName:L.ZodUndefined,...j(e)});An=class extends B{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==N.null){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.null,received:r.parsedType}),M}return ye(t.data)}};An.create=e=>new An({typeName:L.ZodNull,...j(e)});Wt=class extends B{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ye(t.data)}};Wt.create=e=>new Wt({typeName:L.ZodAny,...j(e)});Rt=class extends B{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ye(t.data)}};Rt.create=e=>new Rt({typeName:L.ZodUnknown,...j(e)});et=class extends B{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:C.invalid_type,expected:N.never,received:n.parsedType}),M}};et.create=e=>new et({typeName:L.ZodNever,...j(e)});Ar=class extends B{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==N.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.void,received:r.parsedType}),M}return ye(t.data)}};Ar.create=e=>new Ar({typeName:L.ZodVoid,...j(e)});Ct=class e extends B{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==N.array)return A(n,{code:C.invalid_type,expected:N.array,received:n.parsedType}),M;if(o.exactLength!==null){let a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(A(n,{code:a?C.too_big:C.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(A(n,{code:C.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(A(n,{code:C.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new Ge(n,a,n.path,c)))).then(a=>ue.mergeArray(r,a));let i=[...n.data].map((a,c)=>o.type._parseSync(new Ge(n,a,n.path,c)));return ue.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:O.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:O.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:O.toString(n)}})}nonempty(t){return this.min(1,t)}};Ct.create=(e,t)=>new Ct({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...j(t)});s(Cr,"deepPartialify");Ie=class e extends B{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=G.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==N.object){let d=this._getOrReturnCtx(t);return A(d,{code:C.invalid_type,expected:N.object,received:d.parsedType}),M}let{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof et&&this._def.unknownKeys==="strip"))for(let d in o.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=i[d],p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Ge(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof et){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(A(o,{code:C.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=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Ge(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.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=>ue.mergeObjectSync(r,d)):ue.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return O.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:s((n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:O.errToObj(t).message??o}:{message:o}},"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:L.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 G.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 G.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 G.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of G.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ke;)i=i._def.innerType;n[r]=i}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return dh(G.objectKeys(this.shape))}};Ie.create=(e,t)=>new Ie({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:et.create(),typeName:L.ZodObject,...j(t)});Ie.strictCreate=(e,t)=>new Ie({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:et.create(),typeName:L.ZodObject,...j(t)});Ie.lazycreate=(e,t)=>new Ie({shape:e,unknownKeys:"strip",catchall:et.create(),typeName:L.ZodObject,...j(t)});In=class extends B{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new Ae(c.ctx.common.issues));return A(n,{code:C.invalid_union,unionErrors:a}),M}if(s(o,"handleResults"),n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let i,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"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new Ae(l));return A(n,{code:C.invalid_union,unionErrors:c}),M}}get options(){return this._def.options}};In.create=(e,t)=>new In({options:e,typeName:L.ZodUnion,...j(t)});Et=s(e=>e instanceof On?Et(e.schema):e instanceof We?Et(e.innerType()):e instanceof Dn?[e.value]:e instanceof Pn?e.options:e instanceof Mn?G.objectValues(e.enum):e instanceof $n?Et(e._def.innerType):e instanceof Tn?[void 0]:e instanceof An?[null]:e instanceof Ke?[void 0,...Et(e.unwrap())]:e instanceof pt?[null,...Et(e.unwrap())]:e instanceof Mo||e instanceof Fn?Et(e.unwrap()):e instanceof Ln?Et(e._def.innerType):[],"getDiscriminator"),bs=class e extends B{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==N.object)return A(n,{code:C.invalid_type,expected:N.object,received:n.parsedType}),M;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let i of n){let a=Et(i.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(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,i)}}return new e({typeName:L.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...j(r)})}};s(xl,"mergeValues");Nn=class extends B{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=s((i,a)=>{if(ys(i)||ys(a))return M;let c=xl(i.value,a.value);return c.valid?((_s(i)||_s(a))&&n.dirty(),{status:n.value,value:c.data}):(A(r,{code:C.invalid_intersection_types}),M)},"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(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Nn.create=(e,t,n)=>new Nn({left:e,right:t,typeName:L.ZodIntersection,...j(n)});ut=class e extends B{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==N.array)return A(r,{code:C.invalid_type,expected:N.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return A(r,{code:C.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:C.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Ge(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>ue.mergeArray(n,a)):ue.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ut.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ut({items:e,typeName:L.ZodTuple,rest:null,...j(t)})};ws=class e extends B{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!==N.object)return A(r,{code:C.invalid_type,expected:N.object,received:r.parsedType}),M;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)o.push({key:i._parse(new Ge(r,c,r.path,c)),value:a._parse(new Ge(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ue.mergeObjectAsync(n,o):ue.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof B?new e({keyType:t,valueType:n,typeName:L.ZodRecord,...j(r)}):new e({keyType:Gt.create(),valueType:t,typeName:L.ZodRecord,...j(n)})}},Ir=class extends B{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!==N.map)return A(r,{code:C.invalid_type,expected:N.map,received:r.parsedType}),M;let o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new Ge(r,c,r.path,[d,"key"])),value:i._parse(new Ge(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 M;(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 M;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};Ir.create=(e,t,n)=>new Ir({valueType:t,keyType:e,typeName:L.ZodMap,...j(n)});Nr=class e extends B{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==N.set)return A(r,{code:C.invalid_type,expected:N.set,received:r.parsedType}),M;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(A(r,{code:C.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(A(r,{code:C.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return M;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)=>i._parse(new Ge(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:O.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:O.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:L.ZodSet,...j(t)});vs=class e extends B{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==N.function)return A(n,{code:C.invalid_type,expected:N.function,received:n.parsedType}),M;function r(c,l){return Po({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Er(),St].filter(d=>!!d),issueData:{code:C.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function o(c,l){return Po({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Er(),St].filter(d=>!!d),issueData:{code:C.invalid_return_type,returnTypeError:l}})}s(o,"makeReturnsIssue");let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Vt){let c=this;return ye(async function(...l){let d=new Ae([]),u=await c._def.args.parseAsync(l,i).catch(h=>{throw d.addIssue(r(l,h)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw d.addIssue(o(p,h)),d})})}else{let c=this;return ye(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new Ae([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,i);if(!p.success)throw new Ae([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ut.create(t).rest(Rt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||ut.create([]).rest(Rt.create()),returns:n||Rt.create(),typeName:L.ZodFunction,...j(r)})}},On=class extends B{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})}};On.create=(e,t)=>new On({getter:e,typeName:L.ZodLazy,...j(t)});Dn=class extends B{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(n,{received:n.data,code:C.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:t.data}}get value(){return this._def.value}};Dn.create=(e,t)=>new Dn({value:e,typeName:L.ZodLiteral,...j(t)});s(dh,"createZodEnum");Pn=class e extends B{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{expected:G.joinValues(r),received:n.parsedType,code:C.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{received:n.data,code:C.invalid_enum_value,options:r}),M}return ye(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})}};Pn.create=dh;Mn=class extends B{static{s(this,"ZodNativeEnum")}_parse(t){let n=G.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==N.string&&r.parsedType!==N.number){let o=G.objectValues(n);return A(r,{expected:G.joinValues(o),received:r.parsedType,code:C.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=G.objectValues(n);return A(r,{received:r.data,code:C.invalid_enum_value,options:o}),M}return ye(t.data)}get enum(){return this._def.values}};Mn.create=(e,t)=>new Mn({values:e,typeName:L.ZodNativeEnum,...j(t)});Vt=class extends B{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==N.promise&&n.common.async===!1)return A(n,{code:C.invalid_type,expected:N.promise,received:n.parsedType}),M;let r=n.parsedType===N.promise?n.data:Promise.resolve(n.data);return ye(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Vt.create=(e,t)=>new Vt({type:e,typeName:L.ZodPromise,...j(t)});We=class extends B{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s(a=>{A(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?xn(l.value):n.value==="dirty"?xn(l.value):l});{if(n.value==="aborted")return M;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?M:c.status==="dirty"?xn(c.value):n.value==="dirty"?xn(c.value):c}}if(o.type==="refinement"){let a=s(c=>{let l=o.refinement(c,i);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"?M:(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"?M:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Kt(a))return M;let c=o.transform(a.value,i);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=>Kt(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:n.value,value:c})):M);G.assertNever(o)}};We.create=(e,t,n)=>new We({schema:e,typeName:L.ZodEffects,effect:t,...j(n)});We.createWithPreprocess=(e,t,n)=>new We({schema:t,effect:{type:"preprocess",transform:e},typeName:L.ZodEffects,...j(n)});Ke=class extends B{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===N.undefined?ye(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ke.create=(e,t)=>new Ke({innerType:e,typeName:L.ZodOptional,...j(t)});pt=class extends B{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===N.null?ye(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:L.ZodNullable,...j(t)});$n=class extends B{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===N.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$n.create=(e,t)=>new $n({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...j(t)});Ln=class extends B{static{s(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Rr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ln.create=(e,t)=>new Ln({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...j(t)});Or=class extends B{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==N.nan){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.nan,received:r.parsedType}),M}return{status:"valid",value:t.data}}};Or.create=e=>new Or({typeName:L.ZodNaN,...j(e)});wT=Symbol("zod_brand"),Mo=class extends B{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}},$o=class e extends B{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),xn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:L.ZodPipeline})}},Fn=class extends B{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(o=>(Kt(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return Rr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Fn.create=(e,t)=>new Fn({innerType:e,typeName:L.ZodReadonly,...j(t)});s(sh,"cleanParams");s(uh,"custom");vT={object:Ie.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"})(L||(L={}));kT=s((e,t={message:`Input not instance of ${e.name}`})=>uh(n=>n instanceof e,t),"instanceOfType"),ph=Gt.create,fh=Sn.create,xT=Or.create,ST=En.create,mh=Rn.create,ET=Cn.create,RT=Tr.create,CT=Tn.create,TT=An.create,AT=Wt.create,IT=Rt.create,NT=et.create,OT=Ar.create,DT=Ct.create,PT=Ie.create,MT=Ie.strictCreate,$T=In.create,LT=bs.create,FT=Nn.create,jT=ut.create,HT=ws.create,UT=Ir.create,BT=Nr.create,KT=vs.create,GT=On.create,WT=Dn.create,VT=Pn.create,qT=Mn.create,zT=Vt.create,JT=We.create,YT=Ke.create,XT=pt.create,ZT=We.createWithPreprocess,QT=$o.create,eA=s(()=>ph().optional(),"ostring"),tA=s(()=>fh().optional(),"onumber"),nA=s(()=>mh().optional(),"oboolean"),rA={string:s(e=>Gt.create({...e,coerce:!0}),"string"),number:s(e=>Sn.create({...e,coerce:!0}),"number"),boolean:s(e=>Rn.create({...e,coerce:!0}),"boolean"),bigint:s(e=>En.create({...e,coerce:!0}),"bigint"),date:s(e=>Cn.create({...e,coerce:!0}),"date")},oA=M});var m={};Z(m,{BRAND:()=>wT,DIRTY:()=>xn,EMPTY_PATH:()=>ZC,INVALID:()=>M,NEVER:()=>oA,OK:()=>ye,ParseStatus:()=>ue,Schema:()=>B,ZodAny:()=>Wt,ZodArray:()=>Ct,ZodBigInt:()=>En,ZodBoolean:()=>Rn,ZodBranded:()=>Mo,ZodCatch:()=>Ln,ZodDate:()=>Cn,ZodDefault:()=>$n,ZodDiscriminatedUnion:()=>bs,ZodEffects:()=>We,ZodEnum:()=>Pn,ZodError:()=>Ae,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>vs,ZodIntersection:()=>Nn,ZodIssueCode:()=>C,ZodLazy:()=>On,ZodLiteral:()=>Dn,ZodMap:()=>Ir,ZodNaN:()=>Or,ZodNativeEnum:()=>Mn,ZodNever:()=>et,ZodNull:()=>An,ZodNullable:()=>pt,ZodNumber:()=>Sn,ZodObject:()=>Ie,ZodOptional:()=>Ke,ZodParsedType:()=>N,ZodPipeline:()=>$o,ZodPromise:()=>Vt,ZodReadonly:()=>Fn,ZodRecord:()=>ws,ZodSchema:()=>B,ZodSet:()=>Nr,ZodString:()=>Gt,ZodSymbol:()=>Tr,ZodTransformer:()=>We,ZodTuple:()=>ut,ZodType:()=>B,ZodUndefined:()=>Tn,ZodUnion:()=>In,ZodUnknown:()=>Rt,ZodVoid:()=>Ar,addIssueToContext:()=>A,any:()=>AT,array:()=>DT,bigint:()=>ST,boolean:()=>mh,coerce:()=>rA,custom:()=>uh,date:()=>ET,datetimeRegex:()=>lh,defaultErrorMap:()=>St,discriminatedUnion:()=>LT,effect:()=>JT,enum:()=>VT,function:()=>KT,getErrorMap:()=>Er,getParsedType:()=>dt,instanceof:()=>kT,intersection:()=>FT,isAborted:()=>ys,isAsync:()=>Rr,isDirty:()=>_s,isValid:()=>Kt,late:()=>vT,lazy:()=>GT,literal:()=>WT,makeIssue:()=>Po,map:()=>UT,nan:()=>xT,nativeEnum:()=>qT,never:()=>NT,null:()=>TT,nullable:()=>XT,number:()=>fh,object:()=>PT,objectUtil:()=>bl,oboolean:()=>nA,onumber:()=>tA,optional:()=>YT,ostring:()=>eA,pipeline:()=>QT,preprocess:()=>ZT,promise:()=>zT,quotelessJson:()=>JC,record:()=>HT,set:()=>BT,setErrorMap:()=>XC,strictObject:()=>MT,string:()=>ph,symbol:()=>RT,transformer:()=>JT,tuple:()=>jT,undefined:()=>CT,union:()=>$T,unknown:()=>IT,util:()=>G,void:()=>OT});var Sl=w(()=>{gs();vl();rh();Do();hh();hs()});var _e=w(()=>{Sl();Sl()});var El,Rl=w(()=>{"use strict";_e();El=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 iA,gh=w(()=>{"use strict";_e();Rl();iA=El.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 yh,_h,bh,wh,Cl,vh,kh,xh,sA,Sh=w(()=>{"use strict";_e();yh=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],_h=m.enum(yh),bh=["new_to_ai_agents","new_to_this_client","experienced"],wh=m.enum(bh),Cl=[{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"}],vh=Cl.map(e=>e.header),kh=m.object({experience_level:m.array(wh).default([]),stack_filters:m.array(m.string()).default([])}).default({experience_level:[],stack_filters:[]}),xh=m.object({id:m.string().min(1),client:_h,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:kh,version:m.number().int().min(1).default(1),changelog:m.string().max(500).optional()}),sA=xh.extend({body:m.string().min(1)})});var Rh,ks,Ch,xs,aA,cA,Th,Ah,Ih,Nh,Ss,lA,dA,Eh,uA,Oh,pA,Dh=w(()=>{"use strict";_e();Rh=["operating_procedure","code_review","communication_style"],ks=m.enum(Rh),Ch=["info","recommended","required"],xs=m.enum(Ch),aA=["optional","default_on","mandatory"],cA=m.enum(aA),Th=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Ah=m.enum(Th),Ih=["verify","contribute","mixed"],Nh=m.enum(Ih),Ss=m.object({clients:m.array(Ah).default([]),stacks:m.array(m.string()).default([]),intents:m.array(Nh).default([])}).default({clients:[],stacks:[],intents:[]}),lA=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,dA=64,Eh=200,uA=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")),Oh=m.object({id:m.string().min(5).max(dA).regex(lA,"id must match conv_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),scope:ks,version:m.number().int().min(1),changed_at:uA,changelog:m.string().max(500).optional(),applies_to:Ss,severity:xs.default("recommended"),disableability:cA.default("default_on"),summary:m.string().min(1).max(Eh,`summary must be \u2264 ${Eh} 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()}),pA=Oh.extend({body:m.string().min(1)})});var qt=w(()=>{"use strict";Rl();gh();Sh();Dh()});var Tl,Es,Al,Ph,Mh,$h,fA,Lh=w(()=>{"use strict";_e();Tl=m.object({type:m.literal("text"),md:m.string().min(1).max(2e4)}),Es=m.number().min(0).max(1).optional(),Al=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:Es,right:Es,bottom:Es,left:Es}).optional()}),Ph=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")}),Mh=m.object({type:m.literal("accordion"),title:m.string().min(1).max(200),subtag:Ph.optional(),blocks:m.array(m.discriminatedUnion("type",[Tl,Al])).max(50)}),$h=m.discriminatedUnion("type",[Tl,Al,Mh]),fA=m.array($h).max(100)});var Fh,mA,jh,Hh,hA,gA,yA,Uh=w(()=>{"use strict";_e();Fh=["free","solo_pro","team","enterprise"],mA=m.enum(Fh),jh=["solo_pro","team","enterprise"],Hh=m.enum(jh),hA=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),gA=m.object({user_id:m.string().uuid(),tier:Hh,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:hA.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"}),yA=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Bh=w(()=>{"use strict"});var _A,bA,wA,Kh=w(()=>{"use strict";_e();_A=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),bA=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:_A.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"}),wA=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Gh,vA,Wh,Vh,qh,zh,kA,Jh=w(()=>{"use strict";_e();Gh=m.enum(["info","important","critical"]),vA=m.enum(["pass","warn","fail"]),Wh=m.object({type:m.enum(["template","lesson"]),id:m.string().min(1)}),Vh=m.object({languages:m.array(m.string()).optional(),tools:m.array(m.string()).optional()}).optional(),qh=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")})]),zh=m.object({id:m.string().min(1),title:m.string().min(1),severity:Gh,weight:m.number().int().positive().max(100),applies_when:Vh,check:qh,fail_message:m.string().min(1),warn_message:m.string().optional(),remediation:Wh.optional()}),kA=m.object({version:m.literal(1),checks:m.array(zh).min(1)})});function SA(e){if(!xA.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Rs(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 EA(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var xA,Cs,Yh,Xh,ft,Il,Zh,RA,Qh=w(()=>{"use strict";_e();xA=/^\d{4}-\d{2}-\d{2}$/;s(SA,"isRealDate");Cs=m.string().refine(SA,{message:"expected a real calendar date as YYYY-MM-DD"}),Yh=["exact","prefix"],Xh=m.enum(Yh),ft=m.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Il=[2e5,272e3],Zh=m.object({model_pattern:m.string().min(1).max(100),match_kind:Xh,valid_from:Cs,valid_to:Cs.nullable().optional(),input:ft,output:ft,cache_read:ft,cache_write_5m:ft,cache_write_1h:ft,long_context:m.enum(["same_price","tiered"]).optional(),input_above_200k:ft.optional(),output_above_200k:ft.optional(),cache_read_above_200k:ft.optional(),cache_write_5m_above_200k:ft.optional(),cache_write_1h_above_200k:ft.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=>Rs(e)===0||Rs(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"||Rs(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=>Rs(e)===0||e.context_threshold_tokens==null||Il.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Il.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Rs,"aboveRateCount");s(EA,"rowKey");RA=m.object({changelog:m.string().min(1).max(500),as_of:Cs,source_url:m.string().url().max(500),rows:m.array(Zh).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((o,i)=>{let a=EA(o),c=n.get(a);c!==void 0?t.addIssue({code:m.ZodIssueCode.custom,path:["rows",i],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,i)});let r=new Map;e.rows.forEach((o,i)=>{let a=`${o.model_pattern}|${o.match_kind}`,c=r.get(a)??[];c.push({i,r:o}),r.set(a,c)});for(let o of r.values())if(!(o.length<2)){o.sort((i,a)=>i.r.valid_from.localeCompare(a.r.valid_from));for(let i=0;i<o.length-1;i++){let a=o[i],c=o[i+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 Dr=w(()=>{"use strict"});var Lo=w(()=>{"use strict"});var rg=w(()=>{"use strict";Lo();Dr()});var og=w(()=>{"use strict";Dr()});var ig=w(()=>{"use strict";qt();Lo();Dr()});var sg=w(()=>{"use strict";Lo();Dr()});var ag=w(()=>{"use strict";Dr();rg();og();ig();sg();Lo()});var WA,VA,cg,qA,lg,Nl,dg,ug,pg,fg,zA,Ol=w(()=>{"use strict";_e();qt();WA=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,VA=64,cg=200,qA=1e3,lg=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")),Nl=m.enum(["low","medium","high"]),dg=m.object({owner:m.string().min(1).max(160).optional(),risk_level:Nl.optional(),reviewed_at:lg.optional()}).default({}),ug=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}),pg=m.object({lesson_query:ug,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:[]}),fg=m.object({id:m.string().min(6).max(VA).regex(WA,"id must match skill_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),version:m.number().int().min(1),changed_at:lg,tier:m.enum(["community","curated"]).default("curated"),summary:m.string().min(1).max(cg,`summary must be \u2264 ${cg} chars (rendered as one line in skill_index)`),description:m.string().max(qA).optional(),applies_to:Ss,membership:pg,governance:dg}),zA=fg.extend({body:m.string().default(""),org_id:m.string().uuid().optional(),org_name:m.string().optional()})});var mg,hg,gg,yg,_g,bg,JA,wg,YA,XA,vg=w(()=>{"use strict";_e();Ol();mg=m.enum(["maind","agent-skill"]),hg=m.enum(["ready","needs_attention","blocked"]),gg=m.enum(["info","important","critical"]),yg=m.enum(["pass","warn","fail"]),_g=m.enum(["structure","governance","scope","membership","package","references"]),bg=m.object({id:m.string().min(1),title:m.string().min(1),status:yg,severity:gg,category:_g,field:m.string().nullable().optional(),message:m.string().min(1),hint:m.string().optional()}),JA=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({}),wg=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(),YA=m.object({directory_name:m.string().min(1).max(120).optional(),frontmatter:wg,body:m.string().default(""),file_listing:m.array(m.string()).optional()}),XA=m.object({format:mg,subject:m.string().min(1),status:hg,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(bg),next_steps:m.array(m.string()),trust_note:m.string().min(1)})});var Dl=w(()=>{"use strict"});var kg,QA,xg,Sg,Eg,Pr,eI,Rg,Cg,Tg,Ag,Ig,Ng,Og,Dg,tI,Pg,Mg,$g,zt,Pl,Lg,Fg,nI,jg=w(()=>{"use strict";_e();qt();Dl();kg=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],QA=m.enum(kg),xg=["verdict","advisory"],Sg=m.enum(xg),Eg=["block","warn","note"],Pr=m.enum(Eg),eI=m.object({convention_id:m.string().min(1).max(64),convention_version:m.number().int().min(1),severity:xs,scope:ks,grade:Sg,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()}),Rg=["open","warn","info"],Cg=m.enum(Rg),Tg=["introduced","pre_existing"],Ag=m.enum(Tg),Ig=["full","partial","none"],Ng=m.enum(Ig),Og=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:Cg,baseline:Ag,evidence_hash:m.string().regex(/^[a-f0-9]{64}$/),count:m.number().int().min(1).max(1e5)}),Dg=m.object({version:m.literal(1).default(1),actions:m.object({required:Pr.default("block"),recommended:Pr.default("warn"),info:Pr.default("note")}).default({}),overrides:m.array(m.object({convention_id:m.string().min(1).max(64),action:Pr})).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:Pr,reason:m.string().min(1).max(200)})).max(32).optional()}),tI=Dg.parse({}),Pg=["ran","not_applicable","unavailable","ungraded"],Mg=m.enum(Pg),$g=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),state:Mg}),zt=1e3,Pl=m.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Lg=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()}),Fg=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:Ng}),nI=m.object({changed_symbols:m.array(Lg).max(zt),risk_flags:m.array(m.string().max(64)).max(16),detector_findings:m.array(Og).max(64),detector_runs:m.array($g).min(1).max(32),diff_stats:Fg,commit_sha:Pl.optional(),base_sha:Pl.optional(),merge_base_sha:Pl.optional(),dirty:m.boolean().optional(),code_index_version:m.string().min(1).max(32).optional()})});var Hg,Ug,Bg,Kg,Gg,Ml,rI,oI,Wg,Vg,qg,zg,Jg,iI,sI,Yg,Xg,Zg,aI,Qg=w(()=>{"use strict";_e();Hg=14,Ug=14,Bg=14,Kg=1,Gg=365,Ml=m.number().int().min(Kg).max(Gg),rI=["propose","direct"],oI="propose",Wg=["propose","direct"],Vg="propose",qg=["propose","direct"],zg="propose",Jg=["off","propose","direct"],iI=["member","admin","owner"],sI="member",Yg="off",Xg="en",Zg=m.object({version:m.literal(1).default(1),at_risk_days:Ml.default(Hg),stagnation_days:Ml.default(Ug),agent_date_mode:m.enum(rI).default(oI),health_manual_ttl_days:Ml.default(Bg),agent_event_mode:m.enum(Wg).default(Vg),agent_update_mode:m.enum(qg).default(zg),agent_pull_mode:m.enum(Jg).default(Yg),org_wide_authoring_min_role:m.enum(iI).default(sI),planning_language:m.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Xg)}),aI=Zg.parse({})});var ey,cI,ty=w(()=>{"use strict";_e();ey=m.object({version:m.literal(1).default(1),org_visibility:m.boolean().default(!1),session_span_visibility:m.boolean().default(!0)}),cI=ey.parse({})});var ny,ry,lI,dI,oy=w(()=>{"use strict";_e();ny=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([])}),ry=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:ny.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()}),lI=ry.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()}),dI=m.object({id:m.string().uuid(),title:m.string(),summary:m.string(),tags:m.array(m.string()).default([])})});var iy=w(()=>{"use strict"});function Ts(e){let t=[],n=null;return e.split(`
3
- `).forEach((r,o)=>{let i=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(i===""||a>n)return;n=null}if(i===""||i.startsWith("#"))return;let c=pI.exec(r);if(!c)return;let l=c[3]??"";if(uI.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:o+1,value:d})}),t}var uI,pI,sy=w(()=>{"use strict";uI=new Set(["|",">","|-",">-","|+",">+"]),pI=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(Ts,"plainScalarViolations")});function jo(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,o]=n(e),[i,a]=n(t);for(let c=0;c<Math.max(r.length,i.length);c+=1){let l=(r[c]??0)-(i[c]??0);if(l!==0)return l<0?-1:1}if(o.length===0&&a.length===0)return 0;if(o.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(o.length,a.length);c+=1){let l=o[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 ay=w(()=>{"use strict";s(jo,"compareSemver")});var Ho=w(()=>{"use strict";qt();Lh();qt();qt();Uh();Bh();Kh();Jh();Qh();ag();qt();Ol();vg();jg();Qg();ty();oy();iy();Dl();sy();ay()});function cy(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
- `).slice(0,1e3)}var ly=w(()=>{"use strict";s(cy,"nodeEmbedText")});var $l,Ll=w(()=>{"use strict";$l=["function","method","class","interface","enum","type_alias"]});function dy(e,t){let n=Math.min(e.length,t.length),r=0,o=0,i=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,o+=c*c,i+=l*l}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var uy=w(()=>{"use strict";s(dy,"cosineSimilarity")});import{execFileSync as fI}from"node:child_process";import{createHash as mI}from"node:crypto";import{readFileSync as hI}from"node:fs";import{posix as tt}from"node:path";function py(e){let t=mI("sha256"),n=[];try{n=fI("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(l=>gI.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,o=s(l=>{if(r.has(l))return r.get(l);try{let d=hI(tt.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),i=[],a=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=fy(l,o,0),u=tt.dirname(l)==="."?"":tt.dirname(l);l.endsWith("tsconfig.json")&&a.set(u,d),d.paths&&i.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=my(o(l));if(!d||typeof d.name!="string")continue;let u=tt.dirname(l)==="."?"":tt.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:i},fingerprint:t.digest("hex")}}function fy(e,t,n){let r=my(t(e));if(!r)return{};let o=tt.dirname(e)==="."?"":tt.dirname(e),i={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=tt.normalize(tt.join(o,a.endsWith(".json")?a:a+".json"));i=fy(d,t,n+1)}let c=r.compilerOptions??{},l={...i};return typeof c.outDir=="string"&&(l.outDir=tt.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=tt.normalize(c.rootDir)),c.paths&&typeof c.paths=="object"&&(l.paths=c.paths,l.pathsDir=o,l.baseUrl=typeof c.baseUrl=="string"?c.baseUrl:void 0),l}function my(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(n){t+=o,o==="\\"?t+=e[++r]??"":o==='"'&&(n=!1);continue}if(o==='"')n=!0,t+=o;else if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
2
+ var Um=Object.defineProperty;var s=(e,t)=>Um(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var Z=(e,t)=>{for(var n in t)Um(e,n,{get:t[n],enumerable:!0})};import{homedir as DC}from"node:os";import{join as PC}from"node:path";function us(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=No(r.id),i=No(r.key),a=No(r.title),c=No(r.status);if(!o||!i||!a||!c)continue;let l=r.here===!1?!1:void 0,d=No(r.where);if(t.push({id:o,key:i,title:a,status:c,...l===!1?{here:l}:{},...d?{where:d}:{}}),t.length>=MC)break}return t}function ul(e){if(e.length===0)return null;let t=e.map(r=>`${r.key} "${r.title}"${r.status==="warn"?" (blocked)":""}`+(r.here===!1?` (in ${r.where?`${r.where}/`:"a repository below this one"})`:"")).join(", "),n=e.length===1;return`Assigned to your user 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 Bm(e=DC()){return PC(e,".maind","assigned-told")}function Km(e,t){if(!e||typeof e!="object")return e;let n=e;return Array.isArray(n.assigned_to_you)?{...n,assigned_to_you:n.assigned_to_you.map(r=>{if(!r||typeof r!="object")return r;let o=r;if(o.here!==!1||typeof o.project_key!="string")return r;let i=t(o.project_key);return i?{...o,where:i}:r})}:e}function Gm(e){return e==="claude-code"}var MC,No,ds,Oo=w(()=>{"use strict";MC=5,No=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(us,"parseAssignedList");s(ul,"assignedNoticeText");s(Bm,"assignedToldDir");ds=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=us(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 ul(t)}};s(Km,"labelNestedItems");s(Gm,"clientHasHooks")});function zm(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,o=typeof n.method=="string"?n.method:void 0;if(o!==void 0){let i={kind:r!==void 0?"request":"notification",method:o,id:r};if(o==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(i.toolName=c)}}return i}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function xr(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 ml(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function hl(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function gl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var yl=w(()=>{"use strict";s(zm,"parseFrame");s(xr,"denyResult");s(ml,"toolEvent");s(hl,"policyEvent");s(gl,"shaEvent")});import{execFileSync as Xm}from"node:child_process";function Zm(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=VC}function qC(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 o=[];for(let i of KC){let a=r[i];typeof a=="string"&&Jm.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of GC){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Jm.test(l)&&o.push({field:`${i}.${a}`,sha:l})}return o}function zC(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,Ym);for(let o=Ym;o>=WC;o--){let i=r.slice(0,o),a=t(i);if(a!==null&&a.startsWith(i))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:o}}return{field:"",sha:e,verdict:"unknown"}}function Sr(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 Qm(){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 fs(e=process.cwd()){try{let n=Xm("git",["rev-parse","--show-toplevel"],{cwd:e,env:Qm(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function JC(e){return t=>{try{let r=Xm("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Qm(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function ms(e,t){if(t===null)return[];let n=qC(e);if(n.length===0)return[];let r=JC(t),o=[];for(let{field:i,sha:a}of n){let c=zC(a,r);c.verdict!=="proven"&&o.push({...c,field:i})}return o}var KC,GC,Jm,WC,Ym,VC,_l=w(()=>{"use strict";KC=["commit_sha","base_sha","head_sha"],GC=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Jm=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,WC=7,Ym=12,VC=10;s(Zm,"isDenyGrade");s(qC,"extractShaArgs");s(zC,"classifySha");s(Sr,"shaFindingText");s(Qm,"cleanGitEnv");s(fs,"resolveRepoRootForSha");s(JC,"gitShaResolver");s(ms,"inspectLineForShas")});var th=w(()=>{"use strict"});var G,wl,N,dt,Do=w(()=>{(function(e){e.assertEqual=o=>{};function t(o){}s(t,"assertIs"),e.assertIs=t;function n(o){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},e.getValidEnumValues=o=>{let i=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},e.find=(o,i)=>{for(let a of o)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(wl||(wl={}));N=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dt=s(e=>{switch(typeof e){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(e)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":return Array.isArray(e)?N.array:e===null?N.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?N.promise:typeof Map<"u"&&e instanceof Map?N.map:typeof Set<"u"&&e instanceof Set?N.set:typeof Date<"u"&&e instanceof Date?N.date:N.object;default:return N.unknown}},"getParsedType")});var C,YC,Ae,hs=w(()=>{Do();C=G.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"]),YC=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),Ae=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(i){return i.message},r={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(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 o(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,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ae.create=e=>new Ae(e)});var XC,St,vl=w(()=>{hs();Do();XC=s((e,t)=>{let n;switch(e.code){case C.invalid_type:e.received===N.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case C.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,G.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:n=`Unrecognized key(s) in object: ${G.joinValues(e.keys,", ")}`;break;case C.invalid_union:n="Invalid input";break;case C.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${G.joinValues(e.options)}`;break;case C.invalid_enum_value:n=`Invalid enum value. Expected ${G.joinValues(e.options)}, received '${e.received}'`;break;case C.invalid_arguments:n="Invalid function arguments";break;case C.invalid_return_type:n="Invalid function return type";break;case C.invalid_date:n="Invalid date";break;case C.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}"`:G.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case C.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 C.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 C.custom:n="Invalid input";break;case C.invalid_intersection_types:n="Intersection results could not be merged";break;case C.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case C.not_finite:n="Number must be finite";break;default:n=t.defaultError,G.assertNever(e)}return{message:n}},"errorMap"),St=XC});function ZC(e){nh=e}function Er(){return nh}var nh,gs=w(()=>{vl();nh=St;s(ZC,"setErrorMap");s(Er,"getErrorMap")});function A(e,t){let n=Er(),r=Po({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===St?void 0:St].filter(o=>!!o)});e.common.issues.push(r)}var Po,QC,ue,M,xn,ye,ys,_s,Gt,Rr,kl=w(()=>{gs();vl();Po=s(e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:i,message:c}},"makeIssue"),QC=[];s(A,"addIssueToContext");ue=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 o of n){if(o.status==="aborted")return M;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let i=await o.key,a=await o.value;r.push({key:i,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return M;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}},M=Object.freeze({status:"aborted"}),xn=s(e=>({status:"dirty",value:e}),"DIRTY"),ye=s(e=>({status:"valid",value:e}),"OK"),ys=s(e=>e.status==="aborted","isAborted"),_s=s(e=>e.status==="dirty","isDirty"),Gt=s(e=>e.status==="valid","isValid"),Rr=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var rh=w(()=>{});var O,oh=w(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}))});function j(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{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:o}}function ch(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 gT(e){return new RegExp(`^${ch(e)}$`)}function lh(e){let t=`${ah}T${ch(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 yT(e,t){return!!((t==="v4"||!t)&&lT.test(e)||(t==="v6"||!t)&&uT.test(e))}function _T(e,t){if(!iT.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,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function bT(e,t){return!!((t==="v4"||!t)&&dT.test(e)||(t==="v6"||!t)&&pT.test(e))}function wT(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return i%a/10**o}function Cr(e){if(e instanceof Ie){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ke.create(Cr(r))}return new Ie({...e._def,shape:s(()=>t,"shape")})}else return e instanceof Ct?new Ct({...e._def,type:Cr(e.element)}):e instanceof Ke?Ke.create(Cr(e.unwrap())):e instanceof pt?pt.create(Cr(e.unwrap())):e instanceof ut?ut.create(e.items.map(t=>Cr(t))):e}function Sl(e,t){let n=dt(e),r=dt(t);if(e===t)return{valid:!0,data:e};if(n===N.object&&r===N.object){let o=G.objectKeys(t),i=G.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(let c of i){let l=Sl(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===N.array&&r===N.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let a=e[i],c=t[i],l=Sl(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===N.date&&r===N.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function dh(e,t){return new Pn({values:e,typeName:L.ZodEnum,...j(t)})}function sh(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function uh(e,t={},n){return e?Vt.create().superRefine((r,o)=>{let i=e(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=sh(t,r),l=c.fatal??n??!0;o.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=sh(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}}):Vt.create()}var Ge,ih,B,eT,tT,nT,rT,oT,iT,sT,aT,cT,xl,lT,dT,uT,pT,fT,mT,ah,hT,Wt,Sn,En,Rn,Cn,Tr,Tn,An,Vt,Rt,et,Ar,Ct,Ie,In,Et,bs,Nn,ut,ws,Ir,Nr,vs,On,Dn,Pn,Mn,qt,We,Ke,pt,$n,Ln,Or,vT,Mo,$o,Fn,kT,L,xT,ph,fh,ST,ET,mh,RT,CT,TT,AT,IT,NT,OT,DT,PT,MT,$T,LT,FT,jT,HT,UT,BT,KT,GT,WT,VT,qT,zT,JT,YT,XT,ZT,QT,eA,tA,nA,rA,oA,iA,hh=w(()=>{hs();gs();oh();kl();Do();Ge=class{static{s(this,"ParseInputLazyPath")}constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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}},ih=s((e,t)=>{if(Gt(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 Ae(e.common.issues);return this._error=n,this._error}}},"handleResult");s(j,"processCreateParams");B=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return dt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:dt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ue,ctx:{common:t.parent.common,data:t.data,parsedType:dt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Rr(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:dt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ih(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Gt(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=>Gt(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:dt(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(Rr(o)?o:Promise.resolve(o));return ih(r,i)}refine(t,n){let r=s(o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n,"getIssueProperties");return this._refinement((o,i)=>{let a=t(o),c=s(()=>i.addIssue({code:C.custom,...r(o)}),"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,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new We({schema:this,typeName:L.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 Ke.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ct.create(this)}promise(){return qt.create(this,this._def)}or(t){return In.create([this,t],this._def)}and(t){return Nn.create(this,t,this._def)}transform(t){return new We({...j(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new $n({...j(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new Mo({typeName:L.ZodBranded,type:this,...j(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ln({...j(this._def),innerType:this,catchValue:n,typeName:L.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return $o.create(this,t)}readonly(){return Fn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eT=/^c[^\s-]{8,}$/i,tT=/^[0-9a-z]+$/,nT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rT=/^[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,oT=/^[a-z0-9_-]{21}$/i,iT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sT=/^[-+]?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)?)??$/,aT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lT=/^(?:(?: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])$/,dT=/^(?:(?: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])$/,uT=/^(([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]))$/,pT=/^(([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])$/,fT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ah="((\\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])))",hT=new RegExp(`^${ah}$`);s(ch,"timeRegexSource");s(gT,"timeRegex");s(lh,"datetimeRegex");s(yT,"isValidIP");s(_T,"isValidJWT");s(bT,"isValidCidr");Wt=class e extends B{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==N.string){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_type,expected:N.string,received:i.parsedType}),M}let r=new ue,o;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?A(o,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&A(o,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")aT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"email",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")xl||(xl=new RegExp(cT,"u")),xl.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"emoji",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")rT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"uuid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")oT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"nanoid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")eT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"cuid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")tT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"cuid2",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")nT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"ulid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),A(o,{validation:"url",code:C.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"regex",code:C.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?lh(i).test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?hT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?gT(i).test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?sT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"duration",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?yT(t.data,i.version)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"ip",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?_T(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"jwt",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?bT(t.data,i.version)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"cidr",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?fT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"base64",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?mT.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"base64url",code:C.invalid_string,message:i.message}),r.dirty()):G.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:C.invalid_string,...O.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...O.errToObj(t)})}url(t){return this._addCheck({kind:"url",...O.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...O.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...O.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...O.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...O.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...O.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...O.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...O.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...O.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...O.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...O.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...O.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...O.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...O.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...O.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...O.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...O.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...O.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...O.errToObj(n)})}nonempty(t){return this.min(1,O.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}};Wt.create=e=>new Wt({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...j(e)});s(wT,"floatSafeRemainder");Sn=class e extends B{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)!==N.number){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_type,expected:N.number,received:i.parsedType}),M}let r,o=new ue;for(let i of this._def.checks)i.kind==="int"?G.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:C.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?wT(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:C.not_finite,message:i.message}),o.dirty()):G.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:O.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:O.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.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"&&G.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)}};Sn.create=e=>new Sn({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...j(e)});En=class e extends B{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)!==N.bigint)return this._getInvalidInput(t);let r,o=new ue;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),A(r,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):G.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return A(n,{code:C.invalid_type,expected:N.bigint,received:n.parsedType}),M}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(o)}]})}_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:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.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}};En.create=e=>new En({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...j(e)});Rn=class extends B{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==N.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.boolean,received:r.parsedType}),M}return ye(t.data)}};Rn.create=e=>new Rn({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...j(e)});Cn=class e extends B{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==N.date){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_type,expected:N.date,received:i.parsedType}),M}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return A(i,{code:C.invalid_date}),M}let r=new ue,o;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),A(o,{code:C.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):G.assertNever(i);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:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.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:L.ZodDate,...j(e)});Tr=class extends B{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==N.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.symbol,received:r.parsedType}),M}return ye(t.data)}};Tr.create=e=>new Tr({typeName:L.ZodSymbol,...j(e)});Tn=class extends B{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==N.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.undefined,received:r.parsedType}),M}return ye(t.data)}};Tn.create=e=>new Tn({typeName:L.ZodUndefined,...j(e)});An=class extends B{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==N.null){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.null,received:r.parsedType}),M}return ye(t.data)}};An.create=e=>new An({typeName:L.ZodNull,...j(e)});Vt=class extends B{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ye(t.data)}};Vt.create=e=>new Vt({typeName:L.ZodAny,...j(e)});Rt=class extends B{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ye(t.data)}};Rt.create=e=>new Rt({typeName:L.ZodUnknown,...j(e)});et=class extends B{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:C.invalid_type,expected:N.never,received:n.parsedType}),M}};et.create=e=>new et({typeName:L.ZodNever,...j(e)});Ar=class extends B{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==N.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.void,received:r.parsedType}),M}return ye(t.data)}};Ar.create=e=>new Ar({typeName:L.ZodVoid,...j(e)});Ct=class e extends B{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==N.array)return A(n,{code:C.invalid_type,expected:N.array,received:n.parsedType}),M;if(o.exactLength!==null){let a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(A(n,{code:a?C.too_big:C.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(A(n,{code:C.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(A(n,{code:C.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new Ge(n,a,n.path,c)))).then(a=>ue.mergeArray(r,a));let i=[...n.data].map((a,c)=>o.type._parseSync(new Ge(n,a,n.path,c)));return ue.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:O.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:O.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:O.toString(n)}})}nonempty(t){return this.min(1,t)}};Ct.create=(e,t)=>new Ct({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...j(t)});s(Cr,"deepPartialify");Ie=class e extends B{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=G.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==N.object){let d=this._getOrReturnCtx(t);return A(d,{code:C.invalid_type,expected:N.object,received:d.parsedType}),M}let{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof et&&this._def.unknownKeys==="strip"))for(let d in o.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=i[d],p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Ge(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof et){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(A(o,{code:C.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=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Ge(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.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=>ue.mergeObjectSync(r,d)):ue.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return O.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:s((n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:O.errToObj(t).message??o}:{message:o}},"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:L.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 G.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 G.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 G.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of G.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ke;)i=i._def.innerType;n[r]=i}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return dh(G.objectKeys(this.shape))}};Ie.create=(e,t)=>new Ie({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:et.create(),typeName:L.ZodObject,...j(t)});Ie.strictCreate=(e,t)=>new Ie({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:et.create(),typeName:L.ZodObject,...j(t)});Ie.lazycreate=(e,t)=>new Ie({shape:e,unknownKeys:"strip",catchall:et.create(),typeName:L.ZodObject,...j(t)});In=class extends B{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new Ae(c.ctx.common.issues));return A(n,{code:C.invalid_union,unionErrors:a}),M}if(s(o,"handleResults"),n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let i,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"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new Ae(l));return A(n,{code:C.invalid_union,unionErrors:c}),M}}get options(){return this._def.options}};In.create=(e,t)=>new In({options:e,typeName:L.ZodUnion,...j(t)});Et=s(e=>e instanceof On?Et(e.schema):e instanceof We?Et(e.innerType()):e instanceof Dn?[e.value]:e instanceof Pn?e.options:e instanceof Mn?G.objectValues(e.enum):e instanceof $n?Et(e._def.innerType):e instanceof Tn?[void 0]:e instanceof An?[null]:e instanceof Ke?[void 0,...Et(e.unwrap())]:e instanceof pt?[null,...Et(e.unwrap())]:e instanceof Mo||e instanceof Fn?Et(e.unwrap()):e instanceof Ln?Et(e._def.innerType):[],"getDiscriminator"),bs=class e extends B{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==N.object)return A(n,{code:C.invalid_type,expected:N.object,received:n.parsedType}),M;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let i of n){let a=Et(i.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(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,i)}}return new e({typeName:L.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...j(r)})}};s(Sl,"mergeValues");Nn=class extends B{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=s((i,a)=>{if(ys(i)||ys(a))return M;let c=Sl(i.value,a.value);return c.valid?((_s(i)||_s(a))&&n.dirty(),{status:n.value,value:c.data}):(A(r,{code:C.invalid_intersection_types}),M)},"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(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Nn.create=(e,t,n)=>new Nn({left:e,right:t,typeName:L.ZodIntersection,...j(n)});ut=class e extends B{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==N.array)return A(r,{code:C.invalid_type,expected:N.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return A(r,{code:C.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:C.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Ge(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>ue.mergeArray(n,a)):ue.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ut.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ut({items:e,typeName:L.ZodTuple,rest:null,...j(t)})};ws=class e extends B{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!==N.object)return A(r,{code:C.invalid_type,expected:N.object,received:r.parsedType}),M;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)o.push({key:i._parse(new Ge(r,c,r.path,c)),value:a._parse(new Ge(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ue.mergeObjectAsync(n,o):ue.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof B?new e({keyType:t,valueType:n,typeName:L.ZodRecord,...j(r)}):new e({keyType:Wt.create(),valueType:t,typeName:L.ZodRecord,...j(n)})}},Ir=class extends B{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!==N.map)return A(r,{code:C.invalid_type,expected:N.map,received:r.parsedType}),M;let o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new Ge(r,c,r.path,[d,"key"])),value:i._parse(new Ge(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 M;(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 M;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};Ir.create=(e,t,n)=>new Ir({valueType:t,keyType:e,typeName:L.ZodMap,...j(n)});Nr=class e extends B{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==N.set)return A(r,{code:C.invalid_type,expected:N.set,received:r.parsedType}),M;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(A(r,{code:C.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(A(r,{code:C.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return M;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)=>i._parse(new Ge(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:O.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:O.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:L.ZodSet,...j(t)});vs=class e extends B{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==N.function)return A(n,{code:C.invalid_type,expected:N.function,received:n.parsedType}),M;function r(c,l){return Po({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Er(),St].filter(d=>!!d),issueData:{code:C.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function o(c,l){return Po({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Er(),St].filter(d=>!!d),issueData:{code:C.invalid_return_type,returnTypeError:l}})}s(o,"makeReturnsIssue");let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof qt){let c=this;return ye(async function(...l){let d=new Ae([]),u=await c._def.args.parseAsync(l,i).catch(h=>{throw d.addIssue(r(l,h)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw d.addIssue(o(p,h)),d})})}else{let c=this;return ye(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new Ae([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,i);if(!p.success)throw new Ae([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ut.create(t).rest(Rt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||ut.create([]).rest(Rt.create()),returns:n||Rt.create(),typeName:L.ZodFunction,...j(r)})}},On=class extends B{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})}};On.create=(e,t)=>new On({getter:e,typeName:L.ZodLazy,...j(t)});Dn=class extends B{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(n,{received:n.data,code:C.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:t.data}}get value(){return this._def.value}};Dn.create=(e,t)=>new Dn({value:e,typeName:L.ZodLiteral,...j(t)});s(dh,"createZodEnum");Pn=class e extends B{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{expected:G.joinValues(r),received:n.parsedType,code:C.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{received:n.data,code:C.invalid_enum_value,options:r}),M}return ye(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})}};Pn.create=dh;Mn=class extends B{static{s(this,"ZodNativeEnum")}_parse(t){let n=G.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==N.string&&r.parsedType!==N.number){let o=G.objectValues(n);return A(r,{expected:G.joinValues(o),received:r.parsedType,code:C.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=G.objectValues(n);return A(r,{received:r.data,code:C.invalid_enum_value,options:o}),M}return ye(t.data)}get enum(){return this._def.values}};Mn.create=(e,t)=>new Mn({values:e,typeName:L.ZodNativeEnum,...j(t)});qt=class extends B{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==N.promise&&n.common.async===!1)return A(n,{code:C.invalid_type,expected:N.promise,received:n.parsedType}),M;let r=n.parsedType===N.promise?n.data:Promise.resolve(n.data);return ye(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};qt.create=(e,t)=>new qt({type:e,typeName:L.ZodPromise,...j(t)});We=class extends B{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s(a=>{A(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?xn(l.value):n.value==="dirty"?xn(l.value):l});{if(n.value==="aborted")return M;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?M:c.status==="dirty"?xn(c.value):n.value==="dirty"?xn(c.value):c}}if(o.type==="refinement"){let a=s(c=>{let l=o.refinement(c,i);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"?M:(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"?M:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Gt(a))return M;let c=o.transform(a.value,i);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=>Gt(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:n.value,value:c})):M);G.assertNever(o)}};We.create=(e,t,n)=>new We({schema:e,typeName:L.ZodEffects,effect:t,...j(n)});We.createWithPreprocess=(e,t,n)=>new We({schema:t,effect:{type:"preprocess",transform:e},typeName:L.ZodEffects,...j(n)});Ke=class extends B{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===N.undefined?ye(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ke.create=(e,t)=>new Ke({innerType:e,typeName:L.ZodOptional,...j(t)});pt=class extends B{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===N.null?ye(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:L.ZodNullable,...j(t)});$n=class extends B{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===N.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$n.create=(e,t)=>new $n({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...j(t)});Ln=class extends B{static{s(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Rr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ln.create=(e,t)=>new Ln({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...j(t)});Or=class extends B{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==N.nan){let r=this._getOrReturnCtx(t);return A(r,{code:C.invalid_type,expected:N.nan,received:r.parsedType}),M}return{status:"valid",value:t.data}}};Or.create=e=>new Or({typeName:L.ZodNaN,...j(e)});vT=Symbol("zod_brand"),Mo=class extends B{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}},$o=class e extends B{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),xn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:L.ZodPipeline})}},Fn=class extends B{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(o=>(Gt(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return Rr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Fn.create=(e,t)=>new Fn({innerType:e,typeName:L.ZodReadonly,...j(t)});s(sh,"cleanParams");s(uh,"custom");kT={object:Ie.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"})(L||(L={}));xT=s((e,t={message:`Input not instance of ${e.name}`})=>uh(n=>n instanceof e,t),"instanceOfType"),ph=Wt.create,fh=Sn.create,ST=Or.create,ET=En.create,mh=Rn.create,RT=Cn.create,CT=Tr.create,TT=Tn.create,AT=An.create,IT=Vt.create,NT=Rt.create,OT=et.create,DT=Ar.create,PT=Ct.create,MT=Ie.create,$T=Ie.strictCreate,LT=In.create,FT=bs.create,jT=Nn.create,HT=ut.create,UT=ws.create,BT=Ir.create,KT=Nr.create,GT=vs.create,WT=On.create,VT=Dn.create,qT=Pn.create,zT=Mn.create,JT=qt.create,YT=We.create,XT=Ke.create,ZT=pt.create,QT=We.createWithPreprocess,eA=$o.create,tA=s(()=>ph().optional(),"ostring"),nA=s(()=>fh().optional(),"onumber"),rA=s(()=>mh().optional(),"oboolean"),oA={string:s(e=>Wt.create({...e,coerce:!0}),"string"),number:s(e=>Sn.create({...e,coerce:!0}),"number"),boolean:s(e=>Rn.create({...e,coerce:!0}),"boolean"),bigint:s(e=>En.create({...e,coerce:!0}),"bigint"),date:s(e=>Cn.create({...e,coerce:!0}),"date")},iA=M});var m={};Z(m,{BRAND:()=>vT,DIRTY:()=>xn,EMPTY_PATH:()=>QC,INVALID:()=>M,NEVER:()=>iA,OK:()=>ye,ParseStatus:()=>ue,Schema:()=>B,ZodAny:()=>Vt,ZodArray:()=>Ct,ZodBigInt:()=>En,ZodBoolean:()=>Rn,ZodBranded:()=>Mo,ZodCatch:()=>Ln,ZodDate:()=>Cn,ZodDefault:()=>$n,ZodDiscriminatedUnion:()=>bs,ZodEffects:()=>We,ZodEnum:()=>Pn,ZodError:()=>Ae,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>vs,ZodIntersection:()=>Nn,ZodIssueCode:()=>C,ZodLazy:()=>On,ZodLiteral:()=>Dn,ZodMap:()=>Ir,ZodNaN:()=>Or,ZodNativeEnum:()=>Mn,ZodNever:()=>et,ZodNull:()=>An,ZodNullable:()=>pt,ZodNumber:()=>Sn,ZodObject:()=>Ie,ZodOptional:()=>Ke,ZodParsedType:()=>N,ZodPipeline:()=>$o,ZodPromise:()=>qt,ZodReadonly:()=>Fn,ZodRecord:()=>ws,ZodSchema:()=>B,ZodSet:()=>Nr,ZodString:()=>Wt,ZodSymbol:()=>Tr,ZodTransformer:()=>We,ZodTuple:()=>ut,ZodType:()=>B,ZodUndefined:()=>Tn,ZodUnion:()=>In,ZodUnknown:()=>Rt,ZodVoid:()=>Ar,addIssueToContext:()=>A,any:()=>IT,array:()=>PT,bigint:()=>ET,boolean:()=>mh,coerce:()=>oA,custom:()=>uh,date:()=>RT,datetimeRegex:()=>lh,defaultErrorMap:()=>St,discriminatedUnion:()=>FT,effect:()=>YT,enum:()=>qT,function:()=>GT,getErrorMap:()=>Er,getParsedType:()=>dt,instanceof:()=>xT,intersection:()=>jT,isAborted:()=>ys,isAsync:()=>Rr,isDirty:()=>_s,isValid:()=>Gt,late:()=>kT,lazy:()=>WT,literal:()=>VT,makeIssue:()=>Po,map:()=>BT,nan:()=>ST,nativeEnum:()=>zT,never:()=>OT,null:()=>AT,nullable:()=>ZT,number:()=>fh,object:()=>MT,objectUtil:()=>wl,oboolean:()=>rA,onumber:()=>nA,optional:()=>XT,ostring:()=>tA,pipeline:()=>eA,preprocess:()=>QT,promise:()=>JT,quotelessJson:()=>YC,record:()=>UT,set:()=>KT,setErrorMap:()=>ZC,strictObject:()=>$T,string:()=>ph,symbol:()=>CT,transformer:()=>YT,tuple:()=>HT,undefined:()=>TT,union:()=>LT,unknown:()=>NT,util:()=>G,void:()=>DT});var El=w(()=>{gs();kl();rh();Do();hh();hs()});var _e=w(()=>{El();El()});var Rl,Cl=w(()=>{"use strict";_e();Rl=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 sA,gh=w(()=>{"use strict";_e();Cl();sA=Rl.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 yh,_h,bh,wh,Tl,vh,kh,xh,aA,Sh=w(()=>{"use strict";_e();yh=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],_h=m.enum(yh),bh=["new_to_ai_agents","new_to_this_client","experienced"],wh=m.enum(bh),Tl=[{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"}],vh=Tl.map(e=>e.header),kh=m.object({experience_level:m.array(wh).default([]),stack_filters:m.array(m.string()).default([])}).default({experience_level:[],stack_filters:[]}),xh=m.object({id:m.string().min(1),client:_h,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:kh,version:m.number().int().min(1).default(1),changelog:m.string().max(500).optional()}),aA=xh.extend({body:m.string().min(1)})});var Rh,ks,Ch,xs,cA,lA,Th,Ah,Ih,Nh,Ss,dA,uA,Eh,pA,Oh,fA,Dh=w(()=>{"use strict";_e();Rh=["operating_procedure","code_review","communication_style"],ks=m.enum(Rh),Ch=["info","recommended","required"],xs=m.enum(Ch),cA=["optional","default_on","mandatory"],lA=m.enum(cA),Th=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Ah=m.enum(Th),Ih=["verify","contribute","mixed"],Nh=m.enum(Ih),Ss=m.object({clients:m.array(Ah).default([]),stacks:m.array(m.string()).default([]),intents:m.array(Nh).default([])}).default({clients:[],stacks:[],intents:[]}),dA=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,uA=64,Eh=200,pA=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")),Oh=m.object({id:m.string().min(5).max(uA).regex(dA,"id must match conv_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),scope:ks,version:m.number().int().min(1),changed_at:pA,changelog:m.string().max(500).optional(),applies_to:Ss,severity:xs.default("recommended"),disableability:lA.default("default_on"),summary:m.string().min(1).max(Eh,`summary must be \u2264 ${Eh} 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()}),fA=Oh.extend({body:m.string().min(1)})});var zt=w(()=>{"use strict";Cl();gh();Sh();Dh()});var Al,Es,Il,Ph,Mh,$h,mA,Lh=w(()=>{"use strict";_e();Al=m.object({type:m.literal("text"),md:m.string().min(1).max(2e4)}),Es=m.number().min(0).max(1).optional(),Il=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:Es,right:Es,bottom:Es,left:Es}).optional()}),Ph=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")}),Mh=m.object({type:m.literal("accordion"),title:m.string().min(1).max(200),subtag:Ph.optional(),blocks:m.array(m.discriminatedUnion("type",[Al,Il])).max(50)}),$h=m.discriminatedUnion("type",[Al,Il,Mh]),mA=m.array($h).max(100)});var Fh,hA,jh,Hh,gA,yA,_A,Uh=w(()=>{"use strict";_e();Fh=["free","solo_pro","team","enterprise"],hA=m.enum(Fh),jh=["solo_pro","team","enterprise"],Hh=m.enum(jh),gA=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),yA=m.object({user_id:m.string().uuid(),tier:Hh,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:gA.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"}),_A=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Bh=w(()=>{"use strict"});var bA,wA,vA,Kh=w(()=>{"use strict";_e();bA=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),wA=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:bA.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"}),vA=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Gh,kA,Wh,Vh,qh,zh,xA,Jh=w(()=>{"use strict";_e();Gh=m.enum(["info","important","critical"]),kA=m.enum(["pass","warn","fail"]),Wh=m.object({type:m.enum(["template","lesson"]),id:m.string().min(1)}),Vh=m.object({languages:m.array(m.string()).optional(),tools:m.array(m.string()).optional()}).optional(),qh=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")})]),zh=m.object({id:m.string().min(1),title:m.string().min(1),severity:Gh,weight:m.number().int().positive().max(100),applies_when:Vh,check:qh,fail_message:m.string().min(1),warn_message:m.string().optional(),remediation:Wh.optional()}),xA=m.object({version:m.literal(1),checks:m.array(zh).min(1)})});function EA(e){if(!SA.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Rs(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 RA(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var SA,Cs,Yh,Xh,ft,Nl,Zh,CA,Qh=w(()=>{"use strict";_e();SA=/^\d{4}-\d{2}-\d{2}$/;s(EA,"isRealDate");Cs=m.string().refine(EA,{message:"expected a real calendar date as YYYY-MM-DD"}),Yh=["exact","prefix"],Xh=m.enum(Yh),ft=m.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Nl=[2e5,272e3],Zh=m.object({model_pattern:m.string().min(1).max(100),match_kind:Xh,valid_from:Cs,valid_to:Cs.nullable().optional(),input:ft,output:ft,cache_read:ft,cache_write_5m:ft,cache_write_1h:ft,long_context:m.enum(["same_price","tiered"]).optional(),input_above_200k:ft.optional(),output_above_200k:ft.optional(),cache_read_above_200k:ft.optional(),cache_write_5m_above_200k:ft.optional(),cache_write_1h_above_200k:ft.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=>Rs(e)===0||Rs(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"||Rs(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=>Rs(e)===0||e.context_threshold_tokens==null||Nl.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Nl.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Rs,"aboveRateCount");s(RA,"rowKey");CA=m.object({changelog:m.string().min(1).max(500),as_of:Cs,source_url:m.string().url().max(500),rows:m.array(Zh).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((o,i)=>{let a=RA(o),c=n.get(a);c!==void 0?t.addIssue({code:m.ZodIssueCode.custom,path:["rows",i],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,i)});let r=new Map;e.rows.forEach((o,i)=>{let a=`${o.model_pattern}|${o.match_kind}`,c=r.get(a)??[];c.push({i,r:o}),r.set(a,c)});for(let o of r.values())if(!(o.length<2)){o.sort((i,a)=>i.r.valid_from.localeCompare(a.r.valid_from));for(let i=0;i<o.length-1;i++){let a=o[i],c=o[i+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 Dr=w(()=>{"use strict"});var Lo=w(()=>{"use strict"});var rg=w(()=>{"use strict";Lo();Dr()});var og=w(()=>{"use strict";Dr()});var ig=w(()=>{"use strict";zt();Lo();Dr()});var sg=w(()=>{"use strict";Lo();Dr()});var ag=w(()=>{"use strict";Dr();rg();og();ig();sg();Lo()});var VA,qA,cg,zA,lg,Ol,dg,ug,pg,fg,JA,Dl=w(()=>{"use strict";_e();zt();VA=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,qA=64,cg=200,zA=1e3,lg=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")),Ol=m.enum(["low","medium","high"]),dg=m.object({owner:m.string().min(1).max(160).optional(),risk_level:Ol.optional(),reviewed_at:lg.optional()}).default({}),ug=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}),pg=m.object({lesson_query:ug,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:[]}),fg=m.object({id:m.string().min(6).max(qA).regex(VA,"id must match skill_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),version:m.number().int().min(1),changed_at:lg,tier:m.enum(["community","curated"]).default("curated"),summary:m.string().min(1).max(cg,`summary must be \u2264 ${cg} chars (rendered as one line in skill_index)`),description:m.string().max(zA).optional(),applies_to:Ss,membership:pg,governance:dg}),JA=fg.extend({body:m.string().default(""),org_id:m.string().uuid().optional(),org_name:m.string().optional()})});var mg,hg,gg,yg,_g,bg,YA,wg,XA,ZA,vg=w(()=>{"use strict";_e();Dl();mg=m.enum(["maind","agent-skill"]),hg=m.enum(["ready","needs_attention","blocked"]),gg=m.enum(["info","important","critical"]),yg=m.enum(["pass","warn","fail"]),_g=m.enum(["structure","governance","scope","membership","package","references"]),bg=m.object({id:m.string().min(1),title:m.string().min(1),status:yg,severity:gg,category:_g,field:m.string().nullable().optional(),message:m.string().min(1),hint:m.string().optional()}),YA=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({}),wg=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(),XA=m.object({directory_name:m.string().min(1).max(120).optional(),frontmatter:wg,body:m.string().default(""),file_listing:m.array(m.string()).optional()}),ZA=m.object({format:mg,subject:m.string().min(1),status:hg,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(bg),next_steps:m.array(m.string()),trust_note:m.string().min(1)})});var Pl=w(()=>{"use strict"});var kg,eI,xg,Sg,Eg,Pr,tI,Rg,Cg,Tg,Ag,Ig,Ng,Og,Dg,nI,Pg,Mg,$g,Jt,Ml,Lg,Fg,rI,jg=w(()=>{"use strict";_e();zt();Pl();kg=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],eI=m.enum(kg),xg=["verdict","advisory"],Sg=m.enum(xg),Eg=["block","warn","note"],Pr=m.enum(Eg),tI=m.object({convention_id:m.string().min(1).max(64),convention_version:m.number().int().min(1),severity:xs,scope:ks,grade:Sg,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()}),Rg=["open","warn","info"],Cg=m.enum(Rg),Tg=["introduced","pre_existing"],Ag=m.enum(Tg),Ig=["full","partial","none"],Ng=m.enum(Ig),Og=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:Cg,baseline:Ag,evidence_hash:m.string().regex(/^[a-f0-9]{64}$/),count:m.number().int().min(1).max(1e5)}),Dg=m.object({version:m.literal(1).default(1),actions:m.object({required:Pr.default("block"),recommended:Pr.default("warn"),info:Pr.default("note")}).default({}),overrides:m.array(m.object({convention_id:m.string().min(1).max(64),action:Pr})).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:Pr,reason:m.string().min(1).max(200)})).max(32).optional()}),nI=Dg.parse({}),Pg=["ran","not_applicable","unavailable","ungraded"],Mg=m.enum(Pg),$g=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),state:Mg}),Jt=1e3,Ml=m.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Lg=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()}),Fg=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:Ng}),rI=m.object({changed_symbols:m.array(Lg).max(Jt),risk_flags:m.array(m.string().max(64)).max(16),detector_findings:m.array(Og).max(64),detector_runs:m.array($g).min(1).max(32),diff_stats:Fg,commit_sha:Ml.optional(),base_sha:Ml.optional(),merge_base_sha:Ml.optional(),dirty:m.boolean().optional(),code_index_version:m.string().min(1).max(32).optional()})});var Hg,Ug,Bg,Kg,Gg,$l,oI,iI,Wg,Vg,qg,zg,Jg,sI,aI,Yg,Xg,Zg,cI,Qg=w(()=>{"use strict";_e();Hg=14,Ug=14,Bg=14,Kg=1,Gg=365,$l=m.number().int().min(Kg).max(Gg),oI=["propose","direct"],iI="propose",Wg=["propose","direct"],Vg="propose",qg=["propose","direct"],zg="propose",Jg=["off","propose","direct"],sI=["member","admin","owner"],aI="member",Yg="off",Xg="en",Zg=m.object({version:m.literal(1).default(1),at_risk_days:$l.default(Hg),stagnation_days:$l.default(Ug),agent_date_mode:m.enum(oI).default(iI),health_manual_ttl_days:$l.default(Bg),agent_event_mode:m.enum(Wg).default(Vg),agent_update_mode:m.enum(qg).default(zg),agent_pull_mode:m.enum(Jg).default(Yg),org_wide_authoring_min_role:m.enum(sI).default(aI),planning_language:m.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Xg)}),cI=Zg.parse({})});var ey,lI,ty=w(()=>{"use strict";_e();ey=m.object({version:m.literal(1).default(1),org_visibility:m.boolean().default(!1),session_span_visibility:m.boolean().default(!0)}),lI=ey.parse({})});var ny,ry,dI,uI,oy=w(()=>{"use strict";_e();ny=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([])}),ry=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:ny.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()}),dI=ry.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()}),uI=m.object({id:m.string().uuid(),title:m.string(),summary:m.string(),tags:m.array(m.string()).default([])})});var iy=w(()=>{"use strict"});function Ts(e){let t=[],n=null;return e.split(`
3
+ `).forEach((r,o)=>{let i=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(i===""||a>n)return;n=null}if(i===""||i.startsWith("#"))return;let c=fI.exec(r);if(!c)return;let l=c[3]??"";if(pI.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:o+1,value:d})}),t}var pI,fI,sy=w(()=>{"use strict";pI=new Set(["|",">","|-",">-","|+",">+"]),fI=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(Ts,"plainScalarViolations")});function jo(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,o]=n(e),[i,a]=n(t);for(let c=0;c<Math.max(r.length,i.length);c+=1){let l=(r[c]??0)-(i[c]??0);if(l!==0)return l<0?-1:1}if(o.length===0&&a.length===0)return 0;if(o.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(o.length,a.length);c+=1){let l=o[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 ay=w(()=>{"use strict";s(jo,"compareSemver")});var Ho=w(()=>{"use strict";zt();Lh();zt();zt();Uh();Bh();Kh();Jh();Qh();ag();zt();Dl();vg();jg();Qg();ty();oy();iy();Pl();sy();ay()});function cy(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
+ `).slice(0,1e3)}var ly=w(()=>{"use strict";s(cy,"nodeEmbedText")});var Ll,Fl=w(()=>{"use strict";Ll=["function","method","class","interface","enum","type_alias"]});function dy(e,t){let n=Math.min(e.length,t.length),r=0,o=0,i=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,o+=c*c,i+=l*l}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var uy=w(()=>{"use strict";s(dy,"cosineSimilarity")});import{execFileSync as mI}from"node:child_process";import{createHash as hI}from"node:crypto";import{readFileSync as gI}from"node:fs";import{posix as tt}from"node:path";function py(e){let t=hI("sha256"),n=[];try{n=mI("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
+ `).filter(l=>yI.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,o=s(l=>{if(r.has(l))return r.get(l);try{let d=gI(tt.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),i=[],a=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=fy(l,o,0),u=tt.dirname(l)==="."?"":tt.dirname(l);l.endsWith("tsconfig.json")&&a.set(u,d),d.paths&&i.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=my(o(l));if(!d||typeof d.name!="string")continue;let u=tt.dirname(l)==="."?"":tt.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:i},fingerprint:t.digest("hex")}}function fy(e,t,n){let r=my(t(e));if(!r)return{};let o=tt.dirname(e)==="."?"":tt.dirname(e),i={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=tt.normalize(tt.join(o,a.endsWith(".json")?a:a+".json"));i=fy(d,t,n+1)}let c=r.compilerOptions??{},l={...i};return typeof c.outDir=="string"&&(l.outDir=tt.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=tt.normalize(c.rootDir)),c.paths&&typeof c.paths=="object"&&(l.paths=c.paths,l.pathsDir=o,l.baseUrl=typeof c.baseUrl=="string"?c.baseUrl:void 0),l}function my(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(n){t+=o,o==="\\"?t+=e[++r]??"":o==='"'&&(n=!1);continue}if(o==='"')n=!0,t+=o;else if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
6
6
  `;)r++;t+=`
7
- `}else if(o==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=o}try{let r=JSON.parse(yI(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function yI(e){let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(n){t+=o,o==="\\"?t+=e[++r]??"":o==='"'&&(n=!1);continue}if(o==='"'&&(n=!0),o===","){let i=r+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]==="}"||e[i]==="]")continue}t+=o}return t}var gI,hy=w(()=>{"use strict";gI=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(py,"loadModuleConfig");s(fy,"compilerFacts");s(my,"parseJsonc");s(yI,"dropTrailingCommas")});import{posix as nt}from"node:path";function Uo(e,t){let n=nt.normalize(e).replace(/^\.\//,""),r=[],o=As.some(c=>n.endsWith(c));o&&r.push(n);let i=/\.d\.(m|c)?ts$/.exec(n);i&&r.push(n.slice(0,-i[0].length)+".ts",n.slice(0,-i[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 As)r.push(c+l)}if(!o&&!i){for(let c of As)r.push(n+c);for(let c of As)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function yy(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let o of e){let i=yy(o,t);if(i)return i}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(o=>o.startsWith("."))){if(t in n)return Bo(n[t]);for(let o of r){let i=o.indexOf("*");if(i<0)continue;let a=o.slice(0,i),c=o.slice(i+1);if(t.startsWith(a)&&t.endsWith(c)){let l=Bo(n[o]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?Bo(e):null}function Bo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Bo(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of _I)if(n in t){let r=Bo(t[n]);if(r)return r}}return null}function bI(e,t){let n=nt.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let o=nt.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),i=nt.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===o||n.startsWith(o+"/"))&&r.unshift(nt.join(i,n.slice(o.length+1)))}return r}var As,_I,Fl,gy,Mr,jl=w(()=>{"use strict";As=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],_I=["import","default","node","require","types"],Fl={kind:"unresolved"},gy={kind:"external"};s(Uo,"resolvePathCandidates");Mr=class{static{s(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,o)=>o.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,o)=>o.dir.length-r.dir.length)}resolve(t,n){let r=`${nt.dirname(t)}\0${n}`,o=this.cache.get(r);return o||(o=this.compute(t,n),this.cache.set(r,o)),o}compute(t,n){if(n.startsWith(".")){let i=Uo(nt.join(nt.dirname(t),n),this.files);return i?{kind:"file",path:i}:Fl}if(n.startsWith("node:"))return gy;let r=this.viaTsconfigPaths(t,n);if(r)return r;let o=this.packages.find(i=>n===i.name||n.startsWith(i.name+"/"));if(o){let i=n===o.name?".":"./"+n.slice(o.name.length+1),a=this.viaPackage(o,i);return a?{kind:"file",path:a}:Fl}return gy}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(i=>i.dir===""||t.startsWith(i.dir+"/"));if(!r?.paths)return null;let o=nt.join(r.dir,r.baseUrl??".");for(let[i,a]of Object.entries(r.paths)){let c=i.indexOf("*"),l=null;if(c<0)i===n&&(l="");else{let d=i.slice(0,c),u=i.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=Uo(nt.join(o,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return Fl}}return null}viaPackage(t,n){let r=[],o=yy(t.exports,n);if(o)r.push(o);else if(t.exports===void 0)if(n==="."){for(let i of[t.module,t.main,t.types])i&&r.push(i);r.push("index")}else r.push(n);for(let i of r)for(let a of bI(t,i)){let c=Uo(nt.join(t.dir,a),this.files);if(c)return c}return null}};s(yy,"exportTarget");s(Bo,"conditionTarget");s(bI,"toSource")});function mt(e){return`${e}#<module>`}function ht(e,t,n){return`${e}#${t}:${n}`}var jn=w(()=>{"use strict";s(mt,"moduleKey");s(ht,"symbolKey")});import{posix as _y}from"node:path";function wy(e){let t=new Map,n=new Set,r=new Map,o=new Map,i=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),i.add(c.nodeKey),wI.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(o,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===ht(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:o,keys:i}}function vy(e,t,n=new Mr({packages:[],tsconfigs:[]},t.files)){let r=SI(),o=new Hl(e,t,n);for(let i of e)i.language==="python"?EI(i.filePath,i.refs,i.imports,t,r.push):o.resolveFile(i,r.push);return r.edges}function xI(e,t,n){return t.startsWith(".")?Uo(_y.join(_y.dirname(e),t),n):null}function SI(){let e=new Set,t=[];return{edges:t,push(n,r,o){if(n===r)return;let i=`${n} ${r} ${o}`;e.has(i)||(e.add(i),t.push({srcKey:n,dstKey:r,kind:o}))}}}function EI(e,t,n,r,o){for(let i of t){let a=r.nameToKeys.get(i.targetName);!a||a.length!==1||o(i.fromKey,a[0],i.kind)}for(let i of n){let a=xI(e,i.specifier,r.files);a&&o(i.fromModuleKey,mt(a),"imports")}}function RI(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return ht(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var wI,by,vI,kI,Hl,ky=w(()=>{"use strict";jn();jl();wI=new Set(["function","method","class","interface","enum","type_alias"]),by=["function","class","variable","enum","interface","type_alias"],vI=8,kI=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(wy,"buildResolutionIndex");s(vy,"resolveCrossFileEdges");s(xI,"resolveImportTarget");s(SI,"edgeCollector");s(EI,"legacyFacts");s(RI,"classKeyOfMethod");Hl=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 o of t){this.languages.set(o.filePath,o.language),this.exports.set(o.filePath,o.exports??[]);let i=new Map;for(let a of o.imports)a.localName&&a.importedName&&i.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(o.filePath,i);for(let a of o.refs){if(a.kind==="calls")continue;let c=this.heritage.get(a.fromKey);c?c.push({file:o.filePath,ref:a}):this.heritage.set(a.fromKey,[{file:o.filePath,ref:a}])}}}resolveFile(t,n){for(let r of t.refs){let o=this.resolveRef(t.filePath,r);o&&n(r.fromKey,o,r.kind)}for(let r of t.imports){let o=this.modules.resolve(t.filePath,r.specifier);o.kind==="file"&&n(mt(t.filePath),mt(o.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(kI.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 o=this.nameableKeys(t),i=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=RI(a);if(o.has(c))return!0;for(let l of this.supertypes(c))if(o.has(l)&&this.implementers(l).size===1)return!0;return!1});return i.length===1?i[0]:null}typedMethod(t,n,r){if(n==="#")return null;let o=n.indexOf("."),i;if(o<0)i=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,o),0);i=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(o+1),1):null}if(i?.kind!=="symbol")return null;let a=i.key.endsWith(":class")?[i.key]:[...this.implementers(i.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),o=ht(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(o))return o;for(let i of this.supertypes(t)){if(!i.endsWith(":class"))continue;let a=i.indexOf("#"),c=ht(i.slice(0,a),`${i.slice(a+1,i.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 o=this.implementersOf.get(r);o||this.implementersOf.set(r,o=new Set),o.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 o=this.resolveLocal(t,r,0);o?.kind==="symbol"&&n.add(o.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let o of r)n.add(o);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:o}of this.heritage.get(t)??[]){let i=this.resolveRef(r,o);if(i){n.add(i);for(let a of this.supertypes(i))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),o=t.lastIndexOf(":");if(r<0||o<r)return null;let i=t.slice(0,r),a=t.slice(r+1,o),c=t.slice(o+1),l=c==="method"?a.slice(0,a.lastIndexOf(".")):c==="class"?a:null;if(!l)return null;let d=ht(i,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let o=this.bindings.get(t)?.get(n);return o?this.resolveBinding(t,o,r):this.topLevel(t,n)}resolveBinding(t,n,r){let o=this.modules.resolve(t,n.specifier);return o.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:o.path}:this.resolveExport(o.path,n.importedName,r+1)}resolveExport(t,n,r){let o=`${t}\0${n}`;if(this.memo.has(o))return this.memo.get(o);if(r>vI)return null;this.memo.set(o,null);let i=this.computeExport(t,n,r);return this.memo.set(o,i),i}computeExport(t,n,r){let o=this.exports.get(t)??[];for(let l of o)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 i=this.topLevel(t,n);if(i)return i;let a=this.bindings.get(t)?.get(n);if(a)return this.resolveBinding(t,a,r);let c=new Map;for(let l of o){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 o=s(i=>{let a=by.indexOf(i.slice(i.lastIndexOf(":")+1));return a<0?by.length:a},"rank");return{kind:"symbol",key:[...r].sort((i,a)=>o(i)-o(a))[0]}}}});function $r(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 Ko(e){return e.toLowerCase().endsWith(".d.ts")}var Is=w(()=>{"use strict";s($r,"languageForPath");s(Ko,"isSkippablePath")});import{appendFileSync as CI,existsSync as xy,mkdirSync as TI,readFileSync as AI}from"node:fs";import{join as II}from"node:path";function Go(e,t={}){try{if(!xy(e)){if(!t.create)return"skipped";TI(e,{recursive:!0})}let n=II(e,".gitignore"),r=xy(n)?AI(n,"utf8"):null,o=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),i=Ns.filter(l=>!o.has(l));if(i.length===0)return"unchanged";let a=r===null?[...NI,...i]:i,c=r&&!r.endsWith(`
7
+ `}else if(o==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=o}try{let r=JSON.parse(_I(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function _I(e){let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(n){t+=o,o==="\\"?t+=e[++r]??"":o==='"'&&(n=!1);continue}if(o==='"'&&(n=!0),o===","){let i=r+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]==="}"||e[i]==="]")continue}t+=o}return t}var yI,hy=w(()=>{"use strict";yI=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(py,"loadModuleConfig");s(fy,"compilerFacts");s(my,"parseJsonc");s(_I,"dropTrailingCommas")});import{posix as nt}from"node:path";function Uo(e,t){let n=nt.normalize(e).replace(/^\.\//,""),r=[],o=As.some(c=>n.endsWith(c));o&&r.push(n);let i=/\.d\.(m|c)?ts$/.exec(n);i&&r.push(n.slice(0,-i[0].length)+".ts",n.slice(0,-i[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 As)r.push(c+l)}if(!o&&!i){for(let c of As)r.push(n+c);for(let c of As)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function yy(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let o of e){let i=yy(o,t);if(i)return i}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(o=>o.startsWith("."))){if(t in n)return Bo(n[t]);for(let o of r){let i=o.indexOf("*");if(i<0)continue;let a=o.slice(0,i),c=o.slice(i+1);if(t.startsWith(a)&&t.endsWith(c)){let l=Bo(n[o]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?Bo(e):null}function Bo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Bo(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of bI)if(n in t){let r=Bo(t[n]);if(r)return r}}return null}function wI(e,t){let n=nt.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let o=nt.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),i=nt.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===o||n.startsWith(o+"/"))&&r.unshift(nt.join(i,n.slice(o.length+1)))}return r}var As,bI,jl,gy,Mr,Hl=w(()=>{"use strict";As=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],bI=["import","default","node","require","types"],jl={kind:"unresolved"},gy={kind:"external"};s(Uo,"resolvePathCandidates");Mr=class{static{s(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,o)=>o.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,o)=>o.dir.length-r.dir.length)}resolve(t,n){let r=`${nt.dirname(t)}\0${n}`,o=this.cache.get(r);return o||(o=this.compute(t,n),this.cache.set(r,o)),o}compute(t,n){if(n.startsWith(".")){let i=Uo(nt.join(nt.dirname(t),n),this.files);return i?{kind:"file",path:i}:jl}if(n.startsWith("node:"))return gy;let r=this.viaTsconfigPaths(t,n);if(r)return r;let o=this.packages.find(i=>n===i.name||n.startsWith(i.name+"/"));if(o){let i=n===o.name?".":"./"+n.slice(o.name.length+1),a=this.viaPackage(o,i);return a?{kind:"file",path:a}:jl}return gy}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(i=>i.dir===""||t.startsWith(i.dir+"/"));if(!r?.paths)return null;let o=nt.join(r.dir,r.baseUrl??".");for(let[i,a]of Object.entries(r.paths)){let c=i.indexOf("*"),l=null;if(c<0)i===n&&(l="");else{let d=i.slice(0,c),u=i.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=Uo(nt.join(o,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return jl}}return null}viaPackage(t,n){let r=[],o=yy(t.exports,n);if(o)r.push(o);else if(t.exports===void 0)if(n==="."){for(let i of[t.module,t.main,t.types])i&&r.push(i);r.push("index")}else r.push(n);for(let i of r)for(let a of wI(t,i)){let c=Uo(nt.join(t.dir,a),this.files);if(c)return c}return null}};s(yy,"exportTarget");s(Bo,"conditionTarget");s(wI,"toSource")});function mt(e){return`${e}#<module>`}function ht(e,t,n){return`${e}#${t}:${n}`}var jn=w(()=>{"use strict";s(mt,"moduleKey");s(ht,"symbolKey")});import{posix as _y}from"node:path";function wy(e){let t=new Map,n=new Set,r=new Map,o=new Map,i=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),i.add(c.nodeKey),vI.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(o,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===ht(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:o,keys:i}}function vy(e,t,n=new Mr({packages:[],tsconfigs:[]},t.files)){let r=EI(),o=new Ul(e,t,n);for(let i of e)i.language==="python"?RI(i.filePath,i.refs,i.imports,t,r.push):o.resolveFile(i,r.push);return r.edges}function SI(e,t,n){return t.startsWith(".")?Uo(_y.join(_y.dirname(e),t),n):null}function EI(){let e=new Set,t=[];return{edges:t,push(n,r,o){if(n===r)return;let i=`${n} ${r} ${o}`;e.has(i)||(e.add(i),t.push({srcKey:n,dstKey:r,kind:o}))}}}function RI(e,t,n,r,o){for(let i of t){let a=r.nameToKeys.get(i.targetName);!a||a.length!==1||o(i.fromKey,a[0],i.kind)}for(let i of n){let a=SI(e,i.specifier,r.files);a&&o(i.fromModuleKey,mt(a),"imports")}}function CI(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return ht(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var vI,by,kI,xI,Ul,ky=w(()=>{"use strict";jn();Hl();vI=new Set(["function","method","class","interface","enum","type_alias"]),by=["function","class","variable","enum","interface","type_alias"],kI=8,xI=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(wy,"buildResolutionIndex");s(vy,"resolveCrossFileEdges");s(SI,"resolveImportTarget");s(EI,"edgeCollector");s(RI,"legacyFacts");s(CI,"classKeyOfMethod");Ul=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 o of t){this.languages.set(o.filePath,o.language),this.exports.set(o.filePath,o.exports??[]);let i=new Map;for(let a of o.imports)a.localName&&a.importedName&&i.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(o.filePath,i);for(let a of o.refs){if(a.kind==="calls")continue;let c=this.heritage.get(a.fromKey);c?c.push({file:o.filePath,ref:a}):this.heritage.set(a.fromKey,[{file:o.filePath,ref:a}])}}}resolveFile(t,n){for(let r of t.refs){let o=this.resolveRef(t.filePath,r);o&&n(r.fromKey,o,r.kind)}for(let r of t.imports){let o=this.modules.resolve(t.filePath,r.specifier);o.kind==="file"&&n(mt(t.filePath),mt(o.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(xI.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 o=this.nameableKeys(t),i=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=CI(a);if(o.has(c))return!0;for(let l of this.supertypes(c))if(o.has(l)&&this.implementers(l).size===1)return!0;return!1});return i.length===1?i[0]:null}typedMethod(t,n,r){if(n==="#")return null;let o=n.indexOf("."),i;if(o<0)i=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,o),0);i=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(o+1),1):null}if(i?.kind!=="symbol")return null;let a=i.key.endsWith(":class")?[i.key]:[...this.implementers(i.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),o=ht(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(o))return o;for(let i of this.supertypes(t)){if(!i.endsWith(":class"))continue;let a=i.indexOf("#"),c=ht(i.slice(0,a),`${i.slice(a+1,i.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 o=this.implementersOf.get(r);o||this.implementersOf.set(r,o=new Set),o.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 o=this.resolveLocal(t,r,0);o?.kind==="symbol"&&n.add(o.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let o of r)n.add(o);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:o}of this.heritage.get(t)??[]){let i=this.resolveRef(r,o);if(i){n.add(i);for(let a of this.supertypes(i))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),o=t.lastIndexOf(":");if(r<0||o<r)return null;let i=t.slice(0,r),a=t.slice(r+1,o),c=t.slice(o+1),l=c==="method"?a.slice(0,a.lastIndexOf(".")):c==="class"?a:null;if(!l)return null;let d=ht(i,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let o=this.bindings.get(t)?.get(n);return o?this.resolveBinding(t,o,r):this.topLevel(t,n)}resolveBinding(t,n,r){let o=this.modules.resolve(t,n.specifier);return o.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:o.path}:this.resolveExport(o.path,n.importedName,r+1)}resolveExport(t,n,r){let o=`${t}\0${n}`;if(this.memo.has(o))return this.memo.get(o);if(r>kI)return null;this.memo.set(o,null);let i=this.computeExport(t,n,r);return this.memo.set(o,i),i}computeExport(t,n,r){let o=this.exports.get(t)??[];for(let l of o)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 i=this.topLevel(t,n);if(i)return i;let a=this.bindings.get(t)?.get(n);if(a)return this.resolveBinding(t,a,r);let c=new Map;for(let l of o){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 o=s(i=>{let a=by.indexOf(i.slice(i.lastIndexOf(":")+1));return a<0?by.length:a},"rank");return{kind:"symbol",key:[...r].sort((i,a)=>o(i)-o(a))[0]}}}});function $r(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 Ko(e){return e.toLowerCase().endsWith(".d.ts")}var Is=w(()=>{"use strict";s($r,"languageForPath");s(Ko,"isSkippablePath")});import{appendFileSync as TI,existsSync as xy,mkdirSync as AI,readFileSync as II}from"node:fs";import{join as NI}from"node:path";function Go(e,t={}){try{if(!xy(e)){if(!t.create)return"skipped";AI(e,{recursive:!0})}let n=NI(e,".gitignore"),r=xy(n)?II(n,"utf8"):null,o=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),i=Ns.filter(l=>!o.has(l));if(i.length===0)return"unchanged";let a=r===null?[...OI,...i]:i,c=r&&!r.endsWith(`
8
8
  `)?`
9
- `:"";return CI(n,c+a.join(`
9
+ `:"";return TI(n,c+a.join(`
10
10
  `)+`
11
- `),r===null?"created":"appended"}catch{return"skipped"}}var Ns,Ul,NI,Os=w(()=>{"use strict";Ns=["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"],Ul=["# 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).'],NI=Ul;s(Go,"ensureMaindLocalIgnore")});import{execFileSync as OI}from"node:child_process";import{createHash as DI}from"node:crypto";import{readFileSync as PI,readdirSync as MI,statSync as $I}from"node:fs";import{posix as Kl,sep as Sy}from"node:path";function I(e,t){try{return OI("git",[...LI,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function FI(e){return Sy==="/"?e:e.split(Sy).join("/")}function Ds(e){let t=[];for(let n of e){let r=FI(n).trim();if(!r||Ko(r))continue;let o=$r(r);o&&t.push({path:r,language:o})}return t}function Ry(e){return Ds(e)}function Cy(e){let t=Jt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Ds(t.split(`
12
- `));let n=[];return Ty(e,"",n),Ds(n)}function Ty(e,t,n){let r;try{r=MI(Kl.join(e,t),{withFileTypes:!0})}catch{return}for(let o of r){if(o.name.startsWith(".")&&o.name!=="."&&Ey.has(o.name)||Ey.has(o.name))continue;let i=t?`${t}/${o.name}`:o.name;o.isDirectory()?Ty(e,i,n):o.isFile()&&n.push(i)}}function Gl(e,t){return Wl(e,t)??t}function Wl(e,t){let n=I(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Ps(e,t={}){if(Wo(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Gl(e,t.since):"HEAD",o=["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");o.push("HEAD")}let i=Jt(e,o);if(i===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of i.split(`
13
- `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=Bl((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=Jt(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=Bl(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 Bl(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Vl(e,t={}){let n=Ps(e,t);return n===null?null:Ds(n.keys())}function Ay(e,t){try{let n=$I(Kl.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Ms(e){return DI("sha256").update(e).digest("hex")}function Wo(e){return Jt(e,["rev-parse","HEAD"])?.trim()??null}function $s(e,t){return Jt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function ql(e){let t=Jt(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
15
- `).filter(o=>o.trim().length>0);if(n.length===0)return!1;let r=jI(e);return n.some(o=>r===null||!HI(e,o,r))}function jI(e){let t=Jt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function HI(e,t,n){let r=t[0],o=t[1];if(Bl(t.slice(3))!==n)return!1;let i;if(r==="?"&&o==="?"||r==="A"&&(o===" "||o==="M"))i="";else if((r===" "||r==="M")&&(o===" "||o==="M")){let p=Jt(e,["show",`HEAD:${n}`]);if(p===null)return!1;i=p}else return!1;let a;try{a=PI(Kl.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=s(p=>p.replace(/\r\n/g,`
16
- `),"norm"),l=c(i),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...Ns,...Ul]);return d.slice(l.length).split(`
17
- `).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var Ey,LI,Jt,Ee=w(()=>{"use strict";Is();Os();Ey=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),LI=["-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(I,"runGit");Jt=I;s(FI,"toPosix");s(Ds,"classify");s(Ry,"classifyPaths");s(Cy,"discoverSourceFiles");s(Ty,"walk");s(Gl,"resolveDiffBase");s(Wl,"resolveMergeBase");s(Ps,"enumerateChangedPaths");s(Bl,"unquote");s(Vl,"changedSourceFiles");s(Ay,"statFile");s(Ms,"hashContent");s(Wo,"headCommit");s($s,"resolveCommitSha");s(ql,"isWorktreeDirty");s(jI,"toolIgnoreRepoPath");s(HI,"isToolOnlyIgnoreChange")});function Ny(e,t={}){if(I(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Gl(e,t.since):"HEAD",o=["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");o.push("HEAD")}let i=I(e,o);if(i===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(i,"utf8")>UI?c="none":WI(i,a,()=>{c="partial"}),n){let l=I(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 WI(e,t,n){let r=null,o=0,i=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,o=0},"commit");for(let l of e.split(`
19
- `)){if(l.startsWith("diff --git ")){c(),i=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){i=!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":i?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=GI.exec(l);if(d){if(o++,o>BI){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<KI&&r.addedLines.push(l.slice(1))}c()}var UI,BI,KI,Iy,GI,Oy=w(()=>{"use strict";Ee();UI=16*1024*1024,BI=500,KI=4e3,Iy=256*1024,GI=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Ny,"changedHunks");s(WI,"parseUnifiedDiff")});function Jl(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,o=0,i=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=Ly&&r++,c>o&&(o=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>i&&(i=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:o,distinct_authors:n.size,newest_change_age_days:i>0?Math.max(0,Math.floor((t-i)/864e5)):0}}function zI(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Py(e){return e.split(VI).filter(t=>t.trim().length>0)}function My(e){let[t,n,r,o,i]=e.replace(/\n+$/,"").split(qI);return!t||!o?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:o,subject:i??""}}function JI(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,o=t.get(r);o?o.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 Fy(e,t,n={}){let r=zI(n.limit,20,100),o=n.includeOwnership!==!1,i=Math.max(r,$y),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,zl),l=[];for(let u of c){let p=I(e,["log","-n",String(i),Dy,"--",u]),f=p===null?[]:Py(p).map(My).filter(h=>h!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:o?{topAuthors:JI(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=$s(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=I(e,["log",...p,"-n",String(Ls+1),Dy,"--name-only","--",...c]),h=[];if(f!==null)for(let g of Py(f)){let y=g.split(`
20
- `),_=My(y[0]??"");if(!_)continue;let b=y.slice(1).filter(v=>v.trim().length>0).length;h.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,Ls),truncated:h.length>Ls}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>zl}}var VI,qI,$y,zl,Ls,Dy,Ly,Yl=w(()=>{"use strict";Ee();VI="",qI="\0",$y=200,zl=50,Ls=100,Dy="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",Ly=10;s(Jl,"aggregateHistoryContext");s(zI,"clamp");s(Py,"splitRecords");s(My,"parseHistoryRecord");s(JI,"aggregateOwnership");s(Fy,"readFileHistory")});import{execFileSync as YI}from"node:child_process";import{readdirSync as XI,statSync as jy}from"node:fs";import{isAbsolute as ZI,join as Xl,relative as QI,resolve as eN}from"node:path";function nN(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function rN(e,t){try{let n=YI("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 oN(e){let t;try{t=XI(e)}catch{return null}for(let n of t.filter(nN))try{let r=jy(Xl(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function iN(e){try{return jy(e).isDirectory()}catch{return!1}}function sN(e,t){let n=QI(e,t);return!n||n.startsWith("..")?t:n}function Zl(e){let t=tN.filter(c=>iN(Xl(e,c))),n=rN(e,"core.hooksPath"),r=n?ZI(n)?n:eN(e,n):Xl(e,".git","hooks"),o=sN(e,r),i=oN(r);if(i===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:o};let a=n?i===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:o}}function Ql(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 tN,ed=w(()=>{"use strict";tN=[".githooks",".husky"];s(nN,"isRealHook");s(rN,"gitConfig");s(oN,"hasExecutableHook");s(iN,"isDir");s(sN,"displayPath");s(Zl,"resolveHookState");s(Ql,"describeHookState")});import{posix as Hy}from"node:path";function Lr(e){let t=aN.exec(e);return t?t[1]:null}function Tt(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Hn(e,t){let n=I(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(i=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||i===c||i.startsWith(`${c}/`)}),"wanted"),o=new Map;for(let i of n.split("\0").filter(Boolean)){if(!r(i))continue;let a=Hy.basename(i),c=Lr(a);if(c===null)continue;let l=Hy.dirname(i),d=o.get(l)??[];d.push({path:i,name:a,version:c}),o.set(l,d)}return[...o.entries()].map(([i,a])=>({dir:i,files:a.sort((c,l)=>Tt(c.version,l.version))})).sort((i,a)=>i.dir.localeCompare(a.dir))}function Vo(e){let t=I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var aN,qo=w(()=>{"use strict";Ee();aN=/^(\d+)_.+\.sql$/;s(Lr,"parseMigrationVersion");s(Tt,"compareVersions");s(Hn,"discoverSupabaseProjects");s(Vo,"resolveDefaultBranch")});import{execFileSync as cN}from"node:child_process";import{existsSync as be,readFileSync as Yt,readdirSync as Fs,statSync as nd}from"node:fs";import{posix as W}from"node:path";function pN(e,t){let n=(()=>{let o=I(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return o?o.trim():null})(),r=W.dirname(e);for(let o=0;o<8&&r&&r!==W.dirname(r);o++){if(be(W.join(r,".git"))){let i=(()=>{let c=I(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&i!=null&&od(n,i))){let c=fN(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=W.dirname(r)}return null}function fN(e,t){let n=[];for(let r of dN){let o;try{o=Fs(W.join(e,r),{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name)}catch{continue}for(let i of o){let a=`${r}/${i}`,c=W.join(e,a),l=W.join(t,a);try{let d=nd(c),u=nd(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>uN)continue;Yt(c).equals(Yt(l))||n.push(a)}catch{continue}}}return n.sort()}function qy(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,o=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}${o>0?` (and ${o} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let i=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(i){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(!i&&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 ${id}.`})}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 ${W.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=mN(e.hooks);return a&&t.push(a),hN(t)}function mN(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:Ql(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 hN(e){return[...e].sort((t,n)=>Uy[t.status]-Uy[n.status]||t.id.localeCompare(n.id))}function zy(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function At(e){let t=e?.trim();return t||null}function gN(e){let t=At(I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function yN(e){let t=At(I(e,["rev-parse","--git-dir"]));if(!t)return null;let n=W.isAbsolute(t)?t:W.join(e,t);return be(W.join(n,"rebase-merge"))||be(W.join(n,"rebase-apply"))?"rebase":be(W.join(n,"MERGE_HEAD"))?"merge":be(W.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function _N(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let o of e.split(`
21
- `))if(o.startsWith("worktree "))r(),n={path:o.slice(9).trim(),detached:!1};else if(n)o.startsWith("branch ")?n.branch=o.slice(7).trim().replace(/^refs\/heads\//,""):o.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function bN(e){let t=W.join(e,id);if(!be(t))return[];try{return Yt(t,"utf8").split(`
22
- `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function wN(e){try{return Hn(e).map(t=>W.join(W.dirname(t.dir),"config.toml"))}catch{return[]}}function vN(e){let t=I(e,["ls-files","-z","--",...lN]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let o=Vy[W.basename(r)];if(o===void 0)continue;let i=W.dirname(r);if(!kN(e,i))continue;let a=i==="."?"node_modules":W.join(i,"node_modules");n.has(a)||n.set(a,{dir:a,install:o})}return[...n.values()]}function kN(e,t){return t==="."?!0:rd(e,t)}function rd(e,t){if(be(W.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Yt(W.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Jy(e,t={}){if(At(I(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=At(I(e,["rev-parse","--abbrev-ref","HEAD"])),o=r==="HEAD",i=o?null:r,a=gN(e),c=At(I(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let K=At(I(e,["rev-parse","HEAD"])),x=At(I(e,["rev-parse","@{u}"]));l=K!=null&&x!=null?K===x:null,d=I(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(a){let K=At(I(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(K){let[x,T]=K.split(/\s+/).map(D=>Number.parseInt(D,10));Number.isFinite(x)&&(p=x),Number.isFinite(T)&&(u=T)}}let h=(I(e,["status","--porcelain"])??"").split(`
23
- `).filter(K=>K.trim().length>0).length,g=yN(e),y=At(I(e,["rev-parse","--show-toplevel"]))??e,_=_N(I(e,["worktree","list","--porcelain"])??""),b=_[0]?.path??null,v=b!=null&&od(b,y),k=Math.max(0,_.length-1),E=null;if(b&&!od(b,y)){let K=s(T=>be(W.join(b,T))&&!be(W.join(y,T)),"here"),x=[...Wy,...wN(y),...bN(y),...t.probePaths??[]];E={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(x.filter(K))],missingDeps:vN(y).filter(T=>K(T.dir))}}let S=pN(y,e),R=t.includeRelease===!1?null:AN(e,i),P=[];return a&&(P=(I(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
24
- `).map(x=>x.trim()).filter(x=>x.length>0)),{isRepo:!0,branch:i,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:h,detachedHead:o,inProgressOp:g,isSharedMainTree:v,otherWorktrees:k,worktreeParity:E,toolCopyDrift:S,stalePackageBuilds:Yy(y),release:R,unmergedMigrations:P,hooks:Zl(e)}}function od(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function EN(e){let t=new Set;rd(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Ky;){let o=n.pop();if(o===void 0)break;if(o.depth>=SN)continue;let i;try{i=Fs(W.join(e,o.rel),{withFileTypes:!0})}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=o.rel==="."?a.name:W.join(o.rel,a.name);if(r+=1,r>=Ky)break;rd(e,c)&&t.add(c),n.push({rel:c,depth:o.depth+1})}}return[...t].sort()}function RN(e){let t=[];try{let n=W.join(e,"pnpm-workspace.yaml");if(be(n)){let r=!1;for(let o of Yt(n,"utf8").split(`
25
- `)){let i=o.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(i);a?t.push(a[1]):i.trim().length>0&&!/^\s/.test(i)&&(r=!1)}}}else{let r=W.join(e,"package.json");if(be(r)){let o=JSON.parse(Yt(r,"utf8")),i=Array.isArray(o.workspaces)?o.workspaces:o.workspaces?.packages;Array.isArray(i)&&t.push(...i.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function CN(e){let t=[];for(let n of EN(e)){let r=n==="."?e:W.join(e,n),o=s(i=>n==="."?i:W.join(n,i),"prefix");for(let i of RN(r)){if(t.length>=td)break;if(!(i.startsWith("!")||i.includes("**")))try{if(i.endsWith("/*")){let a=i.slice(0,-2),c=W.join(r,a);if(!be(c))continue;for(let l of Fs(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(o(W.join(a,l.name))),t.length>=td)break}else i.includes("*")||t.push(o(i))}catch{}}}return t.slice(0,td)}function Gy(e){let t=null,n=0,r=[e];for(;r.length>0&&n<By;){let o=r.pop();if(o===void 0)break;let i;try{i=Fs(o,{withFileTypes:!0})}catch{continue}for(let a of i){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=W.join(o,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=nd(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=By)break}}}return t}function TN(e,t){let n=new Set;for(let r of t)try{let o=W.join(e,r,"package.json");if(!be(o))continue;let i=JSON.parse(Yt(o,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=i[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 Yy(e){let t=[],n=CN(e),r=TN(e,n);for(let o of n)try{let i=W.join(e,o,"package.json");if(!be(i))continue;let a=JSON.parse(Yt(i,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let v=b.replace(/^\.\//,"").split("/")[0];return v==="build"||v==="dist"?v: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=W.join(e,o,"src"),h=W.join(e,o,u);if(!be(f)||!be(h))continue;let g=Gy(f),y=Gy(h);if(g===null||y===null)continue;let _=g-y;_>xN&&t.push({packageDir:o,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((o,i)=>o.packageDir.localeCompare(i.packageDir))}function AN(e,t){if(!t)return null;let n=IN(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 o=r.filter(i=>i.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:o,allRed:o===r.length&&r.length>0}}function IN(e,t){try{return cN("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function zo(e,t={}){let n=await Jy(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=qy(n),o=zy(r);return{ok:o,verdict:o?"clean":"diverged",reason:null,findings:r,facts:n}}var Wy,id,Vy,lN,dN,uN,Uy,xN,td,By,SN,Ky,sd=w(()=>{"use strict";ed();Ee();qo();Wy=["supabase/config.toml","supabase/.temp",".env"],id=".maind/worktree-requirements",Vy={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},lN=Object.keys(Vy).flatMap(e=>[e,"*/"+e]),dN=["scripts"],uN=512*1024;s(pN,"gatherToolCopyDrift");s(fN,"compareToolDirs");s(qy,"computeDivergence");s(mN,"computeHookFinding");Uy={open:0,warn:1,info:2,passed:3};s(hN,"sortFindings");s(zy,"isHealthy");s(At,"trimOrNull");s(gN,"resolveDefaultBranch");s(yN,"detectInProgressOp");s(_N,"parseWorktrees");s(bN,"readWorktreeRequirements");s(wN,"discoverSupabaseConfigProbes");s(vN,"discoverDependencyDirs");s(kN,"isWorkspaceRoot");s(rd,"hasWorkspaceMarkers");s(Jy,"gatherRepoHealthFacts");s(od,"samePath");xN=2e3,td=64,By=4e3,SN=3,Ky=400;s(EN,"findWorkspaceRoots");s(RN,"workspacePatternsAt");s(CN,"listWorkspacePackageDirs");s(Gy,"newestMtimeUnder");s(TN,"consumedWorkspaceNames");s(Yy,"gatherStalePackageBuilds");s(AN,"gatherReleaseFact");s(IN,"runGh");s(zo,"checkDivergence")});import{existsSync as ad,readdirSync as Xy}from"node:fs";import{posix as gt}from"node:path";function ld(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(cd)}function t_(e,t={}){let n=t.minFiles??dd;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Zy)}function Fr(e){return`${e.dir}#${e.prefix}`}function Yo(e){let t=NN.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function n_(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let o of e.namespaces){let i=Fr(o),a=e.sightingsByNamespace.get(i);if(!a)continue;let c=new Set(a.keys());for(let[l,d]of a){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),f=u.filter(g=>g!==p),h=`${o.prefix}${l}`;t.push(p?{id:`number.collision:${i}#${l}`,status:"open",namespace:o,number:l,title:`${h} is already taken`,detail:`This branch adds ${p}, but ${h} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${o.prefix}${ud(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:${i}#${l}`,status:"info",namespace:o,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((o,i)=>r[o.status]-r[i.status]||o.id.localeCompare(i.id))}function r_(e){return!e.some(t=>t.status==="open")}function ud(e,t){let n=0;for(let r of e){let o=Number(r);Number.isFinite(o)&&(n=Math.max(n,o))}return String(n+1).padStart(t.length,"0")}function pd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function o_(e,t){let n=pd(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},o=Yo(gt.basename(n));if(!o)return r;let i=`${gt.dirname(n)}#${o.prefix}`,a=e.namespaces.find(u=>Fr(u)===i)??null;if(!a)return{...r,number:o.number};let c=e.sightingsByNamespace.get(i)??new Map,l=new Set,d=[];for(let u of c.get(o.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:o.number,taken:d.length>0,sightings:d,suggestion:ud(c.keys(),o.number)}}function i_(e,t){let n={excluded:0,sameAsLocal:0,stale:0,overLimit:0},r=(t.nowMs-t.maxAgeDays*864e5)/1e3,o=[];for(let a of e){if(a.name==="HEAD"||t.excludeRefs.has(a.ref)||a.name===t.ownBranch){n.excluded+=1;continue}if(t.localTips.get(a.name)===a.sha){n.sameAsLocal+=1;continue}if(a.committedAt<r){n.stale+=1;continue}o.push(a)}o.sort((a,c)=>c.committedAt-a.committedAt||a.ref.localeCompare(c.ref));let i=Math.max(0,Math.floor(t.limit));return n.overLimit=Math.max(0,o.length-i),{selected:o.slice(0,i),skipped:n}}function s_(e,t){if(!e)return[];let n=[...t].sort((o,i)=>i.length-o.length),r=[];for(let o of e.split(`
11
+ `),r===null?"created":"appended"}catch{return"skipped"}}var Ns,Bl,OI,Os=w(()=>{"use strict";Ns=[".gitignore","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"],Bl=["# 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).'],OI=Bl;s(Go,"ensureMaindLocalIgnore")});import{execFileSync as DI}from"node:child_process";import{createHash as PI}from"node:crypto";import{existsSync as MI,readFileSync as $I,readdirSync as LI,statSync as FI}from"node:fs";import{posix as Ps,sep as Sy}from"node:path";function I(e,t){try{return DI("git",[...jI,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function HI(e){return Sy==="/"?e:e.split(Sy).join("/")}function Ds(e){let t=[];for(let n of e){let r=HI(n).trim();if(!r||Ko(r))continue;let o=$r(r);o&&t.push({path:r,language:o})}return t}function Ry(e){return Ds(e)}function Cy(e){let t=Tt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Ds(t.split(`
12
+ `));let n=[];return Ty(e,"",n),Ds(n)}function Ty(e,t,n){let r;try{r=LI(Ps.join(e,t),{withFileTypes:!0})}catch{return}for(let o of r){if(o.name.startsWith(".")&&o.name!=="."&&Ey.has(o.name)||Ey.has(o.name))continue;let i=t?`${t}/${o.name}`:o.name;o.isDirectory()?Ty(e,i,n):o.isFile()&&n.push(i)}}function Gl(e,t){return Wl(e,t)??t}function Wl(e,t){let n=I(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Ms(e,t={}){if(Wo(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Gl(e,t.since):"HEAD",o=["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");o.push("HEAD")}let i=Tt(e,o);if(i===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of i.split(`
13
+ `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=Kl((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 p=l.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=Kl(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 Kl(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Vl(e,t={}){let n=Ms(e,t);return n===null?null:Ds(n.keys())}function Ay(e,t){try{let n=FI(Ps.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function $s(e){return PI("sha256").update(e).digest("hex")}function Wo(e){return Tt(e,["rev-parse","HEAD"])?.trim()??null}function Ls(e,t){return Tt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function ql(e){let t=Tt(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
15
+ `).filter(o=>o.trim().length>0),r=BI(e);return n.some(o=>r===null||!Iy(e,o,r))?!0:r!==null&&UI(e,r)}function UI(e,t){if(!MI(Ps.join(e,".maind",".gitignore")))return!1;let n=Tt(e,["ls-files","--full-name","--",".maind/.gitignore"]);return n===null?!0:n.trim().length>0?!1:!Iy(e,`?? ${t}`,t)}function BI(e){let t=Tt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function Iy(e,t,n){let r=t[0],o=t[1];if(Kl(t.slice(3))!==n)return!1;let i;if(r==="?"&&o==="?"||r==="A"&&(o===" "||o==="M"))i="";else if((r===" "||r==="M")&&(o===" "||o==="M")){let p=Tt(e,["show",`HEAD:${n}`]);if(p===null)return!1;i=p}else return!1;let a;try{a=$I(Ps.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=s(p=>p.replace(/\r\n/g,`
16
+ `),"norm"),l=c(i),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...Ns,...Bl]);return d.slice(l.length).split(`
17
+ `).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var Ey,jI,Tt,Ee=w(()=>{"use strict";Is();Os();Ey=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),jI=["-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(I,"runGit");Tt=I;s(HI,"toPosix");s(Ds,"classify");s(Ry,"classifyPaths");s(Cy,"discoverSourceFiles");s(Ty,"walk");s(Gl,"resolveDiffBase");s(Wl,"resolveMergeBase");s(Ms,"enumerateChangedPaths");s(Kl,"unquote");s(Vl,"changedSourceFiles");s(Ay,"statFile");s($s,"hashContent");s(Wo,"headCommit");s(Ls,"resolveCommitSha");s(ql,"isWorktreeDirty");s(UI,"hasForeignUntrackedIgnore");s(BI,"toolIgnoreRepoPath");s(Iy,"isToolOnlyIgnoreChange")});function Oy(e,t={}){if(I(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Gl(e,t.since):"HEAD",o=["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");o.push("HEAD")}let i=I(e,o);if(i===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(i,"utf8")>KI?c="none":qI(i,a,()=>{c="partial"}),n){let l=I(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 qI(e,t,n){let r=null,o=0,i=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,o=0},"commit");for(let l of e.split(`
19
+ `)){if(l.startsWith("diff --git ")){c(),i=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){i=!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":i?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=VI.exec(l);if(d){if(o++,o>GI){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<WI&&r.addedLines.push(l.slice(1))}c()}var KI,GI,WI,Ny,VI,Dy=w(()=>{"use strict";Ee();KI=16*1024*1024,GI=500,WI=4e3,Ny=256*1024,VI=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Oy,"changedHunks");s(qI,"parseUnifiedDiff")});function Jl(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,o=0,i=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=Fy&&r++,c>o&&(o=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>i&&(i=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:o,distinct_authors:n.size,newest_change_age_days:i>0?Math.max(0,Math.floor((t-i)/864e5)):0}}function YI(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function My(e){return e.split(zI).filter(t=>t.trim().length>0)}function $y(e){let[t,n,r,o,i]=e.replace(/\n+$/,"").split(JI);return!t||!o?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:o,subject:i??""}}function XI(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,o=t.get(r);o?o.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 jy(e,t,n={}){let r=YI(n.limit,20,100),o=n.includeOwnership!==!1,i=Math.max(r,Ly),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,zl),l=[];for(let u of c){let p=I(e,["log","-n",String(i),Py,"--",u]),f=p===null?[]:My(p).map($y).filter(h=>h!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:o?{topAuthors:XI(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=Ls(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=I(e,["log",...p,"-n",String(Fs+1),Py,"--name-only","--",...c]),h=[];if(f!==null)for(let g of My(f)){let y=g.split(`
20
+ `),_=$y(y[0]??"");if(!_)continue;let b=y.slice(1).filter(v=>v.trim().length>0).length;h.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,Fs),truncated:h.length>Fs}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>zl}}var zI,JI,Ly,zl,Fs,Py,Fy,Yl=w(()=>{"use strict";Ee();zI="",JI="\0",Ly=200,zl=50,Fs=100,Py="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",Fy=10;s(Jl,"aggregateHistoryContext");s(YI,"clamp");s(My,"splitRecords");s($y,"parseHistoryRecord");s(XI,"aggregateOwnership");s(jy,"readFileHistory")});import{execFileSync as ZI}from"node:child_process";import{readdirSync as QI,statSync as Hy}from"node:fs";import{isAbsolute as eN,join as Xl,relative as tN,resolve as nN}from"node:path";function oN(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function iN(e,t){try{let n=ZI("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 sN(e){let t;try{t=QI(e)}catch{return null}for(let n of t.filter(oN))try{let r=Hy(Xl(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function aN(e){try{return Hy(e).isDirectory()}catch{return!1}}function cN(e,t){let n=tN(e,t);return!n||n.startsWith("..")?t:n}function Zl(e){let t=rN.filter(c=>aN(Xl(e,c))),n=iN(e,"core.hooksPath"),r=n?eN(n)?n:nN(e,n):Xl(e,".git","hooks"),o=cN(e,r),i=sN(r);if(i===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:o};let a=n?i===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:o}}function Ql(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 rN,ed=w(()=>{"use strict";rN=[".githooks",".husky"];s(oN,"isRealHook");s(iN,"gitConfig");s(sN,"hasExecutableHook");s(aN,"isDir");s(cN,"displayPath");s(Zl,"resolveHookState");s(Ql,"describeHookState")});import{posix as Uy}from"node:path";function Lr(e){let t=lN.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=I(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(i=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||i===c||i.startsWith(`${c}/`)}),"wanted"),o=new Map;for(let i of n.split("\0").filter(Boolean)){if(!r(i))continue;let a=Uy.basename(i),c=Lr(a);if(c===null)continue;let l=Uy.dirname(i),d=o.get(l)??[];d.push({path:i,name:a,version:c}),o.set(l,d)}return[...o.entries()].map(([i,a])=>({dir:i,files:a.sort((c,l)=>At(c.version,l.version))})).sort((i,a)=>i.dir.localeCompare(a.dir))}function Vo(e){let t=I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var lN,qo=w(()=>{"use strict";Ee();lN=/^(\d+)_.+\.sql$/;s(Lr,"parseMigrationVersion");s(At,"compareVersions");s(Hn,"discoverSupabaseProjects");s(Vo,"resolveDefaultBranch")});import{execFileSync as dN}from"node:child_process";import{existsSync as be,readFileSync as Yt,readdirSync as js,statSync as nd}from"node:fs";import{posix as W}from"node:path";function mN(e,t){let n=(()=>{let o=I(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return o?o.trim():null})(),r=W.dirname(e);for(let o=0;o<8&&r&&r!==W.dirname(r);o++){if(be(W.join(r,".git"))){let i=(()=>{let c=I(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&i!=null&&od(n,i))){let c=hN(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=W.dirname(r)}return null}function hN(e,t){let n=[];for(let r of pN){let o;try{o=js(W.join(e,r),{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name)}catch{continue}for(let i of o){let a=`${r}/${i}`,c=W.join(e,a),l=W.join(t,a);try{let d=nd(c),u=nd(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>fN)continue;Yt(c).equals(Yt(l))||n.push(a)}catch{continue}}}return n.sort()}function zy(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,o=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}${o>0?` (and ${o} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let i=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(i){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(!i&&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 ${id}.`})}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 ${W.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=gN(e.hooks);return a&&t.push(a),yN(t)}function gN(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:Ql(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 yN(e){return[...e].sort((t,n)=>By[t.status]-By[n.status]||t.id.localeCompare(n.id))}function Jy(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function It(e){let t=e?.trim();return t||null}function _N(e){let t=It(I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function bN(e){let t=It(I(e,["rev-parse","--git-dir"]));if(!t)return null;let n=W.isAbsolute(t)?t:W.join(e,t);return be(W.join(n,"rebase-merge"))||be(W.join(n,"rebase-apply"))?"rebase":be(W.join(n,"MERGE_HEAD"))?"merge":be(W.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function wN(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let o of e.split(`
21
+ `))if(o.startsWith("worktree "))r(),n={path:o.slice(9).trim(),detached:!1};else if(n)o.startsWith("branch ")?n.branch=o.slice(7).trim().replace(/^refs\/heads\//,""):o.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function vN(e){let t=W.join(e,id);if(!be(t))return[];try{return Yt(t,"utf8").split(`
22
+ `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function kN(e){try{return Hn(e).map(t=>W.join(W.dirname(t.dir),"config.toml"))}catch{return[]}}function xN(e){let t=I(e,["ls-files","-z","--",...uN]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let o=qy[W.basename(r)];if(o===void 0)continue;let i=W.dirname(r);if(!SN(e,i))continue;let a=i==="."?"node_modules":W.join(i,"node_modules");n.has(a)||n.set(a,{dir:a,install:o})}return[...n.values()]}function SN(e,t){return t==="."?!0:rd(e,t)}function rd(e,t){if(be(W.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Yt(W.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Yy(e,t={}){if(It(I(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=It(I(e,["rev-parse","--abbrev-ref","HEAD"])),o=r==="HEAD",i=o?null:r,a=_N(e),c=It(I(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let K=It(I(e,["rev-parse","HEAD"])),x=It(I(e,["rev-parse","@{u}"]));l=K!=null&&x!=null?K===x:null,d=I(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(a){let K=It(I(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(K){let[x,T]=K.split(/\s+/).map(D=>Number.parseInt(D,10));Number.isFinite(x)&&(p=x),Number.isFinite(T)&&(u=T)}}let h=(I(e,["status","--porcelain"])??"").split(`
23
+ `).filter(K=>K.trim().length>0).length,g=bN(e),y=It(I(e,["rev-parse","--show-toplevel"]))??e,_=wN(I(e,["worktree","list","--porcelain"])??""),b=_[0]?.path??null,v=b!=null&&od(b,y),k=Math.max(0,_.length-1),E=null;if(b&&!od(b,y)){let K=s(T=>be(W.join(b,T))&&!be(W.join(y,T)),"here"),x=[...Vy,...kN(y),...vN(y),...t.probePaths??[]];E={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(x.filter(K))],missingDeps:xN(y).filter(T=>K(T.dir))}}let S=mN(y,e),R=t.includeRelease===!1?null:NN(e,i),P=[];return a&&(P=(I(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
24
+ `).map(x=>x.trim()).filter(x=>x.length>0)),{isRepo:!0,branch:i,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:h,detachedHead:o,inProgressOp:g,isSharedMainTree:v,otherWorktrees:k,worktreeParity:E,toolCopyDrift:S,stalePackageBuilds:Xy(y),release:R,unmergedMigrations:P,hooks:Zl(e)}}function od(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function CN(e){let t=new Set;rd(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Gy;){let o=n.pop();if(o===void 0)break;if(o.depth>=RN)continue;let i;try{i=js(W.join(e,o.rel),{withFileTypes:!0})}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=o.rel==="."?a.name:W.join(o.rel,a.name);if(r+=1,r>=Gy)break;rd(e,c)&&t.add(c),n.push({rel:c,depth:o.depth+1})}}return[...t].sort()}function TN(e){let t=[];try{let n=W.join(e,"pnpm-workspace.yaml");if(be(n)){let r=!1;for(let o of Yt(n,"utf8").split(`
25
+ `)){let i=o.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(i);a?t.push(a[1]):i.trim().length>0&&!/^\s/.test(i)&&(r=!1)}}}else{let r=W.join(e,"package.json");if(be(r)){let o=JSON.parse(Yt(r,"utf8")),i=Array.isArray(o.workspaces)?o.workspaces:o.workspaces?.packages;Array.isArray(i)&&t.push(...i.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function AN(e){let t=[];for(let n of CN(e)){let r=n==="."?e:W.join(e,n),o=s(i=>n==="."?i:W.join(n,i),"prefix");for(let i of TN(r)){if(t.length>=td)break;if(!(i.startsWith("!")||i.includes("**")))try{if(i.endsWith("/*")){let a=i.slice(0,-2),c=W.join(r,a);if(!be(c))continue;for(let l of js(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(o(W.join(a,l.name))),t.length>=td)break}else i.includes("*")||t.push(o(i))}catch{}}}return t.slice(0,td)}function Wy(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Ky;){let o=r.pop();if(o===void 0)break;let i;try{i=js(o,{withFileTypes:!0})}catch{continue}for(let a of i){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=W.join(o,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=nd(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Ky)break}}}return t}function IN(e,t){let n=new Set;for(let r of t)try{let o=W.join(e,r,"package.json");if(!be(o))continue;let i=JSON.parse(Yt(o,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=i[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 Xy(e){let t=[],n=AN(e),r=IN(e,n);for(let o of n)try{let i=W.join(e,o,"package.json");if(!be(i))continue;let a=JSON.parse(Yt(i,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let v=b.replace(/^\.\//,"").split("/")[0];return v==="build"||v==="dist"?v: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=W.join(e,o,"src"),h=W.join(e,o,u);if(!be(f)||!be(h))continue;let g=Wy(f),y=Wy(h);if(g===null||y===null)continue;let _=g-y;_>EN&&t.push({packageDir:o,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((o,i)=>o.packageDir.localeCompare(i.packageDir))}function NN(e,t){if(!t)return null;let n=ON(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 o=r.filter(i=>i.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:o,allRed:o===r.length&&r.length>0}}function ON(e,t){try{return dN("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function zo(e,t={}){let n=await Yy(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=zy(n),o=Jy(r);return{ok:o,verdict:o?"clean":"diverged",reason:null,findings:r,facts:n}}var Vy,id,qy,uN,pN,fN,By,EN,td,Ky,RN,Gy,sd=w(()=>{"use strict";ed();Ee();qo();Vy=["supabase/config.toml","supabase/.temp",".env"],id=".maind/worktree-requirements",qy={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},uN=Object.keys(qy).flatMap(e=>[e,"*/"+e]),pN=["scripts"],fN=512*1024;s(mN,"gatherToolCopyDrift");s(hN,"compareToolDirs");s(zy,"computeDivergence");s(gN,"computeHookFinding");By={open:0,warn:1,info:2,passed:3};s(yN,"sortFindings");s(Jy,"isHealthy");s(It,"trimOrNull");s(_N,"resolveDefaultBranch");s(bN,"detectInProgressOp");s(wN,"parseWorktrees");s(vN,"readWorktreeRequirements");s(kN,"discoverSupabaseConfigProbes");s(xN,"discoverDependencyDirs");s(SN,"isWorkspaceRoot");s(rd,"hasWorkspaceMarkers");s(Yy,"gatherRepoHealthFacts");s(od,"samePath");EN=2e3,td=64,Ky=4e3,RN=3,Gy=400;s(CN,"findWorkspaceRoots");s(TN,"workspacePatternsAt");s(AN,"listWorkspacePackageDirs");s(Wy,"newestMtimeUnder");s(IN,"consumedWorkspaceNames");s(Xy,"gatherStalePackageBuilds");s(NN,"gatherReleaseFact");s(ON,"runGh");s(zo,"checkDivergence")});import{existsSync as ad,readdirSync as Zy}from"node:fs";import{posix as gt}from"node:path";function ld(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(cd)}function n_(e,t={}){let n=t.minFiles??dd;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Qy)}function Fr(e){return`${e.dir}#${e.prefix}`}function Yo(e){let t=DN.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function r_(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let o of e.namespaces){let i=Fr(o),a=e.sightingsByNamespace.get(i);if(!a)continue;let c=new Set(a.keys());for(let[l,d]of a){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),f=u.filter(g=>g!==p),h=`${o.prefix}${l}`;t.push(p?{id:`number.collision:${i}#${l}`,status:"open",namespace:o,number:l,title:`${h} is already taken`,detail:`This branch adds ${p}, but ${h} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${o.prefix}${ud(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:${i}#${l}`,status:"info",namespace:o,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((o,i)=>r[o.status]-r[i.status]||o.id.localeCompare(i.id))}function o_(e){return!e.some(t=>t.status==="open")}function ud(e,t){let n=0;for(let r of e){let o=Number(r);Number.isFinite(o)&&(n=Math.max(n,o))}return String(n+1).padStart(t.length,"0")}function pd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function i_(e,t){let n=pd(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},o=Yo(gt.basename(n));if(!o)return r;let i=`${gt.dirname(n)}#${o.prefix}`,a=e.namespaces.find(u=>Fr(u)===i)??null;if(!a)return{...r,number:o.number};let c=e.sightingsByNamespace.get(i)??new Map,l=new Set,d=[];for(let u of c.get(o.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:o.number,taken:d.length>0,sightings:d,suggestion:ud(c.keys(),o.number)}}function s_(e,t){let n={excluded:0,sameAsLocal:0,stale:0,overLimit:0},r=(t.nowMs-t.maxAgeDays*864e5)/1e3,o=[];for(let a of e){if(a.name==="HEAD"||t.excludeRefs.has(a.ref)||a.name===t.ownBranch){n.excluded+=1;continue}if(t.localTips.get(a.name)===a.sha){n.sameAsLocal+=1;continue}if(a.committedAt<r){n.stale+=1;continue}o.push(a)}o.sort((a,c)=>c.committedAt-a.committedAt||a.ref.localeCompare(c.ref));let i=Math.max(0,Math.floor(t.limit));return n.overLimit=Math.max(0,o.length-i),{selected:o.slice(0,i),skipped:n}}function a_(e,t){if(!e)return[];let n=[...t].sort((o,i)=>i.length-o.length),r=[];for(let o of e.split(`
26
26
  `)){if(!o.trim())continue;let[i="",a="",c="",l=""]=o.split("\0");if(l.trim().length>0)continue;let d=n.find(f=>i.startsWith(`refs/remotes/${f}/`));if(!d)continue;let u=i.slice(`refs/remotes/${d}/`.length),p=Number(c.trim().split(/\s+/)[0]);!u||!/^[0-9a-f]{40,64}$/.test(a)||!Number.isFinite(p)||r.push({ref:i,remote:d,name:u,sha:a,committedAt:p})}return r}function Jo(e){let t=e?.trim();return t||null}function Un(e){return e?e.split(`
27
- `).filter(Boolean):[]}function ON(e){let t=Jo(I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function a_(e,t={}){let n=t.minFiles??dd,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let o=I(e,r);if(o===null)return[];let i=new Map;for(let a of o.split("\0").filter(Boolean)){let c=gt.dirname(a),l=Yo(gt.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=i.get(d);u?u.numbers.push(l.number):i.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...i.values()].filter(a=>t_(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)=>Fr(a).localeCompare(Fr(c)))}async function fd(e,t={}){let n=[];if(Jo(I(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 o=a_(e,t),i=new Map(o.map(_=>[Fr(_),_])),a=[...new Set(o.map(_=>_.dir))],c=new Map,l=s((_,b,v)=>{let k=gt.dirname(_),E=Yo(gt.basename(_));if(!E)return;let S=`${k}#${E.prefix}`;if(!i.has(S))return;let R=c.get(S)??new Map,P=R.get(E.number)??[];P.push({kind:b,where:v,path:_}),R.set(E.number,P),c.set(S,R)},"record"),d=s((_,b,v)=>{if(a.length===0)return;let k=I(e,["ls-tree","-r","--name-only",_,"--",...a]);if(k===null){n.push(`could not read ${v}`);return}for(let E of Un(k))l(E,b,v)},"scanTree");for(let _ of a){let b=gt.join(e,_);if(ad(b))try{for(let v of Xy(b))l(`${_}/${v}`,"self","this worktree")}catch{n.push(`could not read ${_}`)}}let u=ON(e),p=t.baseRef??(u?`origin/${u}`:null);p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let f=Jo(I(e,["rev-parse","--abbrev-ref","HEAD"])),h=new Map;if(t.includeBranches!==!1)for(let _ of Un(I(e,["for-each-ref","--format=%(refname:short)%00%(objectname)","refs/heads"]))){let[b="",v=""]=_.split("\0");!b||b===f||(d(b,"branch",`Branch ${b}`),h.set(b,v))}let g;if(t.includeRemoteBranches??t.includeBranches!==!1){let _=Un(I(e,["remote"])).map(S=>S.trim()),b=s_(I(e,["for-each-ref","--format=%(refname)%00%(objectname)%00%(committerdate:raw)%00%(symref)","refs/remotes"]),_),v=new Set;u&&v.add(`refs/remotes/origin/${u}`),p&&v.add(p.startsWith("refs/")?p:`refs/remotes/${p}`);let k=Jo(I(e,["rev-parse","--symbolic-full-name","--verify","--quiet","@{upstream}"]));k?.startsWith("refs/remotes/")&&v.add(k);let E=i_(b,{excludeRefs:v,ownBranch:f&&f!=="HEAD"?f:null,localTips:h,nowMs:t.nowMs??Date.now(),maxAgeDays:t.remoteBranchMaxAgeDays??Qy,limit:t.remoteBranchLimit??e_});for(let S of E.selected)d(S.ref,"remote_branch",`Remote branch ${S.remote}/${S.name}`);g={scanned:E.selected.map(S=>`${S.remote}/${S.name}`),...E.skipped}}if(t.includeWorktrees!==!1){let _=Jo(I(e,["rev-parse","--show-toplevel"]));for(let b of Un(I(e,["worktree","list","--porcelain"]))){if(!b.startsWith("worktree "))continue;let v=b.slice(9).trim();if(!(!v||v===_||!ad(v)))for(let k of a){let E=gt.join(v,k);if(ad(E))try{for(let S of Xy(E))l(`${k}/${S}`,"worktree",`Worktree ${v}`)}catch{n.push(`could not read ${k} in ${v}`)}}}}let y=[];if(p&&a.length>0){let _=I(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);_===null?n.push(cd):y=Un(_);let b=I(e,["ls-files","--others","--exclude-standard","--",...a]);b!==null&&(y=[...y,...Un(b)]);let v=I(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);v!==null&&(y=[...y,...Un(v)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:o,sightingsByNamespace:c,addedPaths:y,skipped:n,...g?{remoteBranches:g}:{}}}async function Bn(e,t={}){let n=await fd(e,t),r=n_(n);return{ok:r_(r),findings:r,facts:n}}async function Kn(e,t,n={}){let r=pd(t);if(!Yo(gt.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let o=await fd(e,{...n,dirs:n.dirs??[gt.dirname(r)]});return o_(o,r)}var cd,NN,dd,Zy,Qy,e_,Xo=w(()=>{"use strict";Ee();cd="could not diff against the base ref \u2014 everything reported as info";s(ld,"isNumberCollisionsGraded");NN=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,dd=3,Zy=.8,Qy=30,e_=100;s(t_,"isCounterNamespace");s(Fr,"namespaceKey");s(Yo,"parseNumbered");s(n_,"computeNumberCollisions");s(r_,"isCollisionFree");s(ud,"suggestNextNumber");s(pd,"normaliseRepoPath");s(o_,"checkProposedNumber");s(i_,"selectRemoteBranches");s(s_,"parseRemoteRefs");s(Jo,"trimOrNull");s(Un,"lines");s(ON,"resolveDefaultBranch");s(a_,"detectNamespaces");s(fd,"gatherNumberCollisionFacts");s(Bn,"checkNumberCollisions");s(Kn,"checkNumberForPath")});import{execFileSync as DN}from"node:child_process";import{createHash as PN}from"node:crypto";function md(e){return PN("sha256").update(e).digest("hex")}function MN(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 $N(e){let t=MN(e);return t?md(t):null}function FN(e){return typeof e=="string"&&LN.test(e)}function c_(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(FN(t))return t;let n;try{n=DN("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?$N(n):null}var LN,hd=w(()=>{"use strict";s(md,"sha256Hex");s(MN,"normalizeRemoteUrl");s($N,"projectKeyFromRemote");LN=/^[a-f0-9]{64}$/;s(FN,"isProjectKey");s(c_,"computeProjectKey")});function bd(e){return`spec.${e}`}function jr(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 jN(e,t){let n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let i=0;i<o;i++){let a=(n[i].codePointAt(0)??0)-(r[i].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function l_(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(jN)}function Qo(e){return md(JSON.stringify(l_(e)))}var Zo,gd,yd,_d,wd=w(()=>{"use strict";hd();Zo={det_number_collisions:{version:"1.3.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"]}},gd="number.collision",yd="theme.dead_class",_d="acl.missing_revoke";s(bd,"specDriftRuleId");s(jr,"gradeEngineStatus");s(jN,"codePointCompare");s(l_,"normalizeEvidenceForHash");s(Qo,"hashDetectorEvidence")});import{existsSync as HN,readFileSync as d_}from"node:fs";import{posix as UN}from"node:path";function Us(e,t){let n=e[t],r=t+1;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===n)return r+1;r++}return e.length}function Bs(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
28
- `,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 ei(e){return e==='"'||e==="'"||e==="`"}function Ks(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function js(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,o=t;for(;o<e.length;){let i=e[o];if(ei(i)){o=Us(e,o);continue}if(Ks(e,o)){o=Bs(e,o);continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r===0))return e.slice(t,o+1);o++}return null}function BN(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Ks(e,t)){t=Bs(e,t);continue}break}return e.slice(t)}function Hr(e){let t=[],n=0,r=0,o=0;for(;o<e.length;){let i=e[o];if(ei(i)){o=Us(e,o);continue}if(Ks(e,o)){o=Bs(e,o);continue}i==="["||i==="{"||i==="("?n++:i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,o)),r=o+1),o++}return t.push(e.slice(r)),t.map(i=>BN(i).trim()).filter(i=>i.length>0)}function m_(e){let t=Us(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,o)=>o==="n"?`
29
- `:o==="r"?"\r":o==="t"?" ":o)}function KN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kd(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${KN(t)}\b`,"m").exec(e);if(!r)return null;let o=r.index+r[0].length,i=!1;for(;o<e.length;){let a=e[o];if(ei(a)){o=Us(e,o);continue}if(Ks(e,o)){o=Bs(e,o);continue}if(!i){if(a==="="&&e[o+1]!=="="&&!"=!<>".includes(e[o-1]??" "))i=!0;else if(a===";")return null;o++;continue}if(a==="[")return js(e,o);if(a===";")return null;o++}return null}function xd(e){let t={};if(!e.startsWith("{"))return t;for(let n of Hr(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let o=r[2]??r[3],i=r[4].trim();ei(i[0]??"")&&(t[o]=m_(i))}return t}function GN(e,t){if(!e.startsWith("{"))return null;for(let n of Hr(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 h_(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function g_(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function y_(e,t){let n=kd(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=g_(),o=[],i=0;for(let a of Hr(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=xd(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");o.push({key:l,fields:h_(c,t.fields),orderPath:d,ordinal:r(d)})}return o.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:o,error:null,dropped:i}}function __(e,t){let n=kd(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=g_(),o=[],i=0,a=s((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of Hr(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){i++;continue}let y=xd(f);for(let[_,b]of Object.entries(u.fields??{}))h[_]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let _=GN(f,u.children);g=_&&_.startsWith("[")?js(_,0):null}}else{if(!f.startsWith("[")){i++;continue}let y=Hr(f.slice(1,-1));for(let[_,b]of Object.entries(u.fields??{})){let v=y[Number(b)];h[_]=v!==void 0&&ei(v[0]??"")?m_(v):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?js(_,0):null}}if(p){let y=h[t.key_field];if(!y){i++;continue}let _=(t.partition_by??[]).map(b=>h[b]??"");o.push({key:y,fields:h_(h,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),o.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:o,error:null,dropped:i}}function u_(e,t){return t.extractor==="object-array"?y_(e,t):__(e,t)}function b_(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(o=>n.has(o.replace("{key}",r).replace(/\/{2,}/g,"/")))}function w_(e,t,n){return`spec.drift:${e}#${t}:${n}`}function WN(e){return e.orderPath.join(" / ")||"(flat)"}function v_(e,t,n,r){let o=[],i=s((d,u,p,f,h,g)=>{o.push({id:w_(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:h,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){i("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${WN(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=d.fields[p]??"",h=u.fields[p]??"";f!==h&&i("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${h||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),f=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),h=new Set(f),g=p.filter(y=>h.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";i("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
30
- 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)||i("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(b_(d,e.grounding,r))continue;let u=a.has(d);i("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 o}function VN(e,t,n){let r=[];for(let o of e.assertions??[]){let i=n.get(o.path);if(!i)continue;let a=i.indexOf(o.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(i.slice(a+o.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[o.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${o.path}`,contract:e.id,dimension:"assertion",status:"warn",key:o.path,title:`${o.path} states ${l} where the ${o.counts} side has ${d}`,detail:`Counted after "${o.prefix}". ${o.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function p_(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 k_(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 o=s(u=>{let p=[],f=[];for(let h of r){let g=u.get(h.spec.path),y=u.get(h.impl.path);if(g==null||y==null){let k=g==null?h.spec.path:h.impl.path;p.push(p_(h.id,`Declared file could not be read: ${k}`)),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=u_(g,h.spec),b=u_(y,h.impl);if(_.error||b.error){p.push(p_(h.id,_.error??b.error??"unknown")),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let v=_.dropped>0||b.dropped>0;f.push({id:h.id,measured:!0,specRecords:_.records.length,implRecords:b.records.length,partial:v}),v&&p.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.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(...v_(h,_.records,b.records,e.files)),p.push(...VN(h,{spec:_.records.length,impl:b.records.length},u))}return{findings:p,contracts:f}},"runOnce"),i=o(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of o(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(w_(u.id,p.dimension,p.key),p);let l=i.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}
31
- Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>f_[u.status]-f_[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:i.contracts}}function vd(e){let t=e?.trim();return t||null}function Gs(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"),o=n(t);if(!o||!Array.isArray(o.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let i=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of o.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return i(`${u}: not an object`);if(!d)return i(`${u}: \`id\` is missing`);if(!r(l.reason))return i(`${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 i(`${u}: \`${p}\` is missing`);let h=r(f.extractor);if(!h)return i(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return i(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return i(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(f.levels))return i(`${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 i(`${u}: exception for "${r(f?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:o,error:null}}function qN(e){let t=vd(I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function zN(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 x_(e,t={}){let n=s((g,y)=>UN.join(g,y),"join"),r=t.manifestPath??Hs,o=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:o};if(vd(I(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!HN(a))return{...i,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}=Gs(d_(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...i,isRepo:!0,manifestError:l};let d=new Map;for(let g of zN(c))try{d.set(g,d_(n(e,g),"utf8"))}catch{d.set(g,null),o.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=I(e,["ls-files","-z"]);if(p===null)o.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let f=null,h=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:qN(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)o.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=vd(I(e,["merge-base",y,"HEAD"])),!f)o.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())h.set(_,I(e,["show",`${f}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:f,files:u,skipped:o}}async function Gn(e,t={}){let n=await x_(e,t);return{...k_(n,t),facts:n}}function Sd(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Hs,f_,ti=w(()=>{"use strict";Ee();Hs=".maind/spec-contracts.json";s(Us,"endOfString");s(Bs,"skipComment");s(ei,"isQuote");s(Ks,"isCommentStart");s(js,"sliceBalanced");s(BN,"stripLeadingTrivia");s(Hr,"splitTopLevel");s(m_,"readStringLiteral");s(KN,"escapeRe");s(kd,"findSymbolArray");s(xd,"parseObjectFields");s(GN,"objectFieldRaw");s(h_,"pickFields");s(g_,"makeOrdinals");s(y_,"extractObjectArray");s(__,"extractNestedList");s(u_,"extractRecords");s(b_,"isGrounded");s(w_,"findingId");s(WN,"partitionOf");s(v_,"compareContract");s(VN,"checkAssertions");s(p_,"unreadable");f_={open:0,warn:1,info:2,passed:3};s(k_,"computeSpecDrift");s(vd,"trimOrNull");s(Gs,"parseManifest");s(qN,"resolveDefaultBranch");s(zN,"declaredPaths");s(x_,"gatherSpecDriftFacts");s(Gn,"checkSpecDrift");s(Sd,"isSpecDriftGraded")});import{execFileSync as JN}from"node:child_process";import{existsSync as YN,readFileSync as XN}from"node:fs";import{join as ZN}from"node:path";function ni(e){let t=[],n=e.split(`
32
- `);for(let r=0;r<n.length;r+=1){let o=n[r]??"";if(!/^##(?!#)\s/.test(o))continue;let i=/(\d+\.\d+\.\d+)/.exec(o);i&&t.push({version:i[1],line:r+1,raw:o.trim(),shape:/^##\s+Unreleased\b/i.test(o)?"unreleased-labelled":QN.test(o)?"never-published":"released"})}return t}function E_(e){let t=new Map;for(let n of ni(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(o=>o.line),shapes:r.map(o=>o.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function R_(e,t){let n=E_(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of ni(t))r.set(a.version,(r.get(a.version)??0)+1);let o=[],i=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?o:i).push({...a,countBefore:c})}return{introduced:o,preExisting:i,baseResolved:!0}}function C_(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 o=R_(r.head,e.baseRef===null?null:r.base);for(let i of o.introduced)t.push({path:r.path,version:i.version,level:"open",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} has ${i.count} headings (was ${i.countBefore})`});for(let i of o.preExisting)t.push({path:r.path,version:i.version,level:"info",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} already had ${i.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function S_(e,t){try{return JN("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function eO(e,t={}){let n=S_(["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(),o=t.baseRef??null,i=r.map(a=>{let c=ZN(e,a);return{path:a,head:YN(c)?XN(c,"utf8"):null,base:o===null?null:S_(["show",`${o}:${a}`],e)}});return{isRepo:!0,baseRef:o,files:i}}function Ed(e,t={}){return C_(eO(e,t))}var QN,Ws=w(()=>{"use strict";QN=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;s(ni,"parseVersionHeadings");s(E_,"findDuplicateHeadings");s(R_,"classifyIntroduced");s(C_,"computeChangelogDuplicates");s(S_,"git");s(eO,"gatherChangelogFacts");s(Ed,"checkChangelogDuplicates")});import{execFileSync as tO}from"node:child_process";import{existsSync as nO,readFileSync as T_}from"node:fs";import{dirname as A_,join as I_}from"node:path";function O_(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]??[]),o=new Set(n.documentedBase??n.documented),i=[...n.documented].sort(jo);for(let a of i){if(r.has(a)||jo(a,n.version)>=0)continue;let c=!o.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(jo))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 N_(e){let t=ni(e),n=[...new Set(t.filter(i=>i.shape!=="never-published").map(i=>i.version))],r=new Set(n),o=[...new Set(t.filter(i=>i.shape==="never-published"&&!r.has(i.version)).map(i=>i.version))];return{documented:n,neverPublished:o}}function Rd(e,t){try{return tO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function D_(e,t=null){let n=Rd(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let o of[...new Set(n.split("\0").filter(Boolean))].sort()){let i;try{i=JSON.parse(T_(I_(e,o),"utf8"))}catch{continue}if(i.private===!0||typeof i.name!="string"||typeof i.version!="string")continue;let a=A_(o)==="."?"":A_(o),c=I_(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=nO(c)?N_(T_(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Rd(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:N_(p).documented;r.push({dir:a,name:i.name,version:i.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function rO(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 P_(e,t={}){if(Rd(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=D_(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??rO,o={};for(let i of n)try{o[i.name]=await r(i.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${i.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:o,registryReachable:!0,registryError:null}}async function Cd(e,t={}){return O_(await P_(e,t))}var Td=w(()=>{"use strict";Ho();Ws();s(O_,"computeReleaseClaims");s(N_,"claimsOf");s(Rd,"git");s(D_,"discoverPackages");s(rO,"packument");s(P_,"gatherReleaseClaimsFacts");s(Cd,"checkReleaseClaims")});import{execFileSync as oO}from"node:child_process";import{existsSync as iO,readFileSync as sO}from"node:fs";import{join as aO}from"node:path";function Id(e){let t=[],n=!1;for(let r of e.split(`
33
- `)){let o=r.trim();if(n){o===F_&&(n=!1);continue}if(o===L_){n=!0;continue}t.push(r)}return t.join(`
34
- `)}function M_(e){return e.split(`
35
- `).map(t=>t.trim()).filter(t=>t.length>0)}function j_(e,t){let n=new Map;for(let i of M_(t??""))n.set(i,(n.get(i)??0)+1);let r=[];for(let i of M_(e)){let a=n.get(i)??0;a>0?n.set(i,a-1):r.push(i)}let o=0;for(let i of n.values())o+=i;return{added:r,removed:o,net:Math.max(0,r.length-o)}}function H_(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=j_(Id(n.head),n.base===null?null:Id(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 Ad(e,t){try{return oO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function U_(e,t={}){let n=Ad(["ls-files","-z","--",...$_],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Ad(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,i=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=aO(e,a);return{path:a,head:iO(c)?sO(c,"utf8"):null,base:r===null?null:Ad(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:i}}function Nd(e,t={}){return H_(U_(e,t))}var $_,L_,F_,Od=w(()=>{"use strict";$_=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],L_="<!-- maind:conventions v1 begin -->",F_="<!-- maind:conventions v1 end -->";s(Id,"stripManagedConventionsBlock");s(M_,"contentLines");s(j_,"proseDelta");s(H_,"computeAgentDocProse");s(Ad,"git");s(U_,"gatherAgentDocProseFacts");s(Nd,"checkAgentDocProse")});var B_,K_,Dd=w(()=>{"use strict";B_=[".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"],K_=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 cO}from"node:child_process";import{existsSync as lO,readFileSync as dO}from"node:fs";import{join as uO}from"node:path";function W_(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?[]:Ts(n.base).map(o=>o.value));for(let o of Ts(n.content)){let i=o.value.length>60?`${o.value.slice(0,57)}\u2026`:o.value,a=e.baseRef!==null&&!r.has(o.value);t.push({path:n.path,level:a?"open":"info",line:o.line,value:o.value,title:`${n.path}:${o.line}: unquoted plain scalar containing ": " \u2014 ${i}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function G_(e,t){try{return cO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function V_(e,t={}){let n=G_(["ls-files","-z","--",...B_],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),o=t.baseRef??null;return{isRepo:!0,baseRef:o,files:r.map(i=>{let a=uO(e,i);return{path:i,content:lO(a)?dO(a,"utf8"):null,base:o===null?null:G_(["show",`${o}:${i}`],e)}})}}function Pd(e,t={}){return W_(V_(e,t))}var Md=w(()=>{"use strict";Ho();Dd();s(W_,"computeWorkflowYaml");s(G_,"git");s(V_,"gatherWorkflowYamlFacts");s(Pd,"checkWorkflowYaml")});import{readFileSync as pO}from"node:fs";import{join as fO,posix as mO}from"node:path";function q_(e){let t="",n=0,r=e.length;for(;n<r;){let o=e[n],i=e[n+1];if(o==="-"&&i==="-"){for(;n<r&&e[n]!==`
36
- `;)n++;continue}if(o==="/"&&i==="*"){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(o==="$"){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=(o==="E"||o==="e")&&i==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(o==="'"||a){let c=o!=="'";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+=o,n++}return t}function rt(e){let t=[],n="",r=!1,o=!1,i=s(()=>{t.push(o?n:n.toLowerCase()),n="",o=!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,o=!0;continue}if(l==="."&&!r){i();continue}n+=l}i();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 It(e){let t=[],n=0,r="";for(let o of e){if(o==="("&&n++,o===")"&&(n=Math.max(0,n-1)),o===","&&n===0){t.push(r.trim()),r="";continue}r+=o}return r.trim()&&t.push(r.trim()),t}function hO(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,o,i]=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&&!It(a[1]).map(f=>rt(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||!It(c[1]).map(p=>rt(p)?.name??"").filter(Boolean).includes("public"))return null;let d=It(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>rt(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of It(o)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase();if(h==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...ri]};f[2]!=="("&&ri.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function z_(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,o,i]=t;if(n)return null;let a=o.trim();if(gO.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!It(l[1]).map(f=>rt(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=It(p).map(h=>rt(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(f.length===0)return null;c=f}let d=It(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>rt(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of It(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase(),g=f[2]==="(";if(h==="ALL")return{tables:c,roles:d,writePrivs:[...ri]};!g&&ri.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function Ld(e){let t=new Map,n=[...e].sort((o,i)=>Tt(o.version,i.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let o of n){let i=q_(o.content);for(let a of i.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=hO(c);if(!p)continue;let f=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),h)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(f&&(r.anonAddressed=!1),h)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=rt(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:o.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 It(p)){let h=rt(f);h&&h.schema==="public"&&t.delete(h.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=rt(u[1]),f=rt(u[2]);if(p&&f&&p.schema==="public"){let h=t.get(p.name);h&&(t.delete(p.name),t.set(f.name,h))}continue}if(/^REVOKE\b/i.test(c)){let p=z_(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,h=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!h&&!g)continue;for(let y of f){let _=t.get(y);if(_&&(h&&(_.anonAddressed=!0),g))for(let b of p.writePrivs)_.authWritesRevoked.add(b)}continue}}}return t}function $d(e){let t=[];for(let[n,r]of Ld(e)){let o=[];r.anonAddressed||o.push("anon"),ri.every(i=>r.authWritesRevoked.has(i))||o.push("authenticated_writes"),o.length>0&&t.push({table:n,createdIn:r.createdIn,missing:o})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function J_(e){let t=$d(e.files),n=new Map;if(e.baseFiles!==null)for(let r of $d(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let o=e.baseFiles===null?null:n.get(r.table),a=o!=null&&r.missing.every(l=>o.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 Y_(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function jd(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Vs)||t.endsWith(Fd))}function _O(e,t){try{let n=pO(e,"utf8");return n.length>t?null:n}catch{return null}}function bO(e,t,n,r,o){let i=I(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(i===null)return o.push(`could not diff ${t} against ${r} ${Vs}`),null;let a=new Set,c=[];for(let u of i.split(`
37
- `).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=mO.basename(u),f=Lr(p);if(f===null)continue;let h=I(e,["show",`${r}:${u}`]);if(h===null)return o.push(`could not read ${u} at ${r} ${Fd}`),null;l.push({name:p,version:f,content:h})}return l}function Wn(e,t={}){let n=t.maxFileBytes??yO,r=[],o=Hn(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let i=t.includeBaseline!==!1,a=null;if(i)if(t.baseRef)a=t.baseRef;else{let f=Vo(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${Vs}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of o){let h=[];for(let _ of f.files){let b=_O(fO(e,_.path),n);if(b===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}h.push({ref:_,content:b})}let g=h.map(({ref:_,content:b})=>({name:_.name,version:_.version,content:b})),y=a===null?null:bO(e,f.dir,h,a,r);c.push(...J_({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:Ld(g).size})}let d=l.reduce((f,h)=>f+h.migrationCount,0),u=Y_(d,c.length),p={open:0,info:1};return c.sort((f,h)=>p[f.status]-p[h.status]||f.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var ri,gO,yO,Vs,Fd,qs=w(()=>{"use strict";Ee();qo();s(q_,"stripSql");s(rt,"normalizeQualifiedIdent");s(It,"splitTopLevel");ri=["INSERT","UPDATE","DELETE"];s(hO,"parseDefaultAclTables");gO=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(z_,"parseTableRevoke");s(Ld,"foldTableAcl");s($d,"evaluateTableAcl");s(J_,"computeTableAclFindings");s(Y_,"deriveTableAclVerdict");yO=5e6,Vs="\u2014 findings reported ungraded (open)",Fd="\u2014 baseline degraded";s(jd,"isTableAclGraded");s(_O,"safeRead");s(bO,"baseFilesFor");s(Wn,"checkTableAclLint")});import{readFileSync as wO}from"node:fs";import{join as Hd}from"node:path";function Bd(e){return e.verdict!=="no_opinion"&&e.graded}function Kd(e){let t=new Set;for(let n of e.matchAll(vO))t.add(n[1]);return t}function Gd(e){return new Set([...e].map(t=>t.split("-")[0]))}function nb(e){return e.split(`
27
+ `).filter(Boolean):[]}function PN(e){let t=Jo(I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function c_(e,t={}){let n=t.minFiles??dd,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let o=I(e,r);if(o===null)return[];let i=new Map;for(let a of o.split("\0").filter(Boolean)){let c=gt.dirname(a),l=Yo(gt.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=i.get(d);u?u.numbers.push(l.number):i.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...i.values()].filter(a=>n_(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)=>Fr(a).localeCompare(Fr(c)))}async function fd(e,t={}){let n=[];if(Jo(I(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 o=c_(e,t),i=new Map(o.map(_=>[Fr(_),_])),a=[...new Set(o.map(_=>_.dir))],c=new Map,l=s((_,b,v)=>{let k=gt.dirname(_),E=Yo(gt.basename(_));if(!E)return;let S=`${k}#${E.prefix}`;if(!i.has(S))return;let R=c.get(S)??new Map,P=R.get(E.number)??[];P.push({kind:b,where:v,path:_}),R.set(E.number,P),c.set(S,R)},"record"),d=s((_,b,v)=>{if(a.length===0)return;let k=I(e,["ls-tree","-r","--name-only",_,"--",...a]);if(k===null){n.push(`could not read ${v}`);return}for(let E of Un(k))l(E,b,v)},"scanTree");for(let _ of a){let b=gt.join(e,_);if(ad(b))try{for(let v of Zy(b))l(`${_}/${v}`,"self","this worktree")}catch{n.push(`could not read ${_}`)}}let u=PN(e),p=t.baseRef??(u?`origin/${u}`:null);p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let f=Jo(I(e,["rev-parse","--abbrev-ref","HEAD"])),h=new Map;if(t.includeBranches!==!1)for(let _ of Un(I(e,["for-each-ref","--format=%(refname:short)%00%(objectname)","refs/heads"]))){let[b="",v=""]=_.split("\0");!b||b===f||(d(b,"branch",`Branch ${b}`),h.set(b,v))}let g;if(t.includeRemoteBranches??t.includeBranches!==!1){let _=Un(I(e,["remote"])).map(S=>S.trim()),b=a_(I(e,["for-each-ref","--format=%(refname)%00%(objectname)%00%(committerdate:raw)%00%(symref)","refs/remotes"]),_),v=new Set;u&&v.add(`refs/remotes/origin/${u}`),p&&v.add(p.startsWith("refs/")?p:`refs/remotes/${p}`);let k=Jo(I(e,["rev-parse","--symbolic-full-name","--verify","--quiet","@{upstream}"]));k?.startsWith("refs/remotes/")&&v.add(k);let E=s_(b,{excludeRefs:v,ownBranch:f&&f!=="HEAD"?f:null,localTips:h,nowMs:t.nowMs??Date.now(),maxAgeDays:t.remoteBranchMaxAgeDays??e_,limit:t.remoteBranchLimit??t_});for(let S of E.selected)d(S.ref,"remote_branch",`Remote branch ${S.remote}/${S.name}`);g={scanned:E.selected.map(S=>`${S.remote}/${S.name}`),...E.skipped}}if(t.includeWorktrees!==!1){let _=Jo(I(e,["rev-parse","--show-toplevel"]));for(let b of Un(I(e,["worktree","list","--porcelain"]))){if(!b.startsWith("worktree "))continue;let v=b.slice(9).trim();if(!(!v||v===_||!ad(v)))for(let k of a){let E=gt.join(v,k);if(ad(E))try{for(let S of Zy(E))l(`${k}/${S}`,"worktree",`Worktree ${v}`)}catch{n.push(`could not read ${k} in ${v}`)}}}}let y=[];if(p&&a.length>0){let _=I(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);_===null?n.push(cd):y=Un(_);let b=I(e,["ls-files","--others","--exclude-standard","--",...a]);b!==null&&(y=[...y,...Un(b)]);let v=I(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);v!==null&&(y=[...y,...Un(v)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:o,sightingsByNamespace:c,addedPaths:y,skipped:n,...g?{remoteBranches:g}:{}}}async function Bn(e,t={}){let n=await fd(e,t),r=r_(n);return{ok:o_(r),findings:r,facts:n}}async function Kn(e,t,n={}){let r=pd(t);if(!Yo(gt.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let o=await fd(e,{...n,dirs:n.dirs??[gt.dirname(r)]});return i_(o,r)}var cd,DN,dd,Qy,e_,t_,Xo=w(()=>{"use strict";Ee();cd="could not diff against the base ref \u2014 everything reported as info";s(ld,"isNumberCollisionsGraded");DN=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,dd=3,Qy=.8,e_=30,t_=100;s(n_,"isCounterNamespace");s(Fr,"namespaceKey");s(Yo,"parseNumbered");s(r_,"computeNumberCollisions");s(o_,"isCollisionFree");s(ud,"suggestNextNumber");s(pd,"normaliseRepoPath");s(i_,"checkProposedNumber");s(s_,"selectRemoteBranches");s(a_,"parseRemoteRefs");s(Jo,"trimOrNull");s(Un,"lines");s(PN,"resolveDefaultBranch");s(c_,"detectNamespaces");s(fd,"gatherNumberCollisionFacts");s(Bn,"checkNumberCollisions");s(Kn,"checkNumberForPath")});import{execFileSync as MN}from"node:child_process";import{createHash as $N}from"node:crypto";function md(e){return $N("sha256").update(e).digest("hex")}function LN(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 FN(e){let t=LN(e);return t?md(t):null}function HN(e){return typeof e=="string"&&jN.test(e)}function l_(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(HN(t))return t;let n;try{n=MN("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?FN(n):null}var jN,hd=w(()=>{"use strict";s(md,"sha256Hex");s(LN,"normalizeRemoteUrl");s(FN,"projectKeyFromRemote");jN=/^[a-f0-9]{64}$/;s(HN,"isProjectKey");s(l_,"computeProjectKey")});function bd(e){return`spec.${e}`}function jr(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 UN(e,t){let n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let i=0;i<o;i++){let a=(n[i].codePointAt(0)??0)-(r[i].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function d_(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(UN)}function Qo(e){return md(JSON.stringify(d_(e)))}var Zo,gd,yd,_d,wd=w(()=>{"use strict";hd();Zo={det_number_collisions:{version:"1.3.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"]}},gd="number.collision",yd="theme.dead_class",_d="acl.missing_revoke";s(bd,"specDriftRuleId");s(jr,"gradeEngineStatus");s(UN,"codePointCompare");s(d_,"normalizeEvidenceForHash");s(Qo,"hashDetectorEvidence")});import{existsSync as BN,readFileSync as u_}from"node:fs";import{posix as KN}from"node:path";function Bs(e,t){let n=e[t],r=t+1;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===n)return r+1;r++}return e.length}function Ks(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
28
+ `,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 ei(e){return e==='"'||e==="'"||e==="`"}function Gs(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Hs(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,o=t;for(;o<e.length;){let i=e[o];if(ei(i)){o=Bs(e,o);continue}if(Gs(e,o)){o=Ks(e,o);continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r===0))return e.slice(t,o+1);o++}return null}function GN(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Gs(e,t)){t=Ks(e,t);continue}break}return e.slice(t)}function Hr(e){let t=[],n=0,r=0,o=0;for(;o<e.length;){let i=e[o];if(ei(i)){o=Bs(e,o);continue}if(Gs(e,o)){o=Ks(e,o);continue}i==="["||i==="{"||i==="("?n++:i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,o)),r=o+1),o++}return t.push(e.slice(r)),t.map(i=>GN(i).trim()).filter(i=>i.length>0)}function h_(e){let t=Bs(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,o)=>o==="n"?`
29
+ `:o==="r"?"\r":o==="t"?" ":o)}function WN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kd(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${WN(t)}\b`,"m").exec(e);if(!r)return null;let o=r.index+r[0].length,i=!1;for(;o<e.length;){let a=e[o];if(ei(a)){o=Bs(e,o);continue}if(Gs(e,o)){o=Ks(e,o);continue}if(!i){if(a==="="&&e[o+1]!=="="&&!"=!<>".includes(e[o-1]??" "))i=!0;else if(a===";")return null;o++;continue}if(a==="[")return Hs(e,o);if(a===";")return null;o++}return null}function xd(e){let t={};if(!e.startsWith("{"))return t;for(let n of Hr(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let o=r[2]??r[3],i=r[4].trim();ei(i[0]??"")&&(t[o]=h_(i))}return t}function VN(e,t){if(!e.startsWith("{"))return null;for(let n of Hr(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 g_(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function y_(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function __(e,t){let n=kd(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=y_(),o=[],i=0;for(let a of Hr(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=xd(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");o.push({key:l,fields:g_(c,t.fields),orderPath:d,ordinal:r(d)})}return o.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:o,error:null,dropped:i}}function b_(e,t){let n=kd(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=y_(),o=[],i=0,a=s((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of Hr(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){i++;continue}let y=xd(f);for(let[_,b]of Object.entries(u.fields??{}))h[_]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let _=VN(f,u.children);g=_&&_.startsWith("[")?Hs(_,0):null}}else{if(!f.startsWith("[")){i++;continue}let y=Hr(f.slice(1,-1));for(let[_,b]of Object.entries(u.fields??{})){let v=y[Number(b)];h[_]=v!==void 0&&ei(v[0]??"")?h_(v):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?Hs(_,0):null}}if(p){let y=h[t.key_field];if(!y){i++;continue}let _=(t.partition_by??[]).map(b=>h[b]??"");o.push({key:y,fields:g_(h,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),o.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:o,error:null,dropped:i}}function p_(e,t){return t.extractor==="object-array"?__(e,t):b_(e,t)}function w_(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(o=>n.has(o.replace("{key}",r).replace(/\/{2,}/g,"/")))}function v_(e,t,n){return`spec.drift:${e}#${t}:${n}`}function qN(e){return e.orderPath.join(" / ")||"(flat)"}function k_(e,t,n,r){let o=[],i=s((d,u,p,f,h,g)=>{o.push({id:v_(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:h,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){i("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${qN(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=d.fields[p]??"",h=u.fields[p]??"";f!==h&&i("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${h||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),f=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),h=new Set(f),g=p.filter(y=>h.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";i("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
30
+ 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)||i("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(w_(d,e.grounding,r))continue;let u=a.has(d);i("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 o}function zN(e,t,n){let r=[];for(let o of e.assertions??[]){let i=n.get(o.path);if(!i)continue;let a=i.indexOf(o.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(i.slice(a+o.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[o.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${o.path}`,contract:e.id,dimension:"assertion",status:"warn",key:o.path,title:`${o.path} states ${l} where the ${o.counts} side has ${d}`,detail:`Counted after "${o.prefix}". ${o.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function f_(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 x_(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 o=s(u=>{let p=[],f=[];for(let h of r){let g=u.get(h.spec.path),y=u.get(h.impl.path);if(g==null||y==null){let k=g==null?h.spec.path:h.impl.path;p.push(f_(h.id,`Declared file could not be read: ${k}`)),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=p_(g,h.spec),b=p_(y,h.impl);if(_.error||b.error){p.push(f_(h.id,_.error??b.error??"unknown")),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let v=_.dropped>0||b.dropped>0;f.push({id:h.id,measured:!0,specRecords:_.records.length,implRecords:b.records.length,partial:v}),v&&p.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.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(...k_(h,_.records,b.records,e.files)),p.push(...zN(h,{spec:_.records.length,impl:b.records.length},u))}return{findings:p,contracts:f}},"runOnce"),i=o(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of o(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(v_(u.id,p.dimension,p.key),p);let l=i.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}
31
+ Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>m_[u.status]-m_[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:i.contracts}}function vd(e){let t=e?.trim();return t||null}function Ws(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"),o=n(t);if(!o||!Array.isArray(o.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let i=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of o.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return i(`${u}: not an object`);if(!d)return i(`${u}: \`id\` is missing`);if(!r(l.reason))return i(`${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 i(`${u}: \`${p}\` is missing`);let h=r(f.extractor);if(!h)return i(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return i(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return i(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(f.levels))return i(`${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 i(`${u}: exception for "${r(f?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:o,error:null}}function JN(e){let t=vd(I(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(I(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function YN(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 S_(e,t={}){let n=s((g,y)=>KN.join(g,y),"join"),r=t.manifestPath??Us,o=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:o};if(vd(I(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!BN(a))return{...i,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}=Ws(u_(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...i,isRepo:!0,manifestError:l};let d=new Map;for(let g of YN(c))try{d.set(g,u_(n(e,g),"utf8"))}catch{d.set(g,null),o.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=I(e,["ls-files","-z"]);if(p===null)o.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let f=null,h=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:JN(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)o.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=vd(I(e,["merge-base",y,"HEAD"])),!f)o.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())h.set(_,I(e,["show",`${f}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:f,files:u,skipped:o}}async function Gn(e,t={}){let n=await S_(e,t);return{...x_(n,t),facts:n}}function Sd(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Us,m_,ti=w(()=>{"use strict";Ee();Us=".maind/spec-contracts.json";s(Bs,"endOfString");s(Ks,"skipComment");s(ei,"isQuote");s(Gs,"isCommentStart");s(Hs,"sliceBalanced");s(GN,"stripLeadingTrivia");s(Hr,"splitTopLevel");s(h_,"readStringLiteral");s(WN,"escapeRe");s(kd,"findSymbolArray");s(xd,"parseObjectFields");s(VN,"objectFieldRaw");s(g_,"pickFields");s(y_,"makeOrdinals");s(__,"extractObjectArray");s(b_,"extractNestedList");s(p_,"extractRecords");s(w_,"isGrounded");s(v_,"findingId");s(qN,"partitionOf");s(k_,"compareContract");s(zN,"checkAssertions");s(f_,"unreadable");m_={open:0,warn:1,info:2,passed:3};s(x_,"computeSpecDrift");s(vd,"trimOrNull");s(Ws,"parseManifest");s(JN,"resolveDefaultBranch");s(YN,"declaredPaths");s(S_,"gatherSpecDriftFacts");s(Gn,"checkSpecDrift");s(Sd,"isSpecDriftGraded")});import{execFileSync as XN}from"node:child_process";import{existsSync as ZN,readFileSync as QN}from"node:fs";import{join as eO}from"node:path";function ni(e){let t=[],n=e.split(`
32
+ `);for(let r=0;r<n.length;r+=1){let o=n[r]??"";if(!/^##(?!#)\s/.test(o))continue;let i=/(\d+\.\d+\.\d+)/.exec(o);i&&t.push({version:i[1],line:r+1,raw:o.trim(),shape:/^##\s+Unreleased\b/i.test(o)?"unreleased-labelled":tO.test(o)?"never-published":"released"})}return t}function R_(e){let t=new Map;for(let n of ni(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(o=>o.line),shapes:r.map(o=>o.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function C_(e,t){let n=R_(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of ni(t))r.set(a.version,(r.get(a.version)??0)+1);let o=[],i=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?o:i).push({...a,countBefore:c})}return{introduced:o,preExisting:i,baseResolved:!0}}function T_(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 o=C_(r.head,e.baseRef===null?null:r.base);for(let i of o.introduced)t.push({path:r.path,version:i.version,level:"open",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} has ${i.count} headings (was ${i.countBefore})`});for(let i of o.preExisting)t.push({path:r.path,version:i.version,level:"info",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} already had ${i.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function E_(e,t){try{return XN("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function nO(e,t={}){let n=E_(["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(),o=t.baseRef??null,i=r.map(a=>{let c=eO(e,a);return{path:a,head:ZN(c)?QN(c,"utf8"):null,base:o===null?null:E_(["show",`${o}:${a}`],e)}});return{isRepo:!0,baseRef:o,files:i}}function Ed(e,t={}){return T_(nO(e,t))}var tO,Vs=w(()=>{"use strict";tO=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;s(ni,"parseVersionHeadings");s(R_,"findDuplicateHeadings");s(C_,"classifyIntroduced");s(T_,"computeChangelogDuplicates");s(E_,"git");s(nO,"gatherChangelogFacts");s(Ed,"checkChangelogDuplicates")});import{execFileSync as rO}from"node:child_process";import{existsSync as oO,readFileSync as A_}from"node:fs";import{dirname as I_,join as N_}from"node:path";function D_(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]??[]),o=new Set(n.documentedBase??n.documented),i=[...n.documented].sort(jo);for(let a of i){if(r.has(a)||jo(a,n.version)>=0)continue;let c=!o.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(jo))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 O_(e){let t=ni(e),n=[...new Set(t.filter(i=>i.shape!=="never-published").map(i=>i.version))],r=new Set(n),o=[...new Set(t.filter(i=>i.shape==="never-published"&&!r.has(i.version)).map(i=>i.version))];return{documented:n,neverPublished:o}}function Rd(e,t){try{return rO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function P_(e,t=null){let n=Rd(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let o of[...new Set(n.split("\0").filter(Boolean))].sort()){let i;try{i=JSON.parse(A_(N_(e,o),"utf8"))}catch{continue}if(i.private===!0||typeof i.name!="string"||typeof i.version!="string")continue;let a=I_(o)==="."?"":I_(o),c=N_(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=oO(c)?O_(A_(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Rd(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:O_(p).documented;r.push({dir:a,name:i.name,version:i.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function iO(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 M_(e,t={}){if(Rd(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=P_(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??iO,o={};for(let i of n)try{o[i.name]=await r(i.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${i.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:o,registryReachable:!0,registryError:null}}async function Cd(e,t={}){return D_(await M_(e,t))}var Td=w(()=>{"use strict";Ho();Vs();s(D_,"computeReleaseClaims");s(O_,"claimsOf");s(Rd,"git");s(P_,"discoverPackages");s(iO,"packument");s(M_,"gatherReleaseClaimsFacts");s(Cd,"checkReleaseClaims")});import{execFileSync as sO}from"node:child_process";import{existsSync as aO,readFileSync as cO}from"node:fs";import{join as lO}from"node:path";function Id(e){let t=[],n=!1;for(let r of e.split(`
33
+ `)){let o=r.trim();if(n){o===j_&&(n=!1);continue}if(o===F_){n=!0;continue}t.push(r)}return t.join(`
34
+ `)}function $_(e){return e.split(`
35
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function H_(e,t){let n=new Map;for(let i of $_(t??""))n.set(i,(n.get(i)??0)+1);let r=[];for(let i of $_(e)){let a=n.get(i)??0;a>0?n.set(i,a-1):r.push(i)}let o=0;for(let i of n.values())o+=i;return{added:r,removed:o,net:Math.max(0,r.length-o)}}function U_(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=H_(Id(n.head),n.base===null?null:Id(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 Ad(e,t){try{return sO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function B_(e,t={}){let n=Ad(["ls-files","-z","--",...L_],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Ad(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,i=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=lO(e,a);return{path:a,head:aO(c)?cO(c,"utf8"):null,base:r===null?null:Ad(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:i}}function Nd(e,t={}){return U_(B_(e,t))}var L_,F_,j_,Od=w(()=>{"use strict";L_=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],F_="<!-- maind:conventions v1 begin -->",j_="<!-- maind:conventions v1 end -->";s(Id,"stripManagedConventionsBlock");s($_,"contentLines");s(H_,"proseDelta");s(U_,"computeAgentDocProse");s(Ad,"git");s(B_,"gatherAgentDocProseFacts");s(Nd,"checkAgentDocProse")});var K_,G_,Dd=w(()=>{"use strict";K_=[".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"],G_=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 dO}from"node:child_process";import{existsSync as uO,readFileSync as pO}from"node:fs";import{join as fO}from"node:path";function V_(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?[]:Ts(n.base).map(o=>o.value));for(let o of Ts(n.content)){let i=o.value.length>60?`${o.value.slice(0,57)}\u2026`:o.value,a=e.baseRef!==null&&!r.has(o.value);t.push({path:n.path,level:a?"open":"info",line:o.line,value:o.value,title:`${n.path}:${o.line}: unquoted plain scalar containing ": " \u2014 ${i}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function W_(e,t){try{return dO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function q_(e,t={}){let n=W_(["ls-files","-z","--",...K_],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),o=t.baseRef??null;return{isRepo:!0,baseRef:o,files:r.map(i=>{let a=fO(e,i);return{path:i,content:uO(a)?pO(a,"utf8"):null,base:o===null?null:W_(["show",`${o}:${i}`],e)}})}}function Pd(e,t={}){return V_(q_(e,t))}var Md=w(()=>{"use strict";Ho();Dd();s(V_,"computeWorkflowYaml");s(W_,"git");s(q_,"gatherWorkflowYamlFacts");s(Pd,"checkWorkflowYaml")});import{readFileSync as mO}from"node:fs";import{join as hO,posix as gO}from"node:path";function z_(e){let t="",n=0,r=e.length;for(;n<r;){let o=e[n],i=e[n+1];if(o==="-"&&i==="-"){for(;n<r&&e[n]!==`
36
+ `;)n++;continue}if(o==="/"&&i==="*"){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(o==="$"){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=(o==="E"||o==="e")&&i==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(o==="'"||a){let c=o!=="'";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+=o,n++}return t}function rt(e){let t=[],n="",r=!1,o=!1,i=s(()=>{t.push(o?n:n.toLowerCase()),n="",o=!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,o=!0;continue}if(l==="."&&!r){i();continue}n+=l}i();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 Nt(e){let t=[],n=0,r="";for(let o of e){if(o==="("&&n++,o===")"&&(n=Math.max(0,n-1)),o===","&&n===0){t.push(r.trim()),r="";continue}r+=o}return r.trim()&&t.push(r.trim()),t}function yO(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,o,i]=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&&!Nt(a[1]).map(f=>rt(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||!Nt(c[1]).map(p=>rt(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Nt(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>rt(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Nt(o)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase();if(h==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...ri]};f[2]!=="("&&ri.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function J_(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,o,i]=t;if(n)return null;let a=o.trim();if(_O.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!Nt(l[1]).map(f=>rt(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=Nt(p).map(h=>rt(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(f.length===0)return null;c=f}let d=Nt(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>rt(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Nt(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase(),g=f[2]==="(";if(h==="ALL")return{tables:c,roles:d,writePrivs:[...ri]};!g&&ri.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function Ld(e){let t=new Map,n=[...e].sort((o,i)=>At(o.version,i.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let o of n){let i=z_(o.content);for(let a of i.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=yO(c);if(!p)continue;let f=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),h)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(f&&(r.anonAddressed=!1),h)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=rt(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:o.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 Nt(p)){let h=rt(f);h&&h.schema==="public"&&t.delete(h.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=rt(u[1]),f=rt(u[2]);if(p&&f&&p.schema==="public"){let h=t.get(p.name);h&&(t.delete(p.name),t.set(f.name,h))}continue}if(/^REVOKE\b/i.test(c)){let p=J_(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,h=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!h&&!g)continue;for(let y of f){let _=t.get(y);if(_&&(h&&(_.anonAddressed=!0),g))for(let b of p.writePrivs)_.authWritesRevoked.add(b)}continue}}}return t}function $d(e){let t=[];for(let[n,r]of Ld(e)){let o=[];r.anonAddressed||o.push("anon"),ri.every(i=>r.authWritesRevoked.has(i))||o.push("authenticated_writes"),o.length>0&&t.push({table:n,createdIn:r.createdIn,missing:o})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Y_(e){let t=$d(e.files),n=new Map;if(e.baseFiles!==null)for(let r of $d(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let o=e.baseFiles===null?null:n.get(r.table),a=o!=null&&r.missing.every(l=>o.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 X_(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function jd(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(qs)||t.endsWith(Fd))}function wO(e,t){try{let n=mO(e,"utf8");return n.length>t?null:n}catch{return null}}function vO(e,t,n,r,o){let i=I(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(i===null)return o.push(`could not diff ${t} against ${r} ${qs}`),null;let a=new Set,c=[];for(let u of i.split(`
37
+ `).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=gO.basename(u),f=Lr(p);if(f===null)continue;let h=I(e,["show",`${r}:${u}`]);if(h===null)return o.push(`could not read ${u} at ${r} ${Fd}`),null;l.push({name:p,version:f,content:h})}return l}function Wn(e,t={}){let n=t.maxFileBytes??bO,r=[],o=Hn(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let i=t.includeBaseline!==!1,a=null;if(i)if(t.baseRef)a=t.baseRef;else{let f=Vo(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${qs}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of o){let h=[];for(let _ of f.files){let b=wO(hO(e,_.path),n);if(b===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}h.push({ref:_,content:b})}let g=h.map(({ref:_,content:b})=>({name:_.name,version:_.version,content:b})),y=a===null?null:vO(e,f.dir,h,a,r);c.push(...Y_({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:Ld(g).size})}let d=l.reduce((f,h)=>f+h.migrationCount,0),u=X_(d,c.length),p={open:0,info:1};return c.sort((f,h)=>p[f.status]-p[h.status]||f.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var ri,_O,bO,qs,Fd,zs=w(()=>{"use strict";Ee();qo();s(z_,"stripSql");s(rt,"normalizeQualifiedIdent");s(Nt,"splitTopLevel");ri=["INSERT","UPDATE","DELETE"];s(yO,"parseDefaultAclTables");_O=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(J_,"parseTableRevoke");s(Ld,"foldTableAcl");s($d,"evaluateTableAcl");s(Y_,"computeTableAclFindings");s(X_,"deriveTableAclVerdict");bO=5e6,qs="\u2014 findings reported ungraded (open)",Fd="\u2014 baseline degraded";s(jd,"isTableAclGraded");s(wO,"safeRead");s(vO,"baseFilesFor");s(Wn,"checkTableAclLint")});import{readFileSync as kO}from"node:fs";import{join as Hd}from"node:path";function Bd(e){return e.verdict!=="no_opinion"&&e.graded}function Kd(e){let t=new Set;for(let n of e.matchAll(xO))t.add(n[1]);return t}function Gd(e){return new Set([...e].map(t=>t.split("-")[0]))}function rb(e){return e.split(`
38
38
  `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
39
- `)}function Wd(e){let t=Gd(e.tokens),n=[];for(let{path:r,content:o}of e.sources){let i=nb(o),a=new Set;for(let c of i.matchAll(kO)){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 X_(e){return`${e.file} ${e.klass}`}function xO(e,t){let n=t===null?null:new Set(t.map(X_));return e.map(r=>({...r,status:n!==null&&n.has(X_(r))?"info":"open"}))}function rb(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Vd(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Q_(e,t){let n=I(e,["ls-files","--",...t]);return n===null?[]:n.split(`
40
- `).filter(Boolean)}function Vn(e,t={}){let n=t.maxFileBytes??SO,r=new Set;for(let u of Q_(e,["*.css"])){let p=Ud(Hd(e,u),n);if(p!==null)for(let f of Kd(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 o=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>Z_.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):Z_,i=[];for(let u of Q_(e,o)){if(!Vd(u))continue;let p=Ud(Hd(e,u),n);p!==null&&i.push({path:u,content:p})}let a=Wd({tokens:r,sources:i}),c=t.includeBaseline===!1?null:EO(e,o,n,t.baseRef),l=xO(a,c?.findings??null),d=rb(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:Gd(r).size,findings:l,scannedFiles:i.length,graded:c!==null,baseRef:c?.mergeBase??null}}function EO(e,t,n,r){let o=r??CO(e);if(o===null)return null;let i=I(e,["merge-base",o,"HEAD"])?.trim();if(!i)return null;let a=I(e,["diff","--name-only","--no-renames",i]);if(a===null)return null;let c=new Set(a.split(`
41
- `).filter(Boolean)),l=s(p=>c.has(p)?I(e,["show",`${i}:${p}`]):Ud(Hd(e,p),n),"atBase"),d=new Set;for(let p of eb(e,i,["*.css"])){let f=l(p);if(f!==null)for(let h of Kd(f))d.add(h)}if(d.size===0)return{findings:[],mergeBase:i};let u=[];for(let p of eb(e,i,t)){if(!Vd(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:Wd({tokens:d,sources:u}),mergeBase:i}}function eb(e,t,n){let r=I(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
42
- `).filter(o=>o.length>0&&n.some(i=>RO(o,i)))}function RO(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),o=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(o!==""&&!e.startsWith(o+"/"))return!1;let i=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?i.endsWith(r.slice(1)):i===r}function CO(e){let t=I(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(o=>I(e,["rev-parse","--verify","--quiet",`origin/${o}`])!==null);return r?`origin/${r}`:null}function Ud(e,t){try{let n=wO(e,"utf8");return n.length>t?null:n}catch{return null}}var tb,vO,kO,Z_,SO,zs=w(()=>{"use strict";Ee();s(Bd,"isThemeClassDriftGraded");tb=["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"],vO=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,kO=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+tb.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Kd,"extractTokens");s(Gd,"deriveNamespaces");s(nb,"stripCommentLines");s(Wd,"evaluateThemeClasses");s(X_,"findingKey");s(xO,"gradeAgainstBaseline");s(rb,"deriveThemeClassVerdict");Z_=["*.ts","*.tsx","*.js","*.jsx"],SO=15e5;s(Vd,"isScannableSource");s(Q_,"listTracked");s(Vn,"checkThemeClassDrift");s(EO,"baselineFindings");s(eb,"listTrackedAt");s(RO,"matchesSourcePattern");s(CO,"resolveBaseRef");s(Ud,"safeRead")});function qd(e){return Zo[e].version}function Ot(e,t,n,r){return{detector_id:e,detector_version:qd(e),state:t,finding_count:n,...r?{reason:r}:{}}}function Y(e,t,n){return{summary:Ot(e,t,0,n),findings:[]}}function lb(e){return e==="open"||e==="warn"||e==="info"}function TO(e){let t="det_number_collisions";if(!e.ok)return Y(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return Y(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return Y(t,"not_applicable","no numbered namespaces");if(!ld(n))return Y(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let o=[];for(let i of r){if(!lb(i.status))continue;let{level:a,baseline:c}=jr(i.status);o.push({detector_id:t,rule_id:gd,level:a,baseline:c,evidence:[...i.ownPath?[i.ownPath]:[],...i.sightings.map(l=>l.path)],title:i.title})}return{summary:Ot(t,"ran",o.length),findings:o}}function AO(e){let t="det_spec_drift";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return Y(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return Y(t,"not_applicable",n.reason??"no opinion");if(!Sd(n))return Y(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let o of n.findings){if(!lb(o.status))continue;let{level:i,baseline:a}=jr(o.status,{excepted:o.exceptionReason!==void 0});r.push({detector_id:t,rule_id:bd(o.dimension),level:i,baseline:a,evidence:[o.id],title:o.title})}return{summary:Ot(t,"ran",r.length),findings:r}}function IO(e){let t="det_theme_class_drift";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable","no theme tokens");if(!Bd(n))return Y(t,"ungraded","no merge-base to grade against");let r=[];for(let o of n.findings){let{level:i,baseline:a}=jr(o.status);r.push({detector_id:t,rule_id:yd,level:i,baseline:a,evidence:[o.file,o.klass,o.token],title:`${o.klass} in ${o.file} \u2014 token ${o.token} does not exist`})}return{summary:Ot(t,"ran",r.length),findings:r}}function NO(e){let t="det_table_acl_lint";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable","no supabase migrations");if(!jd(n))return Y(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let o of n.findings){let{level:i,baseline:a}=jr(o.status);r.push({detector_id:t,rule_id:_d,level:i,baseline:a,evidence:[o.project,o.table,...o.missing],title:o.title})}return{summary:Ot(t,"ran",r.length),findings:r}}function OO(e){let t="det_changelog_duplicates";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return Y(t,"ungraded","no base ref to grade against");let r=n.findings.map(o=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:o.level,baseline:o.level==="open"?"introduced":"pre_existing",evidence:[o.path,o.version],title:o.title}));return{summary:Ot(t,"ran",r.length),findings:r}}function DO(e){let t="det_workflow_yaml";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return Y(t,"ungraded","no base ref to grade against");let r=n.findings.map(o=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:o.level,baseline:o.level==="open"?"introduced":"pre_existing",evidence:[o.path,String(o.line)],title:o.title}));return{summary:Ot(t,"ran",r.length),findings:r}}function PO(e){let t="det_release_claims";if(!e.ok)return Y(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?Y(t,"ungraded",n.reason??"registry unreachable"):Y(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(o=>({detector_id:t,rule_id:o.rule,level:o.level,baseline:"introduced",evidence:[o.package,o.version],title:o.title}));return{summary:Ot(t,"ran",r.length),findings:r}}function MO(e){let t="det_agent_doc_prose";if(!e.ok)return Y(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?Y(t,"ungraded",n.reason??"no base ref to grade against"):Y(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(o=>({detector_id:t,rule_id:"agentdoc.added_prose",level:o.level,baseline:"introduced",evidence:[o.path,...o.sample,String(o.netLines)],title:o.title}));return{summary:Ot(t,"ran",r.length),findings:r}}function zd(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Js[e.level]-Js[t.level]||ib[e.baseline]-ib[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function sb(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function $O(e){let t=new Map,n=new Map;for(let o of e)if(o.baseline==="introduced"){let i=Qo(o.evidence),a=`${o.detector_id}|${o.rule_id}|${o.level}|${i}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:o.detector_id,detector_version:qd(o.detector_id),rule_id:o.rule_id,level:o.level,baseline:"introduced",evidence_hash:i,count:1})}else{let i=`${o.detector_id}|${o.rule_id}`,a=n.get(i);a?(a.evidence.push(...o.evidence),a.count+=1,Js[o.level]<Js[a.level]&&(a.level=o.level)):n.set(i,{detector_id:o.detector_id,rule_id:o.rule_id,level:o.level,evidence:[...o.evidence],count:1})}let r=[...t.values()];for(let o of n.values())r.push({detector_id:o.detector_id,detector_version:qd(o.detector_id),rule_id:o.rule_id,level:o.level,baseline:"pre_existing",evidence_hash:Qo(o.evidence),count:o.count});return r.sort(zd)}function LO(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 Ve(e){let t={det_number_collisions:TO(e.number),det_spec_drift:AO(e.spec),det_theme_class_drift:IO(e.theme),det_table_acl_lint:NO(e.acl),det_changelog_duplicates:OO(e.changelog),det_workflow_yaml:DO(e.workflow),det_release_claims:PO(e.release),det_agent_doc_prose:MO(e.agentDoc)},n=ob.map(l=>t[l].summary),r=ob.flatMap(l=>t[l].findings),o=$O(r),i=[...o].sort((l,d)=>sb(l)-sb(d)||zd(l,d)).slice(0,ab).sort(zd),a=o.length-i.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Qo(l.evidence),title:l.title}));return{findings:i,coverage:LO(n,a),engines:n,local:c,truncated:a}}function Nt(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 Yd(e){return e instanceof Error?e.message:String(e)}async function Xt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Yd(t)}}}async function Xd(e,t={}){let n={...cb,...t.engines};try{if(!db(e))return Ve(Nt("not a git work tree"));let r=await ub(e,n,t.baseRef),o=await Jd(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Ve({...r,number:o})}catch(r){return Ve(Nt(`detector adapter failed: ${Yd(r)}`))}}async function Zd(e,t={}){let n={...cb,...t.engines};try{if(!db(e)){let a=Ve(Nt("not a git work tree"));return{commit:a,local:a}}let r=await ub(e,n,t.baseRef),o=await Jd(e,n,t.baseRef,"commit"),i=await Jd(e,n,t.baseRef,"local");return{commit:Ve({...r,number:o}),local:Ve({...r,number:i})}}catch(r){let o=Ve(Nt(`detector adapter failed: ${Yd(r)}`));return{commit:o,local:o}}}function db(e){return I(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function ub(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Xt(()=>t.spec(e,r)),theme:await Xt(()=>t.theme(e,r)),acl:await Xt(()=>t.acl(e,r)),changelog:await Xt(()=>t.changelog(e,r)),workflow:await Xt(()=>t.workflow(e,r)),release:await Xt(()=>t.release(e,r)),agentDoc:await Xt(()=>t.agentDoc(e,r))}}function Jd(e,t,n,r,o){let i=r==="local";return Xt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:i,includeRemoteBranches:i,includeWorktrees:o??i}))}var ab,cb,ob,Js,ib,Qd=w(()=>{"use strict";Ee();wd();Xo();ti();Td();Od();Md();Ws();qs();zs();ab=64,cb={number:s((e,t)=>Bn(e,t),"number"),spec:s((e,t)=>Gn(e,t),"spec"),theme:s((e,t)=>Vn(e,t),"theme"),acl:s((e,t)=>Wn(e,t),"acl"),changelog:s((e,t)=>Ed(e,t),"changelog"),workflow:s((e,t)=>Pd(e,t),"workflow"),release:s((e,t)=>Cd(e,t),"release"),agentDoc:s((e,t)=>Nd(e,t),"agentDoc")},ob=["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(qd,"versionOf");s(Ot,"summary");s(Y,"noFindings");s(lb,"isFindingStatus");s(TO,"adaptNumber");s(AO,"adaptSpec");s(IO,"adaptTheme");s(NO,"adaptAcl");s(OO,"adaptChangelog");s(DO,"adaptWorkflow");s(PO,"adaptRelease");s(MO,"adaptAgentDoc");Js={open:0,warn:1,info:2},ib={introduced:0,pre_existing:1};s(zd,"compareWire");s(sb,"capPriority");s($O,"buildWire");s(LO,"deriveCoverage");s(Ve,"adaptDetectorReports");s(Nt,"unavailableDetectorReports");s(Yd,"errorText");s(Xt,"attempt");s(Xd,"runRepoHealthDetectors");s(Zd,"runRepoHealthDetectorScopes");s(db,"insideWorkTree");s(ub,"runSharedEngines");s(Jd,"runNumberEngine")});var pb,eu=w(()=>{"use strict";Dd();pb=[{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:K_},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function fb(e){let t=new Set;for(let[n,r]of e.paths)for(let o of pb){if(t.has(o.flag)||!o.path.test(n)||o.onlyWhenAdded&&r!=="added")continue;if(!o.content){t.add(o.flag);continue}let i=FO(n,e);i!==null&&o.content.test(i)&&t.add(o.flag)}return[...t].sort()}function FO(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
43
- `):t.readUntracked(e)}var mb=w(()=>{"use strict";eu();s(fb,"scanRiskFlags");s(FO,"contentForPath")});var Zt,tu,Qt,Ur,oi,Br,nu,Ys,Xs,Zs,ru,hb,Kr=w(()=>{"use strict";Zt="3",tu=`
39
+ `)}function Wd(e){let t=Gd(e.tokens),n=[];for(let{path:r,content:o}of e.sources){let i=rb(o),a=new Set;for(let c of i.matchAll(SO)){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 Z_(e){return`${e.file} ${e.klass}`}function EO(e,t){let n=t===null?null:new Set(t.map(Z_));return e.map(r=>({...r,status:n!==null&&n.has(Z_(r))?"info":"open"}))}function ob(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Vd(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function eb(e,t){let n=I(e,["ls-files","--",...t]);return n===null?[]:n.split(`
40
+ `).filter(Boolean)}function Vn(e,t={}){let n=t.maxFileBytes??RO,r=new Set;for(let u of eb(e,["*.css"])){let p=Ud(Hd(e,u),n);if(p!==null)for(let f of Kd(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 o=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>Q_.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):Q_,i=[];for(let u of eb(e,o)){if(!Vd(u))continue;let p=Ud(Hd(e,u),n);p!==null&&i.push({path:u,content:p})}let a=Wd({tokens:r,sources:i}),c=t.includeBaseline===!1?null:CO(e,o,n,t.baseRef),l=EO(a,c?.findings??null),d=ob(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:Gd(r).size,findings:l,scannedFiles:i.length,graded:c!==null,baseRef:c?.mergeBase??null}}function CO(e,t,n,r){let o=r??AO(e);if(o===null)return null;let i=I(e,["merge-base",o,"HEAD"])?.trim();if(!i)return null;let a=I(e,["diff","--name-only","--no-renames",i]);if(a===null)return null;let c=new Set(a.split(`
41
+ `).filter(Boolean)),l=s(p=>c.has(p)?I(e,["show",`${i}:${p}`]):Ud(Hd(e,p),n),"atBase"),d=new Set;for(let p of tb(e,i,["*.css"])){let f=l(p);if(f!==null)for(let h of Kd(f))d.add(h)}if(d.size===0)return{findings:[],mergeBase:i};let u=[];for(let p of tb(e,i,t)){if(!Vd(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:Wd({tokens:d,sources:u}),mergeBase:i}}function tb(e,t,n){let r=I(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
42
+ `).filter(o=>o.length>0&&n.some(i=>TO(o,i)))}function TO(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),o=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(o!==""&&!e.startsWith(o+"/"))return!1;let i=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?i.endsWith(r.slice(1)):i===r}function AO(e){let t=I(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(o=>I(e,["rev-parse","--verify","--quiet",`origin/${o}`])!==null);return r?`origin/${r}`:null}function Ud(e,t){try{let n=kO(e,"utf8");return n.length>t?null:n}catch{return null}}var nb,xO,SO,Q_,RO,Js=w(()=>{"use strict";Ee();s(Bd,"isThemeClassDriftGraded");nb=["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"],xO=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,SO=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+nb.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Kd,"extractTokens");s(Gd,"deriveNamespaces");s(rb,"stripCommentLines");s(Wd,"evaluateThemeClasses");s(Z_,"findingKey");s(EO,"gradeAgainstBaseline");s(ob,"deriveThemeClassVerdict");Q_=["*.ts","*.tsx","*.js","*.jsx"],RO=15e5;s(Vd,"isScannableSource");s(eb,"listTracked");s(Vn,"checkThemeClassDrift");s(CO,"baselineFindings");s(tb,"listTrackedAt");s(TO,"matchesSourcePattern");s(AO,"resolveBaseRef");s(Ud,"safeRead")});function qd(e){return Zo[e].version}function Dt(e,t,n,r){return{detector_id:e,detector_version:qd(e),state:t,finding_count:n,...r?{reason:r}:{}}}function Y(e,t,n){return{summary:Dt(e,t,0,n),findings:[]}}function db(e){return e==="open"||e==="warn"||e==="info"}function IO(e){let t="det_number_collisions";if(!e.ok)return Y(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return Y(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return Y(t,"not_applicable","no numbered namespaces");if(!ld(n))return Y(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let o=[];for(let i of r){if(!db(i.status))continue;let{level:a,baseline:c}=jr(i.status);o.push({detector_id:t,rule_id:gd,level:a,baseline:c,evidence:[...i.ownPath?[i.ownPath]:[],...i.sightings.map(l=>l.path)],title:i.title})}return{summary:Dt(t,"ran",o.length),findings:o}}function NO(e){let t="det_spec_drift";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return Y(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return Y(t,"not_applicable",n.reason??"no opinion");if(!Sd(n))return Y(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let o of n.findings){if(!db(o.status))continue;let{level:i,baseline:a}=jr(o.status,{excepted:o.exceptionReason!==void 0});r.push({detector_id:t,rule_id:bd(o.dimension),level:i,baseline:a,evidence:[o.id],title:o.title})}return{summary:Dt(t,"ran",r.length),findings:r}}function OO(e){let t="det_theme_class_drift";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable","no theme tokens");if(!Bd(n))return Y(t,"ungraded","no merge-base to grade against");let r=[];for(let o of n.findings){let{level:i,baseline:a}=jr(o.status);r.push({detector_id:t,rule_id:yd,level:i,baseline:a,evidence:[o.file,o.klass,o.token],title:`${o.klass} in ${o.file} \u2014 token ${o.token} does not exist`})}return{summary:Dt(t,"ran",r.length),findings:r}}function DO(e){let t="det_table_acl_lint";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable","no supabase migrations");if(!jd(n))return Y(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let o of n.findings){let{level:i,baseline:a}=jr(o.status);r.push({detector_id:t,rule_id:_d,level:i,baseline:a,evidence:[o.project,o.table,...o.missing],title:o.title})}return{summary:Dt(t,"ran",r.length),findings:r}}function PO(e){let t="det_changelog_duplicates";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return Y(t,"ungraded","no base ref to grade against");let r=n.findings.map(o=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:o.level,baseline:o.level==="open"?"introduced":"pre_existing",evidence:[o.path,o.version],title:o.title}));return{summary:Dt(t,"ran",r.length),findings:r}}function MO(e){let t="det_workflow_yaml";if(!e.ok)return Y(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return Y(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return Y(t,"ungraded","no base ref to grade against");let r=n.findings.map(o=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:o.level,baseline:o.level==="open"?"introduced":"pre_existing",evidence:[o.path,String(o.line)],title:o.title}));return{summary:Dt(t,"ran",r.length),findings:r}}function $O(e){let t="det_release_claims";if(!e.ok)return Y(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?Y(t,"ungraded",n.reason??"registry unreachable"):Y(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(o=>({detector_id:t,rule_id:o.rule,level:o.level,baseline:"introduced",evidence:[o.package,o.version],title:o.title}));return{summary:Dt(t,"ran",r.length),findings:r}}function LO(e){let t="det_agent_doc_prose";if(!e.ok)return Y(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?Y(t,"ungraded",n.reason??"no base ref to grade against"):Y(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(o=>({detector_id:t,rule_id:"agentdoc.added_prose",level:o.level,baseline:"introduced",evidence:[o.path,...o.sample,String(o.netLines)],title:o.title}));return{summary:Dt(t,"ran",r.length),findings:r}}function zd(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Ys[e.level]-Ys[t.level]||sb[e.baseline]-sb[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function ab(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function FO(e){let t=new Map,n=new Map;for(let o of e)if(o.baseline==="introduced"){let i=Qo(o.evidence),a=`${o.detector_id}|${o.rule_id}|${o.level}|${i}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:o.detector_id,detector_version:qd(o.detector_id),rule_id:o.rule_id,level:o.level,baseline:"introduced",evidence_hash:i,count:1})}else{let i=`${o.detector_id}|${o.rule_id}`,a=n.get(i);a?(a.evidence.push(...o.evidence),a.count+=1,Ys[o.level]<Ys[a.level]&&(a.level=o.level)):n.set(i,{detector_id:o.detector_id,rule_id:o.rule_id,level:o.level,evidence:[...o.evidence],count:1})}let r=[...t.values()];for(let o of n.values())r.push({detector_id:o.detector_id,detector_version:qd(o.detector_id),rule_id:o.rule_id,level:o.level,baseline:"pre_existing",evidence_hash:Qo(o.evidence),count:o.count});return r.sort(zd)}function jO(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 Ve(e){let t={det_number_collisions:IO(e.number),det_spec_drift:NO(e.spec),det_theme_class_drift:OO(e.theme),det_table_acl_lint:DO(e.acl),det_changelog_duplicates:PO(e.changelog),det_workflow_yaml:MO(e.workflow),det_release_claims:$O(e.release),det_agent_doc_prose:LO(e.agentDoc)},n=ib.map(l=>t[l].summary),r=ib.flatMap(l=>t[l].findings),o=FO(r),i=[...o].sort((l,d)=>ab(l)-ab(d)||zd(l,d)).slice(0,cb).sort(zd),a=o.length-i.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Qo(l.evidence),title:l.title}));return{findings:i,coverage:jO(n,a),engines:n,local:c,truncated:a}}function Ot(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 Yd(e){return e instanceof Error?e.message:String(e)}async function Xt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Yd(t)}}}async function Xd(e,t={}){let n={...lb,...t.engines};try{if(!ub(e))return Ve(Ot("not a git work tree"));let r=await pb(e,n,t.baseRef),o=await Jd(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Ve({...r,number:o})}catch(r){return Ve(Ot(`detector adapter failed: ${Yd(r)}`))}}async function Zd(e,t={}){let n={...lb,...t.engines};try{if(!ub(e)){let a=Ve(Ot("not a git work tree"));return{commit:a,local:a}}let r=await pb(e,n,t.baseRef),o=await Jd(e,n,t.baseRef,"commit"),i=await Jd(e,n,t.baseRef,"local");return{commit:Ve({...r,number:o}),local:Ve({...r,number:i})}}catch(r){let o=Ve(Ot(`detector adapter failed: ${Yd(r)}`));return{commit:o,local:o}}}function ub(e){return I(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function pb(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Xt(()=>t.spec(e,r)),theme:await Xt(()=>t.theme(e,r)),acl:await Xt(()=>t.acl(e,r)),changelog:await Xt(()=>t.changelog(e,r)),workflow:await Xt(()=>t.workflow(e,r)),release:await Xt(()=>t.release(e,r)),agentDoc:await Xt(()=>t.agentDoc(e,r))}}function Jd(e,t,n,r,o){let i=r==="local";return Xt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:i,includeRemoteBranches:i,includeWorktrees:o??i}))}var cb,lb,ib,Ys,sb,Qd=w(()=>{"use strict";Ee();wd();Xo();ti();Td();Od();Md();Vs();zs();Js();cb=64,lb={number:s((e,t)=>Bn(e,t),"number"),spec:s((e,t)=>Gn(e,t),"spec"),theme:s((e,t)=>Vn(e,t),"theme"),acl:s((e,t)=>Wn(e,t),"acl"),changelog:s((e,t)=>Ed(e,t),"changelog"),workflow:s((e,t)=>Pd(e,t),"workflow"),release:s((e,t)=>Cd(e,t),"release"),agentDoc:s((e,t)=>Nd(e,t),"agentDoc")},ib=["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(qd,"versionOf");s(Dt,"summary");s(Y,"noFindings");s(db,"isFindingStatus");s(IO,"adaptNumber");s(NO,"adaptSpec");s(OO,"adaptTheme");s(DO,"adaptAcl");s(PO,"adaptChangelog");s(MO,"adaptWorkflow");s($O,"adaptRelease");s(LO,"adaptAgentDoc");Ys={open:0,warn:1,info:2},sb={introduced:0,pre_existing:1};s(zd,"compareWire");s(ab,"capPriority");s(FO,"buildWire");s(jO,"deriveCoverage");s(Ve,"adaptDetectorReports");s(Ot,"unavailableDetectorReports");s(Yd,"errorText");s(Xt,"attempt");s(Xd,"runRepoHealthDetectors");s(Zd,"runRepoHealthDetectorScopes");s(ub,"insideWorkTree");s(pb,"runSharedEngines");s(Jd,"runNumberEngine")});var fb,eu=w(()=>{"use strict";Dd();fb=[{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:G_},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function mb(e){let t=new Set;for(let[n,r]of e.paths)for(let o of fb){if(t.has(o.flag)||!o.path.test(n)||o.onlyWhenAdded&&r!=="added")continue;if(!o.content){t.add(o.flag);continue}let i=HO(n,e);i!==null&&o.content.test(i)&&t.add(o.flag)}return[...t].sort()}function HO(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
43
+ `):t.readUntracked(e)}var hb=w(()=>{"use strict";eu();s(mb,"scanRiskFlags");s(HO,"contentForPath")});var Zt,tu,Qt,Ur,oi,Br,nu,Xs,Zs,Qs,ru,gb,Kr=w(()=>{"use strict";Zt="3",tu=`
44
44
  CREATE TABLE IF NOT EXISTS meta (
45
45
  key TEXT PRIMARY KEY,
46
46
  value TEXT NOT NULL
@@ -128,40 +128,40 @@ CREATE TABLE IF NOT EXISTS embeddings (
128
128
  vec BLOB NOT NULL,
129
129
  content_hash TEXT NOT NULL
130
130
  );
131
- `,Qt="schema_version",Ur="last_index_commit",oi="last_indexed_at",Br="edges_dirty",nu="resolve_config_fp",Ys="embed_recipe_version",Xs="embed_model",Zs="embed_dim",ru="last_synced_at",hb="last_synced_commit"});function ou(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 gb(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of ou(e.name))t.add(o);for(let o of ou(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function yb(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 o of ou(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var iu=w(()=>{"use strict";s(ou,"splitIdentifier");s(gb,"buildSearchText");s(yb,"toFtsMatchQuery")});import{readFileSync as _b}from"node:fs";import{posix as bb}from"node:path";function wb(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 qn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function vb(e){return e==="added"?0:e==="modified"?1:2}function jO(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 o=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(o+=l-c+1)}let i=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return o>0||i?{...e,change:"modified",changedLineCount:o,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var ii,su=w(()=>{"use strict";Ho();ly();Ll();uy();hy();jl();ky();Ee();Oy();Yl();sd();Xo();Qd();ti();mb();Kr();iu();ii=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(Qt),o=await this.store.countFiles()>0;(t.full||o&&r!==Zt)&&await this.wipe();let i=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(i.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=Vl(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=Cy(this.repoRoot);let c=new Set(a.map(b=>b.path)),l=new Map(i.map(b=>[b.path,b])),d=i.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(Br,"1"))},"markEdgesDirty");for(let b of i)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let h=0;for(let b of a){h++;let v=Ay(this.repoRoot,b.path);if(!v){u.filesSkipped++;continue}let k=l.get(b.path);if(k&&k.mtimeMs===v.mtimeMs&&k.size===v.size){u.filesSkipped++;continue}let E=this.readRepoFile(b.path);if(E===null){u.filesSkipped++;continue}let S=Ms(E);if(k&&k.contentHash===S){await this.store.upsertFile({...k,mtimeMs:v.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let R=await this.parser.parse(b.path,E,b.language),P=new Map;for(let x of R.nodes)P.set(x.nodeKey,gb(x));let K={path:b.path,language:b.language,contentHash:S,mtimeMs:v.mtimeMs,size:v.size,indexedAt:n};await f(),await this.store.replaceFileNodes(K,R.nodes,P,{contains:R.edges,refs:R.refs,imports:R.imports,exports:R.exports}),u.filesParsed++,t.onProgress?.({path:b.path,done:h,total:a.length})}let g=py(this.repoRoot),y=await this.store.getMeta(nu)!==g.fingerprint;if(p||y||await this.store.getMeta(Br)==="1"){let b=wy(await this.store.getNameIndex()),v=new Mr(g.config,b.files),k=vy(await this.store.getAllFacts(),b,v);await this.store.replaceCrossFileEdges(k),await this.store.setMeta(nu,g.fingerprint),await this.store.setMeta(Br,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...$l]),v=await this.store.getEmbeddingContentHashes(),k=[];for(let S of b){let R=cy(S),P=Ms(`${this.embedder.recipeVersion}\0${R}`);v.get(S.nodeKey)!==P&&k.push({nodeKey:S.nodeKey,text:R,hash:P})}let E=64;for(let S=0;S<k.length;S+=E){let R=k.slice(S,S+E),P=await this.embedder.embedDocuments(R.map(x=>x.text));await this.store.upsertEmbeddings(R.map((x,T)=>({nodeKey:x.nodeKey,dim:this.embedder.dim,vec:P[T],contentHash:x.hash})));let K=Math.min(S+E,k.length);t.onProgress?.({path:"embedding symbols",done:K,total:k.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Ys,this.embedder.recipeVersion),await this.store.setMeta(Xs,this.embedder.model),await this.store.setMeta(Zs,String(this.embedder.dim))}await this.store.setMeta(Qt,Zt),await this.store.setMeta(oi,String(n));let _=Wo(this.repoRoot);return _&&await this.store.setMeta(Ur,_),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 i of n)r[i.language]=i.count;let o=await this.store.getMeta(oi);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:o?Number(o):null,lastIndexCommit:await this.store.getMeta(Ur),schemaVersion:await this.store.getMeta(Qt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=qn(n.limit,20,100),o=await this.store.searchFts(t,n.kind??null,r),i=[];for(let a of o){let c=await this.store.getNode(a.nodeKey);c&&i.push({...wb(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=qn(n.limit,20,100),o=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:dy(o,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({...wb(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=qn(n.maxDepth,3,5),i=qn(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<o&&u.length>0;p++){let f=[];for(let h of u){let g=await this.store.neighbors(h,r,a,i);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>=i)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=_b(bb.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(),o={};for(let a of n)o[a.kind]=a.count;let i={};for(let a of r)i[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:o,languageDistribution:i,topModules:await this.store.topModulesByFanIn(qn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Vl(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=qn(t.limit,64,200),o=[],i=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&i++,o.push(...c)}return o.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:i,symbols:o.slice(0,r),truncated:o.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Ps(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(Wo(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Fy(this.repoRoot,n,t)}async checkDivergence(t={}){return zo(this.repoRoot,t)}async checkNumberCollisions(t={}){return Bn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Kn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Gn(this.repoRoot,t)}async reviewDetectors(t={}){return Xd(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Zd(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Ps(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Ny(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",a=fb({paths:n,hunks:o,readUntracked:s(f=>this.readRepoFileHead(f,Iy),"readUntracked")}),c=Ry(n.keys()),l=qn(t.limit,64,t.attest?zt:200),d=[],u=0,p=0;for(let f of c){let h=await this.store.getNodesByFile(f.path);if(h.length===0)continue;u++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),_=g!==null&&y!==null&&Ms(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let b=n.get(f.path)??"modified",v=o.get(f.path);for(let k of h)d.push(jO(k,b,v,_))}return d.sort((f,h)=>vb(f.change)-vb(h.change)||(f.filePath<h.filePath?-1:f.filePath>h.filePath?1:0)||f.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:Wo(this.repoRoot),dirty:ql(this.repoRoot),baseSha:t.since?$s(this.repoRoot,t.since):null,mergeBaseSha:t.since?Wl(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 _b(bb.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(wb,"toHit");s(qn,"clampLimit");s(vb,"changeRank");s(jO,"classifyReviewSymbol")});var kb=w(()=>{"use strict";Ee()});var HO,m6,xb=w(()=>{"use strict";Ee();HO=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],m6=new RegExp(HO.join("|"),"g")});import{existsSync as au,readdirSync as UO,readFileSync as BO}from"node:fs";import{spawnSync as KO}from"node:child_process";import{dirname as GO,join as Qs,posix as cu}from"node:path";function Eb(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 ${lu} 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 ${lu} 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 o=new Set(r.versions),i=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!o.has(p)).sort(Tt);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=>!i.has(p)).sort(Tt),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let h=l.get(f)??[];h.push(p),l.set(f,h)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(Tt),h=e.remote.versions.filter(g=>!i.has(g)).sort(Tt);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:h})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function Rb(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Tb(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(`
132
- `).filter(Boolean).slice(-1)[0]}}function Sb(e,t,n){let r=e(t,WO,n);return r.ok===!1?Tb(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
133
- `).map(o=>o.trim()).filter(Boolean)}}function Ab(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 VO(e){let t=I(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=GO(t);return n===e?null:n}function qO(e,t,n){let r=cu.dirname(t),i=[{path:Qs(e,r,"config.toml"),source:"worktree"}],a=VO(e);a&&i.push({path:Qs(a,r,"config.toml"),source:"main_worktree"});for(let c of i)if(au(c.path))try{let l=Ab(BO(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 zO(e,t){let n=new Map,r=I(e,["worktree","list","--porcelain"]);if(r===null)return n;let o=I(e,["rev-parse","--show-toplevel"])?.trim();for(let i of r.split(`
134
- `)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===o||!au(a))continue;let c=Qs(a,t);if(au(c))try{for(let l of UO(c)){let d=Lr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function du(e,t={}){let n=t.runPsql??Cb,r=t.timeoutMs??15e3,o=[],i=Hn(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}};let a=[],c=[],l=[];for(let p of i){let f=qO(e,p.dir,o),h=f.source==="missing"?null:Sb(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?Sb(n,t.remoteDbUrl,r):null,y=Eb({dir:p.dir,projectRoot:Qs(e,cu.dirname(cu.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:h,siblingVersions:zO(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=Rb(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:o}}}var lu,Cb,WO,Ib=w(()=>{"use strict";Ee();qo();lu=54322;s(Eb,"evaluateLedgerProject");s(Rb,"deriveLedgerVerdict");Cb=s((e,t,n)=>{let r=KO("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"),WO="select version from supabase_migrations.schema_migrations order by version";s(Tb,"classifyLedgerError");s(Sb,"readLedger");s(Ab,"parseDbPort");s(VO,"mainWorktreeRoot");s(qO,"resolveConfig");s(zO,"gatherSiblingVersions");s(du,"checkMigrationLedgerDrift")});function qe(e){return typeof e=="string"?e:String(e??"")}function si(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function uu(e){return{nodeKey:qe(e.node_key),kind:qe(e.kind),name:qe(e.name),qualifiedName:qe(e.qualified_name),filePath:qe(e.file_path),startLine:si(e.start_line),endLine:si(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function Db(e){return{path:qe(e.path),language:qe(e.language),contentHash:qe(e.content_hash),mtimeMs:si(e.mtime_ms),size:si(e.size),indexedAt:si(e.indexed_at)}}function pu(e){let t=new Map,n=s(o=>{let i=t.get(o);return i===void 0&&(i=e.prepare(o),t.set(o,i)),i},"stmt"),r=s(o=>{let i=n(en.meta).get(o);return i===void 0?null:qe(i.value)},"metaValue");return{meta(){let o=r(Qt),i=r(oi);return{schemaVersion:o,schemaCurrent:o===Zt,edgesDirty:r(Br)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n(en.file).get(o);return i===void 0?null:Db(i)},files(o){let i=new Map;for(let a of new Set(o)){let c=n(en.file).get(a);c!==void 0&&i.set(a,Db(c))}return i},symbolsInFile(o,i=JO){return n(en.symbolsInFile).all(o,i).map(uu)},symbolsNamed(o,i=YO){let a=new Map;for(let c of new Set(o)){let l=n(en.symbolsNamed).all(c,i);l.length>0&&a.set(c,l.map(uu))}return a},callersOfFile(o,i=XO){return n(en.callersOfFile).all(o,o,i).map(c=>({calleeKey:qe(c.callee_key),kind:qe(c.edge_kind),caller:uu(c)}))},importersOf(o,i=ZO){let a=n(en.importersOf).all(mt(o),i),c=[];for(let l of a){let d=qe(l.src_key),u=d.endsWith(Ob)?d.slice(0,-Ob.length):d;u!==o&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function ai(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var Nb,en,JO,YO,XO,ZO,Ob,fu=w(()=>{"use strict";jn();Kr();Nb="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",en={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 ${Nb} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${Nb} 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 ?"},JO=400,YO=8,XO=600,ZO=200,Ob="#<module>";s(qe,"str");s(si,"num");s(uu,"toSymbol");s(Db,"toFileRow");s(pu,"createIndexReader");s(ai,"isFileCurrent")});var mu,hu=w(()=>{"use strict";mu="0.2.0"});function gu(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:zt,attest:!0}}function yu(e,t){let n=0,r=[];for(let i of e.symbols){let a=i.qualifiedName?i.qualifiedName:void 0;if(i.name.length===0||i.name.length>ea||a!==void 0&&a.length>ta){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=Mb?{kind:i.kind}:{},...i.language&&i.language.length<=$b?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),Lb)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.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:mu},dropped:n}}function _u(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 bu(e,t,n){let r=t,o=[];r===0?o.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):o.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"&&o.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&o.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let i=e.changedFiles-e.indexedFiles;return i>0&&o.push(`${i} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&o.push(`Symbol list truncated at ${zt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&o.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),o.join(" ")}function wu(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===Pb&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===Pb?{kind:"invalid_params",code:n,detail:r,issues:QO(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function QO(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 vu(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 ea,ta,Mb,$b,Lb,Pb,eD,Fb=w(()=>{"use strict";Ho();hu();ea=200,ta=512,Mb=64,$b=32,Lb=1e4;s(gu,"attestReviewOptions");s(yu,"buildAttestPayload");s(_u,"attestPersistDecision");s(bu,"attestCoverageNote");Pb=-32602;s(wu,"classifyMcpErrorText");s(QO,"parseIssues");s(vu,"isLegacyAttestRejection");eD=`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 tn=w(()=>{"use strict";th();su();Yl();eu();Ee();Ws();Md();Td();Od();sd();kb();xb();ed();Xo();zs();ti();qo();qs();Ib();wd();Qd();Xo();ti();zs();qs();Is();Ll();Kr();fu();Os();hu();Fb()});import{execFileSync as tD}from"node:child_process";import{createHash as nD}from"node:crypto";import{mkdirSync as rD,readFileSync as oD,renameSync as iD,writeFileSync as sD}from"node:fs";import{dirname as jb,join as Hb}from"node:path";function ot(e=process.cwd()){try{let t=tD("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 nD("sha256").update(e).digest("hex").slice(0,16)}function na(e){return Hb(e,aD)}function Ub(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Bb(e,t,n,r=new Date().toISOString()){try{if(!Ub(n))return;let o={version:ku,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=na(e);rD(jb(i),{recursive:!0}),Go(jb(i));let a=`${i}.${process.pid}.tmp`;sD(a,JSON.stringify(o,null,2),"utf8"),iD(a,i)}catch{}}function ra(e,t){try{let n=oD(na(e),"utf8"),r=JSON.parse(n);return r.version!==ku||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Ub(r.result)?null:{version:ku,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Kb(e,t,n=new Date){let r=cD(t.cached_at,n),o=t.result.instructions??"",i={...t.result,instructions:`${r}
135
-
136
- ${o}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function cD(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${lD(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function lD(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,o=Math.floor(r/6e4);if(o<1)return"just now";if(o<60)return`${o} minute${o===1?"":"s"} ago`;let i=Math.floor(o/60);if(i<24)return`${i} hour${i===1?"":"s"} ago`;let a=Math.floor(i/24);return`${a} day${a===1?"":"s"} ago`}var ku,aD,Dt=w(()=>{"use strict";tn();ku=1,aD=Hb(".maind","conventions-cache.json");s(ot,"resolveRepoRoot");s(Gr,"keyFingerprint");s(na,"cachePath");s(Ub,"hasInstructions");s(Bb,"writeConventionsCache");s(ra,"readConventionsCache");s(Kb,"buildCachedInitializeResponse");s(cD,"fallbackMarker");s(lD,"relativeAge")});import{existsSync as aa,mkdirSync as wD,readFileSync as Vb,writeFileSync as Cu,chmodSync as qb}from"node:fs";import{homedir as vD,hostname as kD,platform as Ru,release as xD}from"node:os";import{randomUUID as SD}from"node:crypto";import{join as zn}from"node:path";function it(){let e=vD(),t=process.env;if(Ru()==="darwin")return zn(e,"Library","Application Support","maind");if(Ru()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:zn(e,"AppData","Roaming");return zn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:zn(e,".config");return zn(n,"maind")}function zb(e){aa(e)||wD(e,{recursive:!0,mode:448})}function ae(){let e=it();zb(e);let t=zn(e,ED);if(aa(t)){let r=Vb(t,"utf8").trim();if(TD(r))return r}let n=SD();Cu(t,n+`
137
- `,{encoding:"utf8",mode:384});try{qb(t,384)}catch{}return n}function TD(e){return CD.test(e)}function Tu(){return zn(it(),RD)}function Jn(e){let t=it();zb(t);let n=Tu();Cu(n,e+`
138
- `,{encoding:"utf8",mode:384});try{qb(n,384)}catch{}}function z(){let e=Tu();if(!aa(e))return null;let t=Vb(e,"utf8").trim();return t.length>0?t:null}function li(){let e=Tu();aa(e)&&Cu(e,"",{encoding:"utf8",mode:384})}function Jb(){try{return`mcp-bridge-${kD()}`}catch{return"mcp-bridge"}}function ca(e){return{os:`${Ru()} ${xD()}`,ide:"mcp-bridge",ext_version:e,device_id:ae()}}var ED,RD,CD,re=w(()=>{"use strict";s(it,"configDir");s(zb,"ensureDir");ED="device-id",RD="api-key";s(ae,"ensureDeviceId");CD=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(TD,"isUuid");s(Tu,"apiKeyPath");s(Jn,"writeApiKey");s(z,"readApiKey");s(li,"clearApiKey");s(Jb,"bridgeLabel");s(ca,"clientMeta")});function di(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:AD}function Vr(e){return`${di()}/${e.replace(/^\/+/,"")}`}var AD,qr=w(()=>{"use strict";AD="https://fn.maind.dev/functions/v1";s(di,"functionsOrigin");s(Vr,"functionsUrl")});import{spawn as ID}from"node:child_process";import{platform as ND}from"node:os";async function zr(e,t=process.stderr){let n=di(),r=`${n}/device-authorization-start`,o=`${n}/device-authorization-poll`,i=ca(e),a=`mcp-bridge-${i.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:i})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await MD(l.verification_uri_complete).catch(()=>{}),PD(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await DD(u);let p=await OD(o,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
131
+ `,Qt="schema_version",Ur="last_index_commit",oi="last_indexed_at",Br="edges_dirty",nu="resolve_config_fp",Xs="embed_recipe_version",Zs="embed_model",Qs="embed_dim",ru="last_synced_at",gb="last_synced_commit"});function ou(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 yb(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of ou(e.name))t.add(o);for(let o of ou(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function _b(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 o of ou(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var iu=w(()=>{"use strict";s(ou,"splitIdentifier");s(yb,"buildSearchText");s(_b,"toFtsMatchQuery")});import{readFileSync as bb}from"node:fs";import{posix as wb}from"node:path";function vb(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 qn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function kb(e){return e==="added"?0:e==="modified"?1:2}function UO(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 o=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(o+=l-c+1)}let i=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return o>0||i?{...e,change:"modified",changedLineCount:o,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var ii,su=w(()=>{"use strict";Ho();ly();Fl();uy();hy();Hl();ky();Ee();Dy();Yl();sd();Xo();Qd();ti();hb();Kr();iu();ii=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(Qt),o=await this.store.countFiles()>0;(t.full||o&&r!==Zt)&&await this.wipe();let i=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(i.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=Vl(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=Cy(this.repoRoot);let c=new Set(a.map(b=>b.path)),l=new Map(i.map(b=>[b.path,b])),d=i.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(Br,"1"))},"markEdgesDirty");for(let b of i)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let h=0;for(let b of a){h++;let v=Ay(this.repoRoot,b.path);if(!v){u.filesSkipped++;continue}let k=l.get(b.path);if(k&&k.mtimeMs===v.mtimeMs&&k.size===v.size){u.filesSkipped++;continue}let E=this.readRepoFile(b.path);if(E===null){u.filesSkipped++;continue}let S=$s(E);if(k&&k.contentHash===S){await this.store.upsertFile({...k,mtimeMs:v.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let R=await this.parser.parse(b.path,E,b.language),P=new Map;for(let x of R.nodes)P.set(x.nodeKey,yb(x));let K={path:b.path,language:b.language,contentHash:S,mtimeMs:v.mtimeMs,size:v.size,indexedAt:n};await f(),await this.store.replaceFileNodes(K,R.nodes,P,{contains:R.edges,refs:R.refs,imports:R.imports,exports:R.exports}),u.filesParsed++,t.onProgress?.({path:b.path,done:h,total:a.length})}let g=py(this.repoRoot),y=await this.store.getMeta(nu)!==g.fingerprint;if(p||y||await this.store.getMeta(Br)==="1"){let b=wy(await this.store.getNameIndex()),v=new Mr(g.config,b.files),k=vy(await this.store.getAllFacts(),b,v);await this.store.replaceCrossFileEdges(k),await this.store.setMeta(nu,g.fingerprint),await this.store.setMeta(Br,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...Ll]),v=await this.store.getEmbeddingContentHashes(),k=[];for(let S of b){let R=cy(S),P=$s(`${this.embedder.recipeVersion}\0${R}`);v.get(S.nodeKey)!==P&&k.push({nodeKey:S.nodeKey,text:R,hash:P})}let E=64;for(let S=0;S<k.length;S+=E){let R=k.slice(S,S+E),P=await this.embedder.embedDocuments(R.map(x=>x.text));await this.store.upsertEmbeddings(R.map((x,T)=>({nodeKey:x.nodeKey,dim:this.embedder.dim,vec:P[T],contentHash:x.hash})));let K=Math.min(S+E,k.length);t.onProgress?.({path:"embedding symbols",done:K,total:k.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Xs,this.embedder.recipeVersion),await this.store.setMeta(Zs,this.embedder.model),await this.store.setMeta(Qs,String(this.embedder.dim))}await this.store.setMeta(Qt,Zt),await this.store.setMeta(oi,String(n));let _=Wo(this.repoRoot);return _&&await this.store.setMeta(Ur,_),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 i of n)r[i.language]=i.count;let o=await this.store.getMeta(oi);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:o?Number(o):null,lastIndexCommit:await this.store.getMeta(Ur),schemaVersion:await this.store.getMeta(Qt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=qn(n.limit,20,100),o=await this.store.searchFts(t,n.kind??null,r),i=[];for(let a of o){let c=await this.store.getNode(a.nodeKey);c&&i.push({...vb(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=qn(n.limit,20,100),o=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:dy(o,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({...vb(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=qn(n.maxDepth,3,5),i=qn(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<o&&u.length>0;p++){let f=[];for(let h of u){let g=await this.store.neighbors(h,r,a,i);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>=i)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=bb(wb.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(),o={};for(let a of n)o[a.kind]=a.count;let i={};for(let a of r)i[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:o,languageDistribution:i,topModules:await this.store.topModulesByFanIn(qn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Vl(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=qn(t.limit,64,200),o=[],i=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&i++,o.push(...c)}return o.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:i,symbols:o.slice(0,r),truncated:o.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Ms(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(Wo(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return jy(this.repoRoot,n,t)}async checkDivergence(t={}){return zo(this.repoRoot,t)}async checkNumberCollisions(t={}){return Bn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Kn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Gn(this.repoRoot,t)}async reviewDetectors(t={}){return Xd(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Zd(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Ms(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Oy(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",a=mb({paths:n,hunks:o,readUntracked:s(f=>this.readRepoFileHead(f,Ny),"readUntracked")}),c=Ry(n.keys()),l=qn(t.limit,64,t.attest?Jt:200),d=[],u=0,p=0;for(let f of c){let h=await this.store.getNodesByFile(f.path);if(h.length===0)continue;u++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),_=g!==null&&y!==null&&$s(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let b=n.get(f.path)??"modified",v=o.get(f.path);for(let k of h)d.push(UO(k,b,v,_))}return d.sort((f,h)=>kb(f.change)-kb(h.change)||(f.filePath<h.filePath?-1:f.filePath>h.filePath?1:0)||f.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:Wo(this.repoRoot),dirty:ql(this.repoRoot),baseSha:t.since?Ls(this.repoRoot,t.since):null,mergeBaseSha:t.since?Wl(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 bb(wb.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(vb,"toHit");s(qn,"clampLimit");s(kb,"changeRank");s(UO,"classifyReviewSymbol")});var xb=w(()=>{"use strict";Ee()});var BO,g6,Sb=w(()=>{"use strict";Ee();BO=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],g6=new RegExp(BO.join("|"),"g")});import{existsSync as au,readdirSync as KO,readFileSync as GO}from"node:fs";import{spawnSync as WO}from"node:child_process";import{dirname as VO,join as ea,posix as cu}from"node:path";function Rb(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 ${lu} 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 ${lu} 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 o=new Set(r.versions),i=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!o.has(p)).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(p=>!i.has(p)).sort(At),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let h=l.get(f)??[];h.push(p),l.set(f,h)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(At),h=e.remote.versions.filter(g=>!i.has(g)).sort(At);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:h})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function Cb(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Ab(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(`
132
+ `).filter(Boolean).slice(-1)[0]}}function Eb(e,t,n){let r=e(t,qO,n);return r.ok===!1?Ab(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
133
+ `).map(o=>o.trim()).filter(Boolean)}}function Ib(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 zO(e){let t=I(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=VO(t);return n===e?null:n}function JO(e,t,n){let r=cu.dirname(t),i=[{path:ea(e,r,"config.toml"),source:"worktree"}],a=zO(e);a&&i.push({path:ea(a,r,"config.toml"),source:"main_worktree"});for(let c of i)if(au(c.path))try{let l=Ib(GO(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 YO(e,t){let n=new Map,r=I(e,["worktree","list","--porcelain"]);if(r===null)return n;let o=I(e,["rev-parse","--show-toplevel"])?.trim();for(let i of r.split(`
134
+ `)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===o||!au(a))continue;let c=ea(a,t);if(au(c))try{for(let l of KO(c)){let d=Lr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function du(e,t={}){let n=t.runPsql??Tb,r=t.timeoutMs??15e3,o=[],i=Hn(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}};let a=[],c=[],l=[];for(let p of i){let f=JO(e,p.dir,o),h=f.source==="missing"?null:Eb(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?Eb(n,t.remoteDbUrl,r):null,y=Rb({dir:p.dir,projectRoot:ea(e,cu.dirname(cu.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:h,siblingVersions:YO(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=Cb(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:o}}}var lu,Tb,qO,Nb=w(()=>{"use strict";Ee();qo();lu=54322;s(Rb,"evaluateLedgerProject");s(Cb,"deriveLedgerVerdict");Tb=s((e,t,n)=>{let r=WO("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"),qO="select version from supabase_migrations.schema_migrations order by version";s(Ab,"classifyLedgerError");s(Eb,"readLedger");s(Ib,"parseDbPort");s(zO,"mainWorktreeRoot");s(JO,"resolveConfig");s(YO,"gatherSiblingVersions");s(du,"checkMigrationLedgerDrift")});function qe(e){return typeof e=="string"?e:String(e??"")}function si(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function uu(e){return{nodeKey:qe(e.node_key),kind:qe(e.kind),name:qe(e.name),qualifiedName:qe(e.qualified_name),filePath:qe(e.file_path),startLine:si(e.start_line),endLine:si(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function Pb(e){return{path:qe(e.path),language:qe(e.language),contentHash:qe(e.content_hash),mtimeMs:si(e.mtime_ms),size:si(e.size),indexedAt:si(e.indexed_at)}}function pu(e){let t=new Map,n=s(o=>{let i=t.get(o);return i===void 0&&(i=e.prepare(o),t.set(o,i)),i},"stmt"),r=s(o=>{let i=n(en.meta).get(o);return i===void 0?null:qe(i.value)},"metaValue");return{meta(){let o=r(Qt),i=r(oi);return{schemaVersion:o,schemaCurrent:o===Zt,edgesDirty:r(Br)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n(en.file).get(o);return i===void 0?null:Pb(i)},files(o){let i=new Map;for(let a of new Set(o)){let c=n(en.file).get(a);c!==void 0&&i.set(a,Pb(c))}return i},symbolsInFile(o,i=XO){return n(en.symbolsInFile).all(o,i).map(uu)},symbolsNamed(o,i=ZO){let a=new Map;for(let c of new Set(o)){let l=n(en.symbolsNamed).all(c,i);l.length>0&&a.set(c,l.map(uu))}return a},callersOfFile(o,i=QO){return n(en.callersOfFile).all(o,o,i).map(c=>({calleeKey:qe(c.callee_key),kind:qe(c.edge_kind),caller:uu(c)}))},importersOf(o,i=eD){let a=n(en.importersOf).all(mt(o),i),c=[];for(let l of a){let d=qe(l.src_key),u=d.endsWith(Db)?d.slice(0,-Db.length):d;u!==o&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function ai(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var Ob,en,XO,ZO,QO,eD,Db,fu=w(()=>{"use strict";jn();Kr();Ob="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",en={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 ${Ob} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${Ob} 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 ?"},XO=400,ZO=8,QO=600,eD=200,Db="#<module>";s(qe,"str");s(si,"num");s(uu,"toSymbol");s(Pb,"toFileRow");s(pu,"createIndexReader");s(ai,"isFileCurrent")});var mu,hu=w(()=>{"use strict";mu="0.2.0"});function gu(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:Jt,attest:!0}}function yu(e,t){let n=0,r=[];for(let i of e.symbols){let a=i.qualifiedName?i.qualifiedName:void 0;if(i.name.length===0||i.name.length>ta||a!==void 0&&a.length>na){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=$b?{kind:i.kind}:{},...i.language&&i.language.length<=Lb?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),Fb)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.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:mu},dropped:n}}function _u(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 bu(e,t,n){let r=t,o=[];r===0?o.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):o.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"&&o.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&o.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let i=e.changedFiles-e.indexedFiles;return i>0&&o.push(`${i} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&o.push(`Symbol list truncated at ${Jt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&o.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),o.join(" ")}function wu(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===Mb&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===Mb?{kind:"invalid_params",code:n,detail:r,issues:tD(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function tD(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 vu(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 ta,na,$b,Lb,Fb,Mb,nD,jb=w(()=>{"use strict";Ho();hu();ta=200,na=512,$b=64,Lb=32,Fb=1e4;s(gu,"attestReviewOptions");s(yu,"buildAttestPayload");s(_u,"attestPersistDecision");s(bu,"attestCoverageNote");Mb=-32602;s(wu,"classifyMcpErrorText");s(tD,"parseIssues");s(vu,"isLegacyAttestRejection");nD=`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 tn=w(()=>{"use strict";th();su();Yl();eu();Ee();Vs();Md();Td();Od();sd();xb();Sb();ed();Xo();Js();ti();qo();zs();Nb();wd();Qd();Xo();ti();Js();zs();Is();Fl();Kr();fu();Os();hu();jb()});import{execFileSync as rD}from"node:child_process";import{createHash as oD}from"node:crypto";import{mkdirSync as iD,readFileSync as sD,renameSync as aD,writeFileSync as cD}from"node:fs";import{dirname as Hb,join as Ub}from"node:path";function ot(e=process.cwd()){try{let t=rD("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 oD("sha256").update(e).digest("hex").slice(0,16)}function ra(e){return Ub(e,lD)}function Bb(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Kb(e,t,n,r=new Date().toISOString()){try{if(!Bb(n))return;let o={version:ku,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=ra(e);iD(Hb(i),{recursive:!0}),Go(Hb(i));let a=`${i}.${process.pid}.tmp`;cD(a,JSON.stringify(o,null,2),"utf8"),aD(a,i)}catch{}}function oa(e,t){try{let n=sD(ra(e),"utf8"),r=JSON.parse(n);return r.version!==ku||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Bb(r.result)?null:{version:ku,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Gb(e,t,n=new Date){let r=dD(t.cached_at,n),o=t.result.instructions??"",i={...t.result,instructions:`${r}
135
+
136
+ ${o}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function dD(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${uD(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function uD(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,o=Math.floor(r/6e4);if(o<1)return"just now";if(o<60)return`${o} minute${o===1?"":"s"} ago`;let i=Math.floor(o/60);if(i<24)return`${i} hour${i===1?"":"s"} ago`;let a=Math.floor(i/24);return`${a} day${a===1?"":"s"} ago`}var ku,lD,Pt=w(()=>{"use strict";tn();ku=1,lD=Ub(".maind","conventions-cache.json");s(ot,"resolveRepoRoot");s(Gr,"keyFingerprint");s(ra,"cachePath");s(Bb,"hasInstructions");s(Kb,"writeConventionsCache");s(oa,"readConventionsCache");s(Gb,"buildCachedInitializeResponse");s(dD,"fallbackMarker");s(uD,"relativeAge")});import{existsSync as ca,mkdirSync as kD,readFileSync as qb,writeFileSync as Cu,chmodSync as zb}from"node:fs";import{homedir as xD,hostname as SD,platform as Ru,release as ED}from"node:os";import{randomUUID as RD}from"node:crypto";import{join as zn}from"node:path";function it(){let e=xD(),t=process.env;if(Ru()==="darwin")return zn(e,"Library","Application Support","maind");if(Ru()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:zn(e,"AppData","Roaming");return zn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:zn(e,".config");return zn(n,"maind")}function Jb(e){ca(e)||kD(e,{recursive:!0,mode:448})}function ae(){let e=it();Jb(e);let t=zn(e,CD);if(ca(t)){let r=qb(t,"utf8").trim();if(ID(r))return r}let n=RD();Cu(t,n+`
137
+ `,{encoding:"utf8",mode:384});try{zb(t,384)}catch{}return n}function ID(e){return AD.test(e)}function Tu(){return zn(it(),TD)}function Jn(e){let t=it();Jb(t);let n=Tu();Cu(n,e+`
138
+ `,{encoding:"utf8",mode:384});try{zb(n,384)}catch{}}function z(){let e=Tu();if(!ca(e))return null;let t=qb(e,"utf8").trim();return t.length>0?t:null}function li(){let e=Tu();ca(e)&&Cu(e,"",{encoding:"utf8",mode:384})}function Yb(){try{return`mcp-bridge-${SD()}`}catch{return"mcp-bridge"}}function la(e){return{os:`${Ru()} ${ED()}`,ide:"mcp-bridge",ext_version:e,device_id:ae()}}var CD,TD,AD,re=w(()=>{"use strict";s(it,"configDir");s(Jb,"ensureDir");CD="device-id",TD="api-key";s(ae,"ensureDeviceId");AD=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(ID,"isUuid");s(Tu,"apiKeyPath");s(Jn,"writeApiKey");s(z,"readApiKey");s(li,"clearApiKey");s(Yb,"bridgeLabel");s(la,"clientMeta")});function di(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:ND}function Vr(e){return`${di()}/${e.replace(/^\/+/,"")}`}var ND,qr=w(()=>{"use strict";ND="https://fn.maind.dev/functions/v1";s(di,"functionsOrigin");s(Vr,"functionsUrl")});import{spawn as OD}from"node:child_process";import{platform as DD}from"node:os";async function zr(e,t=process.stderr){let n=di(),r=`${n}/device-authorization-start`,o=`${n}/device-authorization-poll`,i=la(e),a=`mcp-bridge-${i.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:i})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await LD(l.verification_uri_complete).catch(()=>{}),$D(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await MD(u);let p=await PD(o,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
139
139
  `),null));if(p){if(p.status==="approved")return Jn(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
140
140
  `),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
141
141
  `),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
142
142
  `),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
143
- `),null}async function OD(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()}function DD(e){return new Promise(t=>setTimeout(t,e))}function PD(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: ${Yb(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Yb(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(`
143
+ `),null}async function PD(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()}function MD(e){return new Promise(t=>setTimeout(t,e))}function $D(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: ${Xb(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Xb(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(`
144
144
  `)+`
145
- `)}function Yb(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}async function MD(e){let t,n;switch(ND()){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,o)=>{try{let i=ID(t,n,{stdio:"ignore",detached:!0});i.on("error",o),i.unref(),r()}catch(i){o(i)}})}var Au=w(()=>{"use strict";re();qr();s(zr,"runDeviceFlow");s(OD,"pollOnce");s(DD,"sleep");s(PD,"printAuthInstructions");s(Yb,"pad");s(MD,"openExternalBrowser")});import{mkdirSync as $D,readFileSync as LD,renameSync as FD,writeFileSync as jD}from"node:fs";import{join as HD}from"node:path";function Xb(e=it()){return HD(e,BD)}function GD(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,KD)}function Yn(e,t,n){try{let r=n.dir??it();$D(r,{recursive:!0,mode:448});let o={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:GD(t),bridge_version:n.version},i=Xb(r),a=`${i}.${process.pid}.tmp`;jD(a,JSON.stringify(o)+`
146
- `,{encoding:"utf8",mode:384}),FD(a,i)}catch{}}function Zb(e=it()){try{let t=JSON.parse(LD(Xb(e),"utf8"));return t.v!==1||typeof t.at!="string"||!UD.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 UD,BD,KD,Iu=w(()=>{"use strict";re();UD=["ok","paired","auth_failed","not_paired"],BD="connection-state.json",KD=200;s(Xb,"connectionStatePath");s(GD,"redactDetail");s(Yn,"writeConnectionState");s(Zb,"readConnectionState")});var H,Fe=w(()=>{"use strict";H="0.100.0"});import{execFileSync as Qb}from"node:child_process";import{createHash as WD}from"node:crypto";function Nu(e){return WD("sha256").update(e).digest("hex")}function Ou(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 nn(e){let t=Ou(e);return t?Nu(t):null}function ne(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&VD.test(e))return e;let t;try{t=Qb("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nn(t):null}function yt(e){let t;try{t=Qb("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nn(t):null}var VD,pe=w(()=>{"use strict";s(Nu,"sha256Hex");s(Ou,"normalizeRemoteUrl");s(nn,"projectKeyFromRemote");VD=/^[a-f0-9]{64}$/;s(ne,"computeProjectKey");s(yt,"projectKeyForRepo")});import qD from"node:path";import{fileURLToPath as zD}from"node:url";function JD(e,t=qD.sep){return e.split(t).includes("_npx")}function we(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",tw,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):JD(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 oe(){try{let e=zD(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function ze(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${ew(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:ew(n)).join(" ")}function rn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(tw)}function la(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function ew(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var tw,_t=w(()=>{"use strict";tw="@maind-dev/mcp-bridge";s(JD,"isEphemeralEntry");s(we,"resolveBridgeLaunch");s(oe,"currentBridgeEntry");s(ze,"launchToShellCommand");s(rn,"isNpxForm");s(la,"isLegacyHookForm");s(ew,"shellQuote")});import{readFileSync as YD}from"node:fs";import*as $ from"node:path";function ow(e){let t=e.launch??we({entryPath:oe(),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 sw(e){return fa(e,"Claude")}function ZD(e){return $.join(sw(e),iw)}function fa(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 QD(e){return $.join(fa(e,"Code"),"User")}function ua(e,t,n=[]){return{kind:"foreign-entries",dir:fa(e,t),ours:["User",...n]}}function nw(e){return e.localAppData??$.join(e.homeDir,"AppData","Local")}function tP(e){let t=[{kind:"foreign-entries",dir:sw(e),ours:[iw]}];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(nw(e),"AnthropicClaude")},{kind:"dir",path:$.join(nw(e),"Packages",eP)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Pt(e){return{evidence:[ua(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 aw(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 nP(e){return $.join(aw(e),"mcp_config.json")}function cw(e){return $.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function pa(e){let t=[ua(e,"Devin",["mcp_config.json"]),{kind:"dir",path:$.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:aw(e),ours:["mcp_config.json"]}),t.push(ua(e,"Windsurf"),{kind:"foreign-entries",dir:$.dirname(cw(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 aP(e){return e===null?null:sP.exec(e)?.[1]??null}function dw(e,t){let n=lw.map(r=>$.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push($.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of iP)for(let o of["/Applications",$.join(e.homeDir,"Applications")])n.push($.join(o,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function uw(e){return e.clineDataDir?e.clineDataDir:$.join(e.clineDir??$.join(e.homeDir,".cline"),"data")}function cP(e){return e.clineMcpSettingsPath??$.join(uw(e),"settings","cline_mcp_settings.json")}function Du(e){return{evidence:[{kind:"foreign-entries",dir:uw(e),ours:["settings"]},...rP.map(t=>({kind:"dir",path:$.join(fa(e,t),"User","globalStorage",rw)})),...dw(e,rw)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function ma(e){return e.continueGlobalDir??$.join(e.homeDir,".continue")}function lP(e){return $.join(ma(e),"mcpServers","maind.json")}function Pu(e){return{evidence:[{kind:"foreign-entries",dir:ma(e),ours:["mcpServers","rules"]},...dw(e,oP)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function Jr(e){return e.codexHome??$.join(e.homeDir,".codex")}function pi(e){return $.join(Jr(e),"config.toml")}function Yr(e){let t=Jr(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 Mu(e){return{evidence:[ua(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function dP(e){return $.join(QD(e),"mcp.json")}function fi(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:ZD(e),kind:"json",presence:tP(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:$.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Pt(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:nP(e),kind:"json",presence:pa(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:cw(e),kind:"json",presence:pa(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:dP(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:Mu(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:cP(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:Du(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:lP(e),kind:"json",presence:Pu(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:pi(e),kind:"toml",presence:Yr(e)}]}function pw(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function fw(e){return e.jsonShape??XD}function mw(e){let{homeDir:t,platform:n,env:r}=e,o=$.join(t,"Documents");if(n==="win32"){let l=["OneDrive","OneDriveConsumer","OneDriveCommercial"].map(d=>r[d]?.trim()).filter(d=>typeof d=="string"&&d.length>0&&$.win32.isAbsolute(d)).map(d=>$.join(d,"Documents"));return[...new Set([o,...l])]}if(n==="darwin")return[o];let i=r.XDG_CONFIG_HOME?.trim()||$.join(t,".config"),a=e.readText?.($.join(i,"user-dirs.dirs"))??null,c=a===null?null:hw(a,t);return c!==null&&c!==o?[c,o]:[o]}function hw(e,t){for(let n of e.split(/\r?\n/)){let r=/^\s*XDG_DOCUMENTS_DIR\s*=\s*"?([^"]*)"?\s*$/.exec(n);if(!r)continue;let o=r[1].replace(/^\$HOME(?=\/|$)/,t).replace(/^\$\{HOME\}(?=\/|$)/,t);return $.isAbsolute(o)&&o.length>1?$.normalize(o):null}return null}function Mt(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:da(e.env.XDG_CONFIG_HOME),appData:da(e.env.APPDATA),localAppData:da(e.env.LOCALAPPDATA),clineDir:ui(e.env.CLINE_DIR),clineDataDir:ui(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:ui(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:ui(e.env.CONTINUE_GLOBAL_DIR),codexHome:ui(e.env.CODEX_HOME),bundleAppRoot:aP(e.bridgeEntry??null),documentsDirs:mw({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return YD(t,"utf8")}catch{return null}},"readText")})}}function da(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ui(e){let t=da(e);return t!==null&&$.isAbsolute(t)?t:null}var XD,iw,eP,lw,rP,rw,oP,iP,sP,$u,Je=w(()=>{"use strict";_t();XD={serversKey:"mcpServers"};s(ow,"buildMaindServerEntry");iw="claude_desktop_config.json";s(sw,"claudeDesktopAppDataDir");s(ZD,"claudeDesktopConfigPath");s(fa,"editorAppDataDir");s(QD,"vsCodeUserDir");s(ua,"editorRan");s(nw,"localAppDataDir");eP="Claude_pzs8sxrjxfjjc";s(tP,"claudeDesktopPresence");s(Pt,"cursorPresence");s(aw,"devinConfigDir");s(nP,"devinMcpConfigPath");s(cw,"windsurfLegacyMcpConfigPath");s(pa,"devinDesktopPresence");lw=[{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"}],rP=lw.map(e=>e.appData),rw="saoudrizwan.claude-dev",oP="continue.continue",iP=["AgentComposer"],sP=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(aP,"bundleAppRootOf");s(dw,"agentExtensionEvidence");s(uw,"clineDataDir");s(cP,"clineMcpSettingsPath");s(Du,"clinePresence");s(ma,"continueGlobalDir");s(lP,"continueMcpConfigPath");s(Pu,"continuePresence");s(Jr,"codexHomeDir");s(pi,"codexConfigPath");s(Yr,"codexPresence");s(Mu,"vsCodePresence");s(dP,"vsCodeUserMcpPath");s(fi,"getClientTargets");s(pw,"filterTargetsByFamily");s(fw,"jsonShapeOf");$u=[...new Set(fi({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(mw,"documentsDirCandidates");s(hw,"parseXdgDocumentsDir");s(Mt,"makeDefaultContext");s(da,"nonEmpty");s(ui,"absoluteOrNull")});function Lu(){return $u.map(e=>{let t=Object.keys(ha).filter(n=>ha[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function gw(e){let t={projectRoot:null,full:!1,team:!1,noRules:!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,notices:[]};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"--team":t.team=!0;break;case"--no-rules":t.noRules=!0;break;case"--no-preamble":t.noPreamble||t.notices.push(uP),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 o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--project-root requires a path argument");t.projectRoot=o,n++;break}case"--token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--token requires a token argument");t.token=o,n++;break}case"--one-click-token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--one-click-token requires a token argument");t.oneClickToken=o,n++;break}case"--one-click-exchange-url":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=o,n++;break}case"--client":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye(`--client requires a family argument (${Lu()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(ha,i)?ha[i]:i;if(!$u.includes(a))throw new Ye(`--client "${o}" is not a known client family. Known: ${Lu()}`);t.client=a,n++;break}default:throw new Ye(`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.team&&"--team",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 Ye(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function yw(){process.stdout.write(pP())}function pP(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Pairs this device with MAIND and merges the MCP-server entry into every","supported AI-client config it finds (user level). Then it sets up the","channels that bring the MAIND hint and your project conventions into each","session \u2014 each with its own consent, only for clients that are installed:","hooks for Claude Code (~/.claude/settings.json), Cursor (~/.cursor/hooks.json)","and Codex (config.toml), user-level rule files for GitHub Copilot, Cline and","Continue. It writes nothing into your repository unless you pass --team.","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 (consents to the hooks and rule files)"," --team Also write into the repository, deliberately: the conventions"," block in AGENTS.md (kept current by the bridge) and the project"," .mcp.json \u2014 for teams whose colleagues should get the rules with"," the repository; recommended for teams that work mostly in Cursor"," --no-hook Never write hooks (Claude Code, Cursor, Codex; overrides --full)"," --no-rules Never write the user-level rule files (Copilot, Cline, Continue)"," --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:",` ${Lu()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --skip-codex Skip Codex (its config.toml and hook) even where Codex is installed",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only the user-level channels: the hooks (Claude Code; Cursor and"," Codex where installed) and the rule files (Copilot, Cline,"," Continue where installed) \u2014 no pairing, no MCP configs; adds"," what an existing install is missing; with --full, without prompts"," --telemetry Opt-in: post anonymous install_completed event"," --no-preamble No effect since 0.100.0 (accepted for old scripts)"," -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 --team # also AGENTS.md + .mcp.json in the repo"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","Blocks earlier versions wrote into a repository (CLAUDE.md, AGENTS.md, \u2026) stay","until you remove them: maind-mcp-bridge doctor --migrate-repo-blocks lists them.","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
147
- `)}var ha,uP,Ye,_w=w(()=>{"use strict";Je();ha={devin:"windsurf"};s(Lu,"familyChoices");uP="note: --no-preamble has no effect since bridge 0.100.0 \u2014 install writes no preamble files into the repository any more (ADR-364).";s(gw,"parseInstallFlags");Ye=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};s(yw,"printInstallHelp");s(pP,"installHelpText")});var mi,bw=w(()=>{"use strict";mi=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 o of this.results)o.status==="created"||o.status==="merged"||o.status==="skipped"||o.status==="would-create"||o.status==="would-merge"||o.status==="would-pair"?t++:o.status==="needs-user-decision"?n++:o.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_
145
+ `)}function Xb(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}async function LD(e){let t,n;switch(DD()){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,o)=>{try{let i=OD(t,n,{stdio:"ignore",detached:!0});i.on("error",o),i.unref(),r()}catch(i){o(i)}})}var Au=w(()=>{"use strict";re();qr();s(zr,"runDeviceFlow");s(PD,"pollOnce");s(MD,"sleep");s($D,"printAuthInstructions");s(Xb,"pad");s(LD,"openExternalBrowser")});import{mkdirSync as FD,readFileSync as jD,renameSync as HD,writeFileSync as UD}from"node:fs";import{join as BD}from"node:path";function Zb(e=it()){return BD(e,GD)}function VD(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,WD)}function Yn(e,t,n){try{let r=n.dir??it();FD(r,{recursive:!0,mode:448});let o={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:VD(t),bridge_version:n.version},i=Zb(r),a=`${i}.${process.pid}.tmp`;UD(a,JSON.stringify(o)+`
146
+ `,{encoding:"utf8",mode:384}),HD(a,i)}catch{}}function Qb(e=it()){try{let t=JSON.parse(jD(Zb(e),"utf8"));return t.v!==1||typeof t.at!="string"||!KD.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 KD,GD,WD,Iu=w(()=>{"use strict";re();KD=["ok","paired","auth_failed","not_paired"],GD="connection-state.json",WD=200;s(Zb,"connectionStatePath");s(VD,"redactDetail");s(Yn,"writeConnectionState");s(Qb,"readConnectionState")});var H,Fe=w(()=>{"use strict";H="0.101.0"});import{execFileSync as ew}from"node:child_process";import{createHash as qD}from"node:crypto";function Nu(e){return qD("sha256").update(e).digest("hex")}function Ou(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 nn(e){let t=Ou(e);return t?Nu(t):null}function ne(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&zD.test(e))return e;let t;try{t=ew("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nn(t):null}function yt(e){let t;try{t=ew("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nn(t):null}var zD,pe=w(()=>{"use strict";s(Nu,"sha256Hex");s(Ou,"normalizeRemoteUrl");s(nn,"projectKeyFromRemote");zD=/^[a-f0-9]{64}$/;s(ne,"computeProjectKey");s(yt,"projectKeyForRepo")});import JD from"node:path";import{fileURLToPath as YD}from"node:url";function XD(e,t=JD.sep){return e.split(t).includes("_npx")}function we(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",nw,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):XD(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 oe(){try{let e=YD(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function ze(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${tw(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:tw(n)).join(" ")}function rn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(nw)}function da(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function tw(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var nw,_t=w(()=>{"use strict";nw="@maind-dev/mcp-bridge";s(XD,"isEphemeralEntry");s(we,"resolveBridgeLaunch");s(oe,"currentBridgeEntry");s(ze,"launchToShellCommand");s(rn,"isNpxForm");s(da,"isLegacyHookForm");s(tw,"shellQuote")});import{readFileSync as ZD}from"node:fs";import*as $ from"node:path";function iw(e){let t=e.launch??we({entryPath:oe(),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 aw(e){return ma(e,"Claude")}function eP(e){return $.join(aw(e),sw)}function ma(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 tP(e){return $.join(ma(e,"Code"),"User")}function pa(e,t,n=[]){return{kind:"foreign-entries",dir:ma(e,t),ours:["User",...n]}}function rw(e){return e.localAppData??$.join(e.homeDir,"AppData","Local")}function rP(e){let t=[{kind:"foreign-entries",dir:aw(e),ours:[sw]}];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(rw(e),"AnthropicClaude")},{kind:"dir",path:$.join(rw(e),"Packages",nP)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Mt(e){return{evidence:[pa(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 cw(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 oP(e){return $.join(cw(e),"mcp_config.json")}function lw(e){return $.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function fa(e){let t=[pa(e,"Devin",["mcp_config.json"]),{kind:"dir",path:$.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:cw(e),ours:["mcp_config.json"]}),t.push(pa(e,"Windsurf"),{kind:"foreign-entries",dir:$.dirname(lw(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 lP(e){return e===null?null:cP.exec(e)?.[1]??null}function uw(e,t){let n=dw.map(r=>$.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push($.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of aP)for(let o of["/Applications",$.join(e.homeDir,"Applications")])n.push($.join(o,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function pw(e){return e.clineDataDir?e.clineDataDir:$.join(e.clineDir??$.join(e.homeDir,".cline"),"data")}function dP(e){return e.clineMcpSettingsPath??$.join(pw(e),"settings","cline_mcp_settings.json")}function Du(e){return{evidence:[{kind:"foreign-entries",dir:pw(e),ours:["settings"]},...iP.map(t=>({kind:"dir",path:$.join(ma(e,t),"User","globalStorage",ow)})),...uw(e,ow)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function ha(e){return e.continueGlobalDir??$.join(e.homeDir,".continue")}function uP(e){return $.join(ha(e),"mcpServers","maind.json")}function Pu(e){return{evidence:[{kind:"foreign-entries",dir:ha(e),ours:["mcpServers","rules"]},...uw(e,sP)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function Jr(e){return e.codexHome??$.join(e.homeDir,".codex")}function pi(e){return $.join(Jr(e),"config.toml")}function Yr(e){let t=Jr(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 Mu(e){return{evidence:[pa(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function pP(e){return $.join(tP(e),"mcp.json")}function fi(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:eP(e),kind:"json",presence:rP(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:$.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Mt(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:oP(e),kind:"json",presence:fa(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:lw(e),kind:"json",presence:fa(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:pP(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:Mu(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:dP(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:Du(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:uP(e),kind:"json",presence:Pu(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:pi(e),kind:"toml",presence:Yr(e)}]}function fw(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function mw(e){return e.jsonShape??QD}function hw(e){let{homeDir:t,platform:n,env:r}=e,o=$.join(t,"Documents");if(n==="win32"){let l=["OneDrive","OneDriveConsumer","OneDriveCommercial"].map(d=>r[d]?.trim()).filter(d=>typeof d=="string"&&d.length>0&&$.win32.isAbsolute(d)).map(d=>$.join(d,"Documents"));return[...new Set([o,...l])]}if(n==="darwin")return[o];let i=r.XDG_CONFIG_HOME?.trim()||$.join(t,".config"),a=e.readText?.($.join(i,"user-dirs.dirs"))??null,c=a===null?null:gw(a,t);return c!==null&&c!==o?[c,o]:[o]}function gw(e,t){for(let n of e.split(/\r?\n/)){let r=/^\s*XDG_DOCUMENTS_DIR\s*=\s*"?([^"]*)"?\s*$/.exec(n);if(!r)continue;let o=r[1].replace(/^\$HOME(?=\/|$)/,t).replace(/^\$\{HOME\}(?=\/|$)/,t);return $.isAbsolute(o)&&o.length>1?$.normalize(o):null}return null}function $t(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:ua(e.env.XDG_CONFIG_HOME),appData:ua(e.env.APPDATA),localAppData:ua(e.env.LOCALAPPDATA),clineDir:ui(e.env.CLINE_DIR),clineDataDir:ui(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:ui(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:ui(e.env.CONTINUE_GLOBAL_DIR),codexHome:ui(e.env.CODEX_HOME),bundleAppRoot:lP(e.bridgeEntry??null),documentsDirs:hw({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return ZD(t,"utf8")}catch{return null}},"readText")})}}function ua(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ui(e){let t=ua(e);return t!==null&&$.isAbsolute(t)?t:null}var QD,sw,nP,dw,iP,ow,sP,aP,cP,$u,Je=w(()=>{"use strict";_t();QD={serversKey:"mcpServers"};s(iw,"buildMaindServerEntry");sw="claude_desktop_config.json";s(aw,"claudeDesktopAppDataDir");s(eP,"claudeDesktopConfigPath");s(ma,"editorAppDataDir");s(tP,"vsCodeUserDir");s(pa,"editorRan");s(rw,"localAppDataDir");nP="Claude_pzs8sxrjxfjjc";s(rP,"claudeDesktopPresence");s(Mt,"cursorPresence");s(cw,"devinConfigDir");s(oP,"devinMcpConfigPath");s(lw,"windsurfLegacyMcpConfigPath");s(fa,"devinDesktopPresence");dw=[{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"}],iP=dw.map(e=>e.appData),ow="saoudrizwan.claude-dev",sP="continue.continue",aP=["AgentComposer"],cP=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(lP,"bundleAppRootOf");s(uw,"agentExtensionEvidence");s(pw,"clineDataDir");s(dP,"clineMcpSettingsPath");s(Du,"clinePresence");s(ha,"continueGlobalDir");s(uP,"continueMcpConfigPath");s(Pu,"continuePresence");s(Jr,"codexHomeDir");s(pi,"codexConfigPath");s(Yr,"codexPresence");s(Mu,"vsCodePresence");s(pP,"vsCodeUserMcpPath");s(fi,"getClientTargets");s(fw,"filterTargetsByFamily");s(mw,"jsonShapeOf");$u=[...new Set(fi({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(hw,"documentsDirCandidates");s(gw,"parseXdgDocumentsDir");s($t,"makeDefaultContext");s(ua,"nonEmpty");s(ui,"absoluteOrNull")});function Lu(){return $u.map(e=>{let t=Object.keys(ga).filter(n=>ga[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function yw(e){let t={projectRoot:null,full:!1,team:!1,noRules:!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,notices:[]};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"--team":t.team=!0;break;case"--no-rules":t.noRules=!0;break;case"--no-preamble":t.noPreamble||t.notices.push(fP),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 o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--project-root requires a path argument");t.projectRoot=o,n++;break}case"--token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--token requires a token argument");t.token=o,n++;break}case"--one-click-token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--one-click-token requires a token argument");t.oneClickToken=o,n++;break}case"--one-click-exchange-url":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=o,n++;break}case"--client":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Ye(`--client requires a family argument (${Lu()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(ga,i)?ga[i]:i;if(!$u.includes(a))throw new Ye(`--client "${o}" is not a known client family. Known: ${Lu()}`);t.client=a,n++;break}default:throw new Ye(`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.team&&"--team",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 Ye(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function _w(){process.stdout.write(mP())}function mP(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Pairs this device with MAIND and merges the MCP-server entry into every","supported AI-client config it finds (user level). Then it sets up the","channels that bring the MAIND hint and your project conventions into each","session \u2014 each with its own consent, only for clients that are installed:","hooks for Claude Code (~/.claude/settings.json), Cursor (~/.cursor/hooks.json)","and Codex (config.toml), user-level rule files for GitHub Copilot, Cline and","Continue. It writes nothing into your repository unless you pass --team.","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 (consents to the hooks and rule files)"," --team Also write into the repository, deliberately: the conventions"," block in AGENTS.md (kept current by the bridge) and the project"," .mcp.json \u2014 for teams whose colleagues should get the rules with"," the repository; recommended for teams that work mostly in Cursor"," --no-hook Never write hooks (Claude Code, Cursor, Codex; overrides --full)"," --no-rules Never write the user-level rule files (Copilot, Cline, Continue)"," --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:",` ${Lu()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --skip-codex Skip Codex (its config.toml and hook) even where Codex is installed",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only the user-level channels: the hooks (Claude Code; Cursor and"," Codex where installed) and the rule files (Copilot, Cline,"," Continue where installed) \u2014 no pairing, no MCP configs; adds"," what an existing install is missing; with --full, without prompts"," --telemetry Opt-in: post anonymous install_completed event"," --no-preamble No effect since 0.100.0 (accepted for old scripts)"," -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 --team # also AGENTS.md + .mcp.json in the repo"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","Blocks earlier versions wrote into a repository (CLAUDE.md, AGENTS.md, \u2026) stay","until you remove them: maind-mcp-bridge doctor --migrate-repo-blocks lists them.","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
147
+ `)}var ga,fP,Ye,bw=w(()=>{"use strict";Je();ga={devin:"windsurf"};s(Lu,"familyChoices");fP="note: --no-preamble has no effect since bridge 0.100.0 \u2014 install writes no preamble files into the repository any more (ADR-364).";s(yw,"parseInstallFlags");Ye=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};s(_w,"printInstallHelp");s(mP,"installHelpText")});var mi,ww=w(()=>{"use strict";mi=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 o of this.results)o.status==="created"||o.status==="merged"||o.status==="skipped"||o.status==="would-create"||o.status==="would-merge"||o.status==="would-pair"?t++:o.status==="needs-user-decision"?n++:o.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_
148
148
  `;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)),o=Math.max(t[2].length,...this.results.map(d=>d.status.length)),i=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(o)} | ${"-".repeat(i)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],o)} | ${a(t[3],i)} |`),l.push(c);for(let d of this.results)l.push(`| ${a(d.target,n)} | ${a(d.action,r)} | ${a(d.status,o)} | ${a(d.detail??"",i)} |`);return l.join(`
149
149
  `)+`
150
150
  `}print(t){let n=this.summary();t.write(`
151
151
  `),t.write(this.toMarkdownTable()),t.write(`
152
152
  Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
153
- `)}toJson(){return{steps:[...this.results],summary:this.summary()}}}});import*as ww from"node:fs/promises";import*as on from"node:path";import*as vw from"node:readline";async function kw(e){let t=on.resolve(e),n=t;for(;;){if(await xw(n))return n;let r=on.dirname(n);if(r===n)return t;n=r}}async function ga(e){let n=on.resolve(e),r=[];for(;;){await xw(n)&&r.push(n);let o=on.dirname(n);if(o===n)break;n=o}return r}async function xw(e){for(let t of fP)try{return await ww.access(on.join(e,t)),!0}catch{}return!1}async function Sw(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
153
+ `)}toJson(){return{steps:[...this.results],summary:this.summary()}}}});import*as vw from"node:fs/promises";import*as on from"node:path";import*as kw from"node:readline";async function xw(e){let t=on.resolve(e),n=t;for(;;){if(await Sw(n))return n;let r=on.dirname(n);if(r===n)return t;n=r}}async function ya(e){let n=on.resolve(e),r=[];for(;;){await Sw(n)&&r.push(n);let o=on.dirname(n);if(o===n)break;n=o}return r}async function Sw(e){for(let t of hP)try{return await vw.access(on.join(e,t)),!0}catch{}return!1}async function Ew(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
154
154
  Multiple project roots found between cwd and the filesystem root:
155
155
  `),e.forEach((i,a)=>{process.stdout.write(` [${a+1}] ${i}
156
156
  `)}),process.stdout.write(`
157
- Which one should install --team write AGENTS.md and .mcp.json into? [1-${e.length}, default 1]: `);let n=vw.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(i=>{n.question("",a=>i(a.trim()))});if(n.close(),r==="")return e[0];let o=Number.parseInt(r,10);return Number.isNaN(o)||o<1||o>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
158
- `),null):e[o-1]}var fP,Fu=w(()=>{"use strict";fP=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];s(kw,"detectProjectRoot");s(ga,"findAllProjectRoots");s(xw,"hasAnyMarker");s(Sw,"disambiguateProjectRoot")});import{existsSync as mP,readdirSync as hP}from"node:fs";import*as fe from"node:fs/promises";import*as ya from"node:path";async function q(e){try{return await fe.readFile(e,"utf8")}catch(t){if(yP(t))return null;throw t}}async function gP(e){await fe.mkdir(e,{recursive:!0})}async function U(e,t,n){let r=ya.dirname(e);await gP(r);let o=ya.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await fe.writeFile(o,t,{encoding:"utf8",mode:n});try{await fe.rename(o,e)}catch(i){if(_P(i))try{await fe.copyFile(o,e),await fe.unlink(o).catch(()=>{}),n!==void 0&&await fe.chmod(e,n).catch(()=>{});return}catch(a){throw await fe.unlink(o).catch(()=>{}),a}throw await fe.unlink(o).catch(()=>{}),i}}async function Ew(e,t){let n=await q(e);return n===null?!1:n.split(/\r?\n/).some(o=>o.startsWith(t))}function yP(e){return Rw(e)&&e.code==="ENOENT"}function _P(e){return!Rw(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Rw(e){return typeof e=="object"&&e!==null&&"code"in e}var ce,ie=w(()=>{"use strict";ce={exists:s(e=>mP(e),"exists"),readdir:s(e=>{try{return hP(e)}catch{return null}},"readdir")};s(q,"readFileSafe");s(gP,"ensureDir");s(U,"atomicWriteFile");s(Ew,"hasLinePrefix");s(yP,"isNoEnt");s(_P,"isWindowsRenameFailure");s(Rw,"isNodeError")});function bP(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function wP(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(`${r}-`)}function vP(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=>wP(r,e.id)):n.some(r=>!bP(r)&&!e.ours.includes(r))}function Ne(e,t){return e.evidence.some(n=>vP(n,t))}function Cw(e,t){return Ne(Pt(e),t)}function Tw(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||Ne(t.presence,r))return null;let o=r.exists(t.path);return{target:t.key,action:"merge",status:"skipped",detail:o?`${t.presence.skipDetail}; leftover file: maind-mcp-bridge doctor --remove-phantoms`:t.presence.skipDetail}}var Xr=w(()=>{"use strict";Je();s(bP,"isNoise");s(wP,"isExtensionFolder");s(vP,"evidenceHolds");s(Ne,"clientPresent");s(Cw,"cursorInstalled");s(Tw,"presenceSkipRow")});import{applyEdits as kP,modify as xP,parse as SP,printParseErrorCode as EP}from"jsonc-parser";async function Ow(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=fw(e),o=r.serversKey==="servers",i;try{i=await q(e.path)}catch(h){return ju(e,"read",h)}let a,c="create";if(i===null||i.trim().length===0)a={};else{c="merge";try{a=o?RP(i):JSON.parse(i)}catch(h){return e.refreshOnly!==void 0?Nw(e,`not valid JSON: ${h instanceof Error?h.message:String(h)}`):ju(e,"parse",h)}}if(!sn(a))return e.refreshOnly!==void 0?Nw(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(i===null||!sn(h)||!(Xn in h))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&TP(a),d,u,p=!1;if(l){let h=a[Xn];p=Iw(h,t,r),u=Aw(h,t,r),d={...a,[Xn]:u}}else{let h=a[r.serversKey],g=sn(h)?h:{},y=g[Xn];p=Iw(y,t,r),u=Aw(y,t,r),d={...a,[r.serversKey]:{...g,[Xn]:u}}}if(p&&i!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=o&&!l?CP(i??"",[r.serversKey,Xn],u):JSON.stringify(d,null,2)+`
159
- `;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await U(e.path,f)}catch(h){return ju(e,"write",h)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}function Aw(e,t,n){let r=sn(e)&&sn(e.env)?e.env:{},o={...t.env};for(let[p,f]of Object.entries(r))!(p in o)&&typeof f=="string"&&(o[p]=f);let i={command:t.command,args:[...t.args],env:o},a=n.entryType===void 0?i:{type:n.entryType,...i};if(n.clientKeys===void 0)return a;let{defaults:c,drop:l}=n.clientKeys,d={};if(sn(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)}}function RP(e){let t=[],n=SP(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${EP(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}function CP(e,t,n){let r=xP(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
160
- `}}),o=kP(e,r);return o.endsWith(`
157
+ Which one should install --team write AGENTS.md and .mcp.json into? [1-${e.length}, default 1]: `);let n=kw.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(i=>{n.question("",a=>i(a.trim()))});if(n.close(),r==="")return e[0];let o=Number.parseInt(r,10);return Number.isNaN(o)||o<1||o>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
158
+ `),null):e[o-1]}var hP,Fu=w(()=>{"use strict";hP=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];s(xw,"detectProjectRoot");s(ya,"findAllProjectRoots");s(Sw,"hasAnyMarker");s(Ew,"disambiguateProjectRoot")});import{existsSync as gP,readdirSync as yP}from"node:fs";import*as fe from"node:fs/promises";import*as _a from"node:path";async function q(e){try{return await fe.readFile(e,"utf8")}catch(t){if(bP(t))return null;throw t}}async function _P(e){await fe.mkdir(e,{recursive:!0})}async function U(e,t,n){let r=_a.dirname(e);await _P(r);let o=_a.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await fe.writeFile(o,t,{encoding:"utf8",mode:n});try{await fe.rename(o,e)}catch(i){if(wP(i))try{await fe.copyFile(o,e),await fe.unlink(o).catch(()=>{}),n!==void 0&&await fe.chmod(e,n).catch(()=>{});return}catch(a){throw await fe.unlink(o).catch(()=>{}),a}throw await fe.unlink(o).catch(()=>{}),i}}async function Rw(e,t){let n=await q(e);return n===null?!1:n.split(/\r?\n/).some(o=>o.startsWith(t))}function bP(e){return Cw(e)&&e.code==="ENOENT"}function wP(e){return!Cw(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Cw(e){return typeof e=="object"&&e!==null&&"code"in e}var ce,ie=w(()=>{"use strict";ce={exists:s(e=>gP(e),"exists"),readdir:s(e=>{try{return yP(e)}catch{return null}},"readdir")};s(q,"readFileSafe");s(_P,"ensureDir");s(U,"atomicWriteFile");s(Rw,"hasLinePrefix");s(bP,"isNoEnt");s(wP,"isWindowsRenameFailure");s(Cw,"isNodeError")});function vP(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function kP(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(`${r}-`)}function xP(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=>kP(r,e.id)):n.some(r=>!vP(r)&&!e.ours.includes(r))}function Ne(e,t){return e.evidence.some(n=>xP(n,t))}function Tw(e,t){return Ne(Mt(e),t)}function Aw(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||Ne(t.presence,r))return null;let o=r.exists(t.path);return{target:t.key,action:"merge",status:"skipped",detail:o?`${t.presence.skipDetail}; leftover file: maind-mcp-bridge doctor --remove-phantoms`:t.presence.skipDetail}}var Xr=w(()=>{"use strict";Je();s(vP,"isNoise");s(kP,"isExtensionFolder");s(xP,"evidenceHolds");s(Ne,"clientPresent");s(Tw,"cursorInstalled");s(Aw,"presenceSkipRow")});import{applyEdits as SP,modify as EP,parse as RP,printParseErrorCode as CP}from"jsonc-parser";async function Dw(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=mw(e),o=r.serversKey==="servers",i;try{i=await q(e.path)}catch(h){return ju(e,"read",h)}let a,c="create";if(i===null||i.trim().length===0)a={};else{c="merge";try{a=o?TP(i):JSON.parse(i)}catch(h){return e.refreshOnly!==void 0?Ow(e,`not valid JSON: ${h instanceof Error?h.message:String(h)}`):ju(e,"parse",h)}}if(!sn(a))return e.refreshOnly!==void 0?Ow(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(i===null||!sn(h)||!(Xn in h))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&IP(a),d,u,p=!1;if(l){let h=a[Xn];p=Nw(h,t,r),u=Iw(h,t,r),d={...a,[Xn]:u}}else{let h=a[r.serversKey],g=sn(h)?h:{},y=g[Xn];p=Nw(y,t,r),u=Iw(y,t,r),d={...a,[r.serversKey]:{...g,[Xn]:u}}}if(p&&i!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=o&&!l?AP(i??"",[r.serversKey,Xn],u):JSON.stringify(d,null,2)+`
159
+ `;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await U(e.path,f)}catch(h){return ju(e,"write",h)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}function Iw(e,t,n){let r=sn(e)&&sn(e.env)?e.env:{},o={...t.env};for(let[p,f]of Object.entries(r))!(p in o)&&typeof f=="string"&&(o[p]=f);let i={command:t.command,args:[...t.args],env:o},a=n.entryType===void 0?i:{type:n.entryType,...i};if(n.clientKeys===void 0)return a;let{defaults:c,drop:l}=n.clientKeys,d={};if(sn(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)}}function TP(e){let t=[],n=RP(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${CP(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}function AP(e,t,n){let r=EP(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
160
+ `}}),o=SP(e,r);return o.endsWith(`
161
161
  `)?o:o+`
162
- `}function TP(e){return!("mcpServers"in e||!(Xn in e))}function Iw(e,t,n){if(!sn(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||!AP(e.args,t.args)||!sn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}function AP(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}function sn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nw(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}function ju(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var Xn,Dw=w(()=>{"use strict";ie();Je();Xn="maind";s(Ow,"mergeJsonConfig");s(Aw,"mergeEntry");s(RP,"parseJsoncStrict");s(CP,"editInPlace");s(TP,"hasRootShape");s(Iw,"serverEntriesEqual");s(AP,"arrayEquals");s(sn,"isObject");s(Nw,"leftAlone");s(ju,"failed")});import{parse as IP,stringify as NP}from"smol-toml";async function Pw(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await q(e.path)}catch(g){return _a(e,"read",g)}let o,i="create";if(r===null||r.trim().length===0)o={};else{i="merge";try{let g=IP(r);if(!Zn(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};o=g}catch(g){return _a(e,"parse",g)}}let a=Zn(o.mcp_servers)?o.mcp_servers:{},c=a.maind;if(Zn(c)&&OP(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Zn(c)&&Zn(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={...o,mcp_servers:{...a,maind:u}},f;try{f=NP(p),f.endsWith(`
162
+ `}function IP(e){return!("mcpServers"in e||!(Xn in e))}function Nw(e,t,n){if(!sn(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||!NP(e.args,t.args)||!sn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}function NP(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}function sn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ow(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}function ju(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var Xn,Pw=w(()=>{"use strict";ie();Je();Xn="maind";s(Dw,"mergeJsonConfig");s(Iw,"mergeEntry");s(TP,"parseJsoncStrict");s(AP,"editInPlace");s(IP,"hasRootShape");s(Nw,"serverEntriesEqual");s(NP,"arrayEquals");s(sn,"isObject");s(Ow,"leftAlone");s(ju,"failed")});import{parse as OP,stringify as DP}from"smol-toml";async function Mw(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await q(e.path)}catch(g){return ba(e,"read",g)}let o,i="create";if(r===null||r.trim().length===0)o={};else{i="merge";try{let g=OP(r);if(!Zn(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};o=g}catch(g){return ba(e,"parse",g)}}let a=Zn(o.mcp_servers)?o.mcp_servers:{},c=a.maind;if(Zn(c)&&PP(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Zn(c)&&Zn(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={...o,mcp_servers:{...a,maind:u}},f;try{f=DP(p),f.endsWith(`
163
163
  `)||(f+=`
164
- `)}catch(g){return _a(e,"write",g)}let h=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(h.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${h.length}`};if(n)return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"would-create":"would-merge",detail:e.path};try{await U(e.path,f)}catch(g){return _a(e,"write",g)}return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"created":"merged",detail:e.path}}function OP(e,t){if(!Zn(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(!Zn(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}function Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _a(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var Mw=w(()=>{"use strict";ie();s(Pw,"mergeTomlConfig");s(OP,"tomlServerEntryEqual");s(Zn,"isObject");s(_a,"failed")});function $P(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 LP(e){return`I want to add the **maind MCP server** to my AI coding agent.
164
+ `)}catch(g){return ba(e,"write",g)}let h=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(h.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${h.length}`};if(n)return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"would-create":"would-merge",detail:e.path};try{await U(e.path,f)}catch(g){return ba(e,"write",g)}return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"created":"merged",detail:e.path}}function PP(e,t){if(!Zn(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(!Zn(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}function Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ba(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var $w=w(()=>{"use strict";ie();s(Mw,"mergeTomlConfig");s(PP,"tomlServerEntryEqual");s(Zn,"isObject");s(ba,"failed")});function FP(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 jP(e){return`I want to add the **maind MCP server** to my AI coding agent.
165
165
 
166
166
  - My stack: \`__STACK__\`
167
167
  - MCP endpoint: \`${e}\`
@@ -170,11 +170,14 @@ Please set this up strictly in order. Do not skip steps silently.
170
170
 
171
171
  ## Setup rules
172
172
 
173
- 1. Resolve \`PROJECT_ROOT\` before writing preamble files. Prefer the current
174
- workspace project root. If multiple plausible project roots exist, ask me
175
- which one should receive \`CLAUDE.md\`, \`AGENTS.md\`,
176
- \`.github/copilot-instructions.md\`, \`.cursorrules\`, and
177
- \`.windsurfrules\` before continuing.
173
+ 1. Write nothing into the repository unless I confirm it. Two configs below
174
+ can live in the project \u2014 \`.mcp.json\` (Claude Code) and
175
+ \`.vscode/mcp.json\` (GitHub Copilot) \u2014 and travel with it to everyone who
176
+ clones it. Before writing either, resolve \`PROJECT_ROOT\` (prefer the
177
+ current workspace project root; if several are plausible, ask me which
178
+ one) and ask whether I want that file there. Never add a maind block to
179
+ \`CLAUDE.md\`, \`AGENTS.md\`, \`.github/copilot-instructions.md\`,
180
+ \`.cursorrules\` or \`.windsurfrules\`.
178
181
  2. Use \`@maind-dev/mcp-bridge\` everywhere. Browser pairing is the only
179
182
  supported setup path for this prompt; do not embed API keys in config files.
180
183
  3. Preflight before writing: scan every target config you can access for
@@ -205,7 +208,21 @@ Please set this up strictly in order. Do not skip steps silently.
205
208
  Use the browser-pairing blocks below. They intentionally omit API keys; the
206
209
  bridge creates and stores a device-bound key during first launch.
207
210
 
208
- # Claude Code project-scoped .mcp.json
211
+ # Claude Code user scope (~/.claude.json mcpServers.maind shape \u2014 where the
212
+ # installer writes it)
213
+ {
214
+ "maind": {
215
+ "command": "npx",
216
+ "args": ["-y", "@maind-dev/mcp-bridge"],
217
+ "env": {
218
+ "MAIND_CLIENT_FAMILY": "claude-code",
219
+ "MAIND_MCP_URL": "${e}"
220
+ }
221
+ }
222
+ }
223
+
224
+ # Claude Code project-scoped PROJECT_ROOT/.mcp.json \u2014 only if I confirm it
225
+ # (setup rule 1)
209
226
  {
210
227
  "mcpServers": {
211
228
  "maind": {
@@ -219,18 +236,6 @@ bridge creates and stores a device-bound key during first launch.
219
236
  }
220
237
  }
221
238
 
222
- # Claude Code user-scope fallback (~/.claude.json mcpServers.maind shape)
223
- {
224
- "maind": {
225
- "command": "npx",
226
- "args": ["-y", "@maind-dev/mcp-bridge"],
227
- "env": {
228
- "MAIND_CLIENT_FAMILY": "claude-code",
229
- "MAIND_MCP_URL": "${e}"
230
- }
231
- }
232
- }
233
-
234
239
  # Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json)
235
240
  {
236
241
  "mcpServers": {
@@ -253,7 +258,10 @@ args = ["-y", "@maind-dev/mcp-bridge"]
253
258
  MAIND_CLIENT_FAMILY = "codex"
254
259
  MAIND_MCP_URL = "${e}"
255
260
 
256
- # GitHub Copilot / VS Code workspace MCP (PROJECT_ROOT/.vscode/mcp.json)
261
+ # GitHub Copilot / VS Code MCP: VS Code's user-profile mcp.json, where the
262
+ # installer writes it (macOS ~/Library/Application Support/Code/User/mcp.json,
263
+ # Linux ~/.config/Code/User/mcp.json, Windows %APPDATA%\\Code\\User\\mcp.json) \u2014
264
+ # or the workspace PROJECT_ROOT/.vscode/mcp.json, only if I confirm it (setup rule 1).
257
265
  # VS Code's own shape: \`servers\` (not \`mcpServers\`) and \`"type": "stdio"\` on the
258
266
  # entry \u2014 an \`mcpServers\` key is ignored silently. The file is JSONC: keep any
259
267
  # existing comments and the other \`servers.*\` / \`inputs\` entries as they are.
@@ -344,22 +352,17 @@ MAIND_MCP_URL = "${e}"
344
352
  }
345
353
  }
346
354
 
347
- ## Preamble files
355
+ ## Session hint for Claude Code
348
356
 
349
- Append the exact block below to \`PROJECT_ROOT/CLAUDE.md\`,
350
- \`PROJECT_ROOT/AGENTS.md\`, \`PROJECT_ROOT/.github/copilot-instructions.md\`,
351
- \`PROJECT_ROOT/.cursorrules\`, and \`PROJECT_ROOT/.windsurfrules\` only when
352
- the file does not already contain a line starting with
353
- \`## maind MCP integration\`. Create missing files with only this block. Report
354
- written vs skipped.
355
-
356
- Also write a byte-identical copy to
357
- \`~/.claude/maind-session-start-reminder.md\`. Then print this JSON snippet and
357
+ Write the exact block at the end of this prompt to
358
+ \`~/.claude/maind-session-start-reminder.md\` \u2014 a file in my home directory,
359
+ not in the repository. If the file already exists, leave it as it is and
360
+ report skipped. Then print this JSON snippet and
358
361
  ask me to merge it manually into \`~/.claude/settings.json\` or
359
362
  \`~/.claude/settings.local.json\`; do not auto-write hook JSON:
360
363
 
361
364
  \`\`\`json
362
- { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${$w}", "timeout": 5 } ] } ] } }
365
+ { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${Lw}", "timeout": 5 } ] } ] } }
363
366
  \`\`\`
364
367
 
365
368
  The hook runs the bridge subcommand \`on-session-reminder\` (bridge 0.94.0 or
@@ -368,6 +371,19 @@ later). If a SessionStart entry already runs
368
371
  replace its command with the one above instead of adding a second entry \u2014
369
372
  \`cat\` prints plain text into Cursor, which takes only JSON there.
370
373
 
374
+ ## Nothing in the repository
375
+
376
+ Do not write this block into any repository file. Bridge 0.100.0 and later
377
+ keep maind's session channels out of the repository; tell me that
378
+ \`npx -y @maind-dev/mcp-bridge install --hooks-only\` sets up the ones this
379
+ prompt leaves out \u2014 the conventions briefing hook for Claude Code, the hooks
380
+ for Cursor and Codex, the user-level rule files for GitHub Copilot, Cline and
381
+ Continue \u2014 asking before each one, without pairing and without MCP configs.
382
+ If a repository file already holds a line starting with
383
+ \`## maind MCP integration\` from an earlier setup, leave it and tell me that
384
+ \`npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks\` lists such
385
+ blocks and removes them only when run with \`--yes\`.
386
+
371
387
  ## Session-start message
372
388
 
373
389
  After setup, write this message to the clipboard when possible and print it as
@@ -400,7 +416,7 @@ $i3 = '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_sessi
400
416
  Verification failure should be reported in the final table; do not undo the
401
417
  written config.
402
418
 
403
- --- Preamble block ---
419
+ --- Session hint block ---
404
420
 
405
421
  ${bt}`}function Qn(e,t,n,r={serversKey:"mcpServers"},o={}){let i=n?`
406
422
  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?`
@@ -451,7 +467,7 @@ ${d}`:""}
451
467
  config[serversKey].maind = server;
452
468
  fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
453
469
  console.log("WROTE " + file);
454
- NODE`}function FP(e){return`#!/usr/bin/env bash
470
+ NODE`}function HP(e){return`#!/usr/bin/env bash
455
471
  set -euo pipefail
456
472
 
457
473
  CONFIG_FILE="$HOME/.codex/config.toml"
@@ -504,7 +520,7 @@ if (serverCount !== 1 || envCount !== 1) {
504
520
 
505
521
  fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
506
522
  console.log("WROTE " + file);
507
- NODE`}function jP(e=Hu){let t=`${e}${MP}`;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:LP(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:`{
523
+ NODE`}function UP(e=Hu){let t=`${e}${LP}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing and merges the MCP-server entry into the user-level config of every supported AI client it finds (Claude Code, Cursor, Devin Desktop (formerly Windsurf), Codex, Copilot, Claude Desktop, Cline, Continue). Then it asks before each session channel it sets up for the MAIND hint and your project conventions: hooks for Claude Code, Cursor and Codex, user-level rule files for GitHub Copilot, Cline and Continue. Since bridge 0.100.0 it writes nothing into your repository unless you pass --team. Idempotent \u2014 re-running is safe. Run it 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 and consent to the hooks and the user-level rule files without asking \u2014 pass --no-hook or --no-rules 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>"},{label:"Team option (writes into the repository)",description:"Everything the installer does, plus two files in the repository, on purpose: the conventions block in AGENTS.md, which the bridge keeps current, and the project .mcp.json \u2014 so colleagues get the rules with the repository. Recommended for teams that work mostly in Cursor. Run it from the project root (bridge 0.100.0 or later).",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --team"},{label:"Old repository blocks",description:"Bridges before 0.100.0 wrote a MAIND block into CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules and .windsurfrules. This lists the blocks in the current repository and changes nothing. Add --yes to set up the user-level channels first and then remove exactly the listed blocks; a block you edited by hand is listed for you to remove yourself, and a team block in AGENTS.md stays.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks"}]},{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:jP(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:`{
508
524
  "mcpServers": {
509
525
  "maind": {
510
526
  "command": "npx",
@@ -532,7 +548,7 @@ args = ["-y", "@maind-dev/mcp-bridge"]
532
548
 
533
549
  [mcp_servers.maind.env]
534
550
  MAIND_CLIENT_FAMILY = "codex"
535
- 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:FP(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:`{
551
+ 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:HP(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:`{
536
552
  "servers": {
537
553
  "maind": {
538
554
  "type": "stdio",
@@ -544,40 +560,27 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
544
560
  }
545
561
  }
546
562
  }
547
- }`,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:Qn(".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 (the bridge subcommand on-session-reminder, bridge 0.94.0 or later) 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
548
- # maind agent-preamble installer \u2014 idempotent. Creates or extends:
549
- # CLAUDE.md (Claude Code)
550
- # AGENTS.md (Codex, Devin Desktop, newer Cursor \u2014 cross-agent standard)
551
- # .github/copilot-instructions.md (GitHub Copilot)
552
- # .cursorrules (Cursor legacy)
553
- # .windsurfrules (Devin Desktop / Windsurf legacy)
554
- # ~/.claude/maind-session-start-reminder.md (Claude Code SessionStart-Hook input)
555
- # Plus emits a JSON snippet for manual merge into ~/.claude/settings.json
556
- # (the SessionStart-Hook that adds the reminder to every new session \u2014 the
563
+ }`,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:Qn(".vscode/mcp.json",t,"copilot",{serversKey:"servers",entryType:"stdio"})}]},{id:"agent-preamble",label:"Session hint for Claude Code (user level)",description:"Idempotent shell script for setups without the installer. It writes MAIND's session hint to ~/.claude/maind-session-start-reminder.md and prints the SessionStart hook to merge into ~/.claude/settings.json by hand (the bridge subcommand on-session-reminder, bridge 0.94.0 or later) \u2014 a manual step, because a naive append breaks JSON. It writes nothing into your repository. To set up every session channel at once \u2014 the conventions briefing for Claude Code, hooks for Cursor and Codex, user-level rule files for GitHub Copilot, Cline and Continue \u2014 run npx -y @maind-dev/mcp-bridge install --hooks-only instead: no pairing, no MCP configs, one consent per channel.",filename:"writes ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
564
+ # maind session hint for Claude Code \u2014 idempotent, user level only. Writes:
565
+ # ~/.claude/maind-session-start-reminder.md (read by the SessionStart hook)
566
+ # Plus prints a JSON snippet for manual merge into ~/.claude/settings.json
567
+ # (the SessionStart hook that adds the hint to every new session \u2014 the
557
568
  # bridge subcommand on-session-reminder, bridge 0.94.0 or later).
558
569
  #
559
- # Re-running this script is safe \u2014 it checks for an existing maind section first.
570
+ # Nothing goes into the repository. A maind block that an earlier setup wrote
571
+ # into CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules or
572
+ # .windsurfrules is listed by:
573
+ # npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks
574
+ #
575
+ # Re-running this script is safe \u2014 an existing reminder file is left as it is.
560
576
 
561
577
  set -e
562
578
 
563
- read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
579
+ read -r -d '' MAIND_BLOCK <<'MAIND_HINT_EOF' || true
564
580
 
565
581
  ${bt}
566
- MAIND_PREAMBLE_EOF
582
+ MAIND_HINT_EOF
567
583
 
568
- mkdir -p .github
569
-
570
- for f in CLAUDE.md AGENTS.md .github/copilot-instructions.md .cursorrules .windsurfrules; do
571
- if [ -f "$f" ] && grep -q "## maind MCP integration" "$f"; then
572
- echo "SKIP $f \u2014 maind section already present (may be legacy soft variant \u2014 consider upgrading manually to the hardened block)"
573
- else
574
- printf '%s\\n' "$MAIND_BLOCK" >> "$f"
575
- echo "WROTE $f"
576
- fi
577
- done
578
-
579
- # Reminder-File schreibt denselben Block (Single-Source-of-Truth: vier
580
- # Preamble-Files + Reminder-File haben byte-identischen Inhalt).
581
584
  REMINDER_FILE="$HOME/.claude/maind-session-start-reminder.md"
582
585
  if [ -e "$REMINDER_FILE" ]; then
583
586
  echo "SKIP $REMINDER_FILE \u2014 already exists (delete and re-run to refresh)"
@@ -588,12 +591,10 @@ else
588
591
  fi
589
592
 
590
593
  echo ""
591
- echo "Done. Agents will auto-load the five preamble files at session start."
592
- echo ""
593
- echo "Optional next step \u2014 install the SessionStart-Hook for Claude Code users:"
594
+ echo "Next step \u2014 install the SessionStart hook for Claude Code:"
594
595
  echo " Merge this snippet into ~/.claude/settings.json (or settings.local.json):"
595
596
  echo ""
596
- echo ' { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${$w}", "timeout": 5 } ] } ] } }'
597
+ echo ' { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${Lw}", "timeout": 5 } ] } ] } }'
597
598
  echo ""
598
599
  echo " \u2022 The hook runs the bridge subcommand on-session-reminder (bridge 0.94.0 or later)"
599
600
  echo " \u2022 An entry that still runs 'cat ~/.claude/maind-session-start-reminder.md' is the"
@@ -602,8 +603,10 @@ echo " \u2022 If 'hooks' object already exists: add only the SessionStart entry
602
603
  echo " \u2022 If 'hooks.SessionStart' array exists: append a new entry to it"
603
604
  echo " \u2022 Do NOT just cat-append \u2014 naive append breaks JSON syntax"
604
605
  echo ""
605
- echo "Drift-note: if you edit one of the five preamble files later, paste the"
606
- echo "same edit into the others to keep the agent's view consistent."`},{id:"cursor",label:"Cursor",description:"Browser-pairing Cursor 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:"~/.cursor/mcp.json",lang:"json",template:`{
606
+ echo "Every session channel at once \u2014 the conventions briefing for Claude Code,"
607
+ echo "hooks for Cursor and Codex, rule files for GitHub Copilot, Cline and"
608
+ echo "Continue \u2014 one consent each, nothing in the repository:"
609
+ echo " npx -y @maind-dev/mcp-bridge install --hooks-only"`},{id:"cursor",label:"Cursor",description:"Browser-pairing Cursor 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:"~/.cursor/mcp.json",lang:"json",template:`{
607
610
  "mcpServers": {
608
611
  "maind": {
609
612
  "command": "npx",
@@ -669,7 +672,7 @@ const tools = await mcp.getTools();
669
672
  "env": {
670
673
  "MAIND_MCP_URL": "${t}"
671
674
  }
672
- }`}]}var DP,PP,Hu,MP,BX,$w,bt,KX,ba=w(()=>{"use strict";DP="__STACK__",PP="__INTENT__",Hu="https://mcp.maind.dev/mcp",MP=`?stack=${DP}&intent=${PP}`;s($P,"buildStackAwareEndpoint");BX=$P(Hu,{stack:["nextjs","supabase"],intent:"mixed"}),$w="npx -y @maind-dev/mcp-bridge on-session-reminder",bt=`## maind MCP integration \u2014 Mandatory consultation
675
+ }`}]}var MP,$P,Hu,LP,GX,Lw,bt,WX,wa=w(()=>{"use strict";MP="__STACK__",$P="__INTENT__",Hu="https://mcp.maind.dev/mcp",LP=`?stack=${MP}&intent=${$P}`;s(FP,"buildStackAwareEndpoint");GX=FP(Hu,{stack:["nextjs","supabase"],intent:"mixed"}),Lw="npx -y @maind-dev/mcp-bridge on-session-reminder",bt=`## maind MCP integration \u2014 Mandatory consultation
673
676
 
674
677
  This project uses the maind MCP server (mcp.maind.dev/mcp) as
675
678
  authoritative source for vetted coding conventions and lessons. The
@@ -738,35 +741,35 @@ For non-trivial changes, resolve documentation path in this order:
738
741
  If no path is discoverable, provide a guided fallback:
739
742
  \`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
740
743
 
741
- Full tool set + provenance via \`get_conventions\`.`;s(LP,"buildAiPromptBody");s(Qn,"buildJsonConfigInstaller");s(FP,"buildCodexTomlInstaller");s(jP,"buildSnippetTemplates");KX=jP(Hu)});function UP(e){return`${ka}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 BP(e){return`${ka}always-on policies for everyone working in this repository, served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on session start, do not edit by hand.`}function xa(e,t,n={}){let r=(e??"").replace(/\r\n/g,`
742
- `).trim(),o=r.length===0?Lw:Bu(r,Uu).text,i=n.team===!0?[HP,BP(t)]:[UP(t)];return[wa,...i,o,va].join(`
744
+ Full tool set + provenance via \`get_conventions\`.`;s(jP,"buildAiPromptBody");s(Qn,"buildJsonConfigInstaller");s(HP,"buildCodexTomlInstaller");s(UP,"buildSnippetTemplates");WX=UP(Hu)});function KP(e){return`${xa}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 GP(e){return`${xa}always-on policies for everyone working in this repository, served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on session start, do not edit by hand.`}function Sa(e,t,n={}){let r=(e??"").replace(/\r\n/g,`
745
+ `).trim(),o=r.length===0?Fw:Bu(r,Uu).text,i=n.team===!0?[BP,GP(t)]:[KP(t)];return[va,...i,o,ka].join(`
743
746
  `)}function Bu(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
744
747
  `),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"),o=[],i=0;for(let a=0;a<n.length;a++){let c=(o.length===0?0:1)+n[a].length,l=a+1<n.length?1+r(a+1).length:0;if(i+c+l>t){if(o.length===0){let u=r(1);o.push(n[0].slice(0,Math.max(0,t-u.length-1)))}let d=r(o.length);return{text:[...o,d].join(`
745
748
  `),dropped:n.length-o.length}}o.push(n[a]),i+=c}return{text:o.join(`
746
- `),dropped:0}}function Fw(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Ku(e){let t=e.findIndex(o=>o.trim()===wa);if(t<0)return{kind:"none"};let n=e.findIndex((o,i)=>i>t&&o.trim()===va);if(n<0)return{kind:"damaged",begin:t};let r=e.slice(t+1,n).some(o=>o.trim().startsWith(hi));return{kind:"block",begin:t,end:n,team:r}}function jw(e){let t=Ku(e.split(/\r?\n/));return t.kind==="block"&&t.team}function Hw(e){let t=e.split(/\r?\n/),n=Ku(t);if(n.kind!=="block")return null;let o=t.slice(n.begin+1,n.end).filter(i=>!i.trim().startsWith(hi)&&!i.startsWith(ka)).join(`
747
- `).trim();return o.length===0||o===Lw?null:o}function Sa(e,t,n=er,r={}){let o=e.includes(`\r
749
+ `),dropped:0}}function jw(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Ku(e){let t=e.findIndex(o=>o.trim()===va);if(t<0)return{kind:"none"};let n=e.findIndex((o,i)=>i>t&&o.trim()===ka);if(n<0)return{kind:"damaged",begin:t};let r=e.slice(t+1,n).some(o=>o.trim().startsWith(hi));return{kind:"block",begin:t,end:n,team:r}}function Hw(e){let t=Ku(e.split(/\r?\n/));return t.kind==="block"&&t.team}function Uw(e){let t=e.split(/\r?\n/),n=Ku(t);if(n.kind!=="block")return null;let o=t.slice(n.begin+1,n.end).filter(i=>!i.trim().startsWith(hi)&&!i.startsWith(xa)).join(`
750
+ `).trim();return o.length===0||o===Fw?null:o}function Ea(e,t,n=er,r={}){let o=e.includes(`\r
748
751
  `)?`\r
749
752
  `:`
750
753
  `,i=e.split(o),a=t.split(`
751
- `),c=Ku(i);if(c.kind==="damaged")return{next:e,changed:!1,outcome:"damaged"};if(c.kind==="block"){let y=i.slice(c.begin,c.end+1);if(GP(y,a))return{next:e,changed:!1,outcome:"unchanged"};let _=[...i.slice(0,c.begin),...a,...i.slice(c.end+1)].join(o);return{next:_,changed:_!==e,outcome:"replaced"}}if(r.replaceOnly===!0)return{next:e,changed:!1,outcome:"no-header"};let l=i.findIndex(y=>y.startsWith(n));if(l<0)return r.appendWhenNoHeader!==!0?{next:e,changed:!1,outcome:"no-header"}:{next:KP(e,i,a,o),changed:!0,outcome:"inserted"};let d=i.length,u=!1;for(let y=l+1;y<i.length;y++){if(/^\s{0,3}(```|~~~)/.test(i[y])){u=!u;continue}if(!u&&/^#{1,2}\s/.test(i[y])){d=y;break}}let p=d-1;for(;p>l&&i[p].trim()==="";)p--;let f=i.slice(0,p+1),h=i.slice(p+1),g=[...f,"",...a];return d===i.length?g.push(...h.length===0?[""]:h):((h.length===0||h[0].trim()!=="")&&g.push(""),g.push(...h)),{next:g.join(o),changed:!0,outcome:"inserted"}}function KP(e,t,n,r){if(e.trim().length===0)return n.join(r)+r;let o=e;o.endsWith(r)||(o+=r);let i=t.length>=2&&t[t.length-1]===""&&t[t.length-2].trim()==="";return o+(i?"":r)+n.join(r)+r}function GP(e,t){let n=s(i=>i.map(a=>a.replace(/\r$/,"")).filter(a=>!a.startsWith(ka)),"strip"),r=n(e),o=n(t);return r.length===o.length&&r.every((i,a)=>i===o[a])}var wa,va,hi,HP,er,Uu,Lw,ka,Zr=w(()=>{"use strict";wa="<!-- maind:conventions v1 begin -->",va="<!-- maind:conventions v1 end -->",hi="<!-- maind:conventions scope=team",HP=`${hi} \xB7 chosen with \`maind-mcp-bridge install --team\`: this block travels with the repository -->`,er="## maind MCP integration",Uu=6e3,Lw="(No conventions loaded yet \u2014 the bridge fills this block on the next session start in this repository.)",ka="Project conventions \u2014 ";s(UP,"renderConventionsLead");s(BP,"renderTeamLead");s(xa,"renderConventionsBlock");s(Bu,"capAtLineBoundary");s(Fw,"countConventions");s(Ku,"locateConventionsBlock");s(jw,"hasTeamBlock");s(Hw,"blockConventionsText");s(Sa,"upsertConventionsBlock");s(KP,"appendBlock");s(GP,"sameConventions")});import{existsSync as WP}from"node:fs";import*as Uw from"node:path";function Oe(e,t={},n=je){let r=t.fileExists??WP,o=t.expectedCommand??zP,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Gu(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=JP(i,a.event,a.subcommand),d=l===null&&a.supersedes?YP(i,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: ${o(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: ${o(a.subcommand)}`;if(la(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(rn(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=XP(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 Wu(e){return e.some(t=>t.status!=="ok")}function Ea(e){return e.some(t=>t.remedy==="run-install")}function zP(e){return ze(we({entryPath:oe(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function JP(e,t,n){return Bw(e,t,r=>r.includes(n))}function YP(e,t,n){return Bw(e,t,r=>n.test(r))}function Bw(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!Gu(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!Gu(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function XP(e){for(let t of ZP(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Uw.isAbsolute(t)?t:null;return null}function ZP(e){let t=[],n="",r=!1;for(let o of e){if(o==="'"){r=!r;continue}if(!r&&/\s/.test(o)){n.length>0&&t.push(n),n="";continue}n+=o}return n.length>0&&t.push(n),t}function Gu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var J,gi,$t,VP,qP,je,Qr,ve=w(()=>{"use strict";_t();J="on-session-briefing",gi=".claude/maind-session-start-reminder.md",$t="on-session-reminder",VP=/maind-session-start-reminder\.md/,qP=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,je=[{event:"SessionStart",subcommand:$t,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:VP,replaceable:qP},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:J,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. It also passes on, once per issue, open issues assigned to you that this machine's bridge already received from the MAIND server (read from the local presence snapshot under ~/.maind/presence; remembered under ~/.maind/assigned-told/) \u2014 no network call here either."},{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. It reads the target file PATH (never the file's contents) to find which repository you are editing, then \u2014 at most ONCE per session and repository, not on every call \u2014 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? It notes in ~/.maind/state.json that it checked, plus two counters (runs, findings) that the Stop hook later sends with your Tier-3 session metrics \u2014 numbers only, never paths. Only if you allow the checkout memory (a separate install question, off until you answer it) does it also note the repository's ROOT directory and project key in ~/.maind/checkout-roots.json, so a worktree deleted before the session ends keeps its cost attribution; that file never leaves this machine. The hook itself makes 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' at the end of every turn and returns at once: it closes the turn's counters in ~/.maind/state.json and hands the rest to a detached background run, so the session never waits on the network. That run reads the session's TRANSCRIPT on this machine (sub-agent transcripts included) and derives communication analytics (momentum, reactions, time shape) and the session's token spend per model. For the spend it fetches the attribution context from mcp.maind.dev \u2014 sending your API key, device id, the project key and the coordination session ids the session used \u2014 and matches the edited file PATHS against it locally. It uploads the analytics and the cost slices (object ids and token sums \u2014 never paths, never transcript text), gated by your Tier-3 consent server-side, then flushes the queued Tier-3 counters. Locally it keeps a job queue, a lock and a run log (session id, timings, outcome \u2014 no content) under ~/.maind/session-end/, and \u2014 only if you allow the checkout memory, a separate install question \u2014 the ROOT directories of the repositories you edited in ~/.maind/checkout-roots.json. Those files never leave the machine."},{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."}],Qr=[{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(Oe,"inspectHookWiring");s(Wu,"hasWiringDrift");s(Ea,"needsInstallRun");s(zP,"defaultExpectedCommand");s(JP,"findCommand");s(YP,"findCommandMatching");s(Bw,"findFirstCommand");s(XP,"extractScriptPath");s(ZP,"tokenize");s(Gu,"isObject")});import*as Kw from"node:path";async function Vu(e,t){let n=Kw.join(e,gi);try{if(await Ew(n,er))return{target:Ra,action:"skip",status:"skipped",detail:`${er} header already present`};let r=await q(n);if(t)return{target:Ra,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:n};let o=r===null||r.length===0?`${bt}
752
- `:QP(r)+`${bt}
753
- `;return await U(n,o),{target:Ra,action:r===null?"write":"append",status:r===null?"created":"merged",detail:n}}catch(r){return{target:Ra,action:"write",status:"failed",detail:r instanceof Error?r.message:String(r)}}}function QP(e){return e.endsWith(`
754
+ `),c=Ku(i);if(c.kind==="damaged")return{next:e,changed:!1,outcome:"damaged"};if(c.kind==="block"){let y=i.slice(c.begin,c.end+1);if(VP(y,a))return{next:e,changed:!1,outcome:"unchanged"};let _=[...i.slice(0,c.begin),...a,...i.slice(c.end+1)].join(o);return{next:_,changed:_!==e,outcome:"replaced"}}if(r.replaceOnly===!0)return{next:e,changed:!1,outcome:"no-header"};let l=i.findIndex(y=>y.startsWith(n));if(l<0)return r.appendWhenNoHeader!==!0?{next:e,changed:!1,outcome:"no-header"}:{next:WP(e,i,a,o),changed:!0,outcome:"inserted"};let d=i.length,u=!1;for(let y=l+1;y<i.length;y++){if(/^\s{0,3}(```|~~~)/.test(i[y])){u=!u;continue}if(!u&&/^#{1,2}\s/.test(i[y])){d=y;break}}let p=d-1;for(;p>l&&i[p].trim()==="";)p--;let f=i.slice(0,p+1),h=i.slice(p+1),g=[...f,"",...a];return d===i.length?g.push(...h.length===0?[""]:h):((h.length===0||h[0].trim()!=="")&&g.push(""),g.push(...h)),{next:g.join(o),changed:!0,outcome:"inserted"}}function WP(e,t,n,r){if(e.trim().length===0)return n.join(r)+r;let o=e;o.endsWith(r)||(o+=r);let i=t.length>=2&&t[t.length-1]===""&&t[t.length-2].trim()==="";return o+(i?"":r)+n.join(r)+r}function VP(e,t){let n=s(i=>i.map(a=>a.replace(/\r$/,"")).filter(a=>!a.startsWith(xa)),"strip"),r=n(e),o=n(t);return r.length===o.length&&r.every((i,a)=>i===o[a])}var va,ka,hi,BP,er,Uu,Fw,xa,Zr=w(()=>{"use strict";va="<!-- maind:conventions v1 begin -->",ka="<!-- maind:conventions v1 end -->",hi="<!-- maind:conventions scope=team",BP=`${hi} \xB7 chosen with \`maind-mcp-bridge install --team\`: this block travels with the repository -->`,er="## maind MCP integration",Uu=6e3,Fw="(No conventions loaded yet \u2014 the bridge fills this block on the next session start in this repository.)",xa="Project conventions \u2014 ";s(KP,"renderConventionsLead");s(GP,"renderTeamLead");s(Sa,"renderConventionsBlock");s(Bu,"capAtLineBoundary");s(jw,"countConventions");s(Ku,"locateConventionsBlock");s(Hw,"hasTeamBlock");s(Uw,"blockConventionsText");s(Ea,"upsertConventionsBlock");s(WP,"appendBlock");s(VP,"sameConventions")});import{existsSync as qP}from"node:fs";import*as Bw from"node:path";function Oe(e,t={},n=je){let r=t.fileExists??qP,o=t.expectedCommand??YP,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Gu(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=XP(i,a.event,a.subcommand),d=l===null&&a.supersedes?ZP(i,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: ${o(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: ${o(a.subcommand)}`;if(da(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(rn(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=QP(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 Wu(e){return e.some(t=>t.status!=="ok")}function Ra(e){return e.some(t=>t.remedy==="run-install")}function YP(e){return ze(we({entryPath:oe(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function XP(e,t,n){return Kw(e,t,r=>r.includes(n))}function ZP(e,t,n){return Kw(e,t,r=>n.test(r))}function Kw(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!Gu(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!Gu(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function QP(e){for(let t of eM(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Bw.isAbsolute(t)?t:null;return null}function eM(e){let t=[],n="",r=!1;for(let o of e){if(o==="'"){r=!r;continue}if(!r&&/\s/.test(o)){n.length>0&&t.push(n),n="";continue}n+=o}return n.length>0&&t.push(n),t}function Gu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var J,gi,Lt,zP,JP,je,Qr,ve=w(()=>{"use strict";_t();J="on-session-briefing",gi=".claude/maind-session-start-reminder.md",Lt="on-session-reminder",zP=/maind-session-start-reminder\.md/,JP=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,je=[{event:"SessionStart",subcommand:Lt,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:zP,replaceable:JP},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:J,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. It also passes on, once per issue, open issues assigned to you that this machine's bridge already received from the MAIND server (read from the local presence snapshot under ~/.maind/presence; remembered under ~/.maind/assigned-told/) \u2014 no network call here either."},{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. It reads the target file PATH (never the file's contents) to find which repository you are editing, then \u2014 at most ONCE per session and repository, not on every call \u2014 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? It notes in ~/.maind/state.json that it checked, plus two counters (runs, findings) that the Stop hook later sends with your Tier-3 session metrics \u2014 numbers only, never paths. Only if you allow the checkout memory (a separate install question, off until you answer it) does it also note the repository's ROOT directory and project key in ~/.maind/checkout-roots.json, so a worktree deleted before the session ends keeps its cost attribution; that file never leaves this machine. The hook itself makes 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' at the end of every turn and returns at once: it closes the turn's counters in ~/.maind/state.json and hands the rest to a detached background run, so the session never waits on the network. That run reads the session's TRANSCRIPT on this machine (sub-agent transcripts included) and derives communication analytics (momentum, reactions, time shape) and the session's token spend per model. For the spend it fetches the attribution context from mcp.maind.dev \u2014 sending your API key, device id, the project key and the coordination session ids the session used \u2014 and matches the edited file PATHS against it locally. It uploads the analytics and the cost slices (object ids and token sums \u2014 never paths, never transcript text), gated by your Tier-3 consent server-side, then flushes the queued Tier-3 counters. Locally it keeps a job queue, a lock and a run log (session id, timings, outcome \u2014 no content) under ~/.maind/session-end/, and \u2014 only if you allow the checkout memory, a separate install question \u2014 the ROOT directories of the repositories you edited in ~/.maind/checkout-roots.json. Those files never leave the machine."},{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."}],Qr=[{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(Oe,"inspectHookWiring");s(Wu,"hasWiringDrift");s(Ra,"needsInstallRun");s(YP,"defaultExpectedCommand");s(XP,"findCommand");s(ZP,"findCommandMatching");s(Kw,"findFirstCommand");s(QP,"extractScriptPath");s(eM,"tokenize");s(Gu,"isObject")});import*as Gw from"node:path";async function Vu(e,t){let n=Gw.join(e,gi);try{if(await Rw(n,er))return{target:Ca,action:"skip",status:"skipped",detail:`${er} header already present`};let r=await q(n);if(t)return{target:Ca,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:n};let o=r===null||r.length===0?`${bt}
755
+ `:tM(r)+`${bt}
756
+ `;return await U(n,o),{target:Ca,action:r===null?"write":"append",status:r===null?"created":"merged",detail:n}}catch(r){return{target:Ca,action:"write",status:"failed",detail:r instanceof Error?r.message:String(r)}}}function tM(e){return e.endsWith(`
754
757
 
755
758
  `)?e:e.endsWith(`
756
759
  `)?e+`
757
760
  `:e+`
758
761
 
759
- `}var Ra,Gw=w(()=>{"use strict";ba();Zr();ie();ve();Ra="reminder:~/.claude/maind-session-start-reminder.md";s(Vu,"writeReminderFile");s(QP,"ensureTrailingBlankLine")});import*as Ww from"node:path";async function Vw(e){let t=Ww.join(e.projectRoot,"AGENTS.md"),n=s((r,o,i="upsert")=>({target:eM,action:i,status:r,detail:o}),"row");try{let r=await q(t),o=await e.conventions()??(r!==null?Hw(r):null),i=xa(o,{date:new Date(e.nowMs??Date.now()).toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??H},{team:!0}),a=o===null||o.trim().length===0?" (no conventions yet \u2014 filled on the next session start)":"";if(r===null)return e.dryRun?n("would-create",`${t}${a}`,"write"):(await U(t,i+`
760
- `),n("created",`${t}${a}`,"write"));let c=Sa(r,i,void 0,{appendWhenNoHeader:!0});switch(c.outcome){case"unchanged":return n("skipped","team block already up to date","skip");case"damaged":return n("failed",`begin marker without end marker in ${t} \u2014 remove the <!-- maind:conventions --> lines, then run install --team again`);case"no-header":return n("failed",`no place for the block in ${t}`);case"inserted":case"replaced":{let l=c.outcome==="inserted"?"inserted":"replaced";return e.dryRun?n("would-merge",`${t} (would be ${l})${a}`):(await U(t,c.next),n("merged",`${t} (${l})${a}`))}}}catch(r){return n("failed",r instanceof Error?r.message:String(r))}}var eM,qw=w(()=>{"use strict";Fe();Zr();ie();eM="team:AGENTS.md#conventions";s(Vw,"writeTeamConventionsBlock")});import{existsSync as tM,readFileSync as nM}from"node:fs";import{join as rM}from"node:path";function He(){return rM(it(),"config.json")}function Q(){try{let e=He();if(!tM(e))return null;let t=JSON.parse(nM(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(o=>typeof o=="string")),typeof n.devin_hook_output=="boolean"&&(r.devin_hook_output=n.devin_hook_output),typeof n.checkout_memory=="boolean"&&(r.checkout_memory=n.checkout_memory),r}catch{return null}}var Ue=w(()=>{"use strict";re();s(He,"bridgeConfigPath");s(Q,"readBridgeConfig")});function oM(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===qu?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 o=[...r].sort();return o.length===e.length&&o.every(a=>e.includes(a))?null:o}async function zw(e,t,n=He()){try{let r={},o=await q(n);if(o!==null&&o.trim().length>0){let l=JSON.parse(o);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let i=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=oM(i,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await U(n,JSON.stringify(c,null,2)+`
761
- `,384)}catch{}}var qu,zu=w(()=>{"use strict";Ue();ie();qu="user declined";s(oM,"nextDeclinedHooks");s(zw,"recordHookDecisions")});import*as Jw from"node:path";import*as Yw from"node:readline";async function iM(e,t){let n=Jw.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let o;try{o=await q(n)}catch(g){return{target:r,action:"merge",status:"failed",detail:`read: ${Ju(g)}`}}let i,a="create";if(o===null||o.trim().length===0)i={};else{a="merge";try{let g=JSON.parse(o);if(!yi(g))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};i=g}catch(g){return{target:r,action:"merge",status:"failed",detail:`parse: ${Ju(g)}`}}}let c=cM(i,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};let l=t.supersedes?aM(i,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?`
762
+ `}var Ca,Ww=w(()=>{"use strict";wa();Zr();ie();ve();Ca="reminder:~/.claude/maind-session-start-reminder.md";s(Vu,"writeReminderFile");s(tM,"ensureTrailingBlankLine")});import*as Vw from"node:path";async function qw(e){let t=Vw.join(e.projectRoot,"AGENTS.md"),n=s((r,o,i="upsert")=>({target:nM,action:i,status:r,detail:o}),"row");try{let r=await q(t),o=await e.conventions()??(r!==null?Uw(r):null),i=Sa(o,{date:new Date(e.nowMs??Date.now()).toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??H},{team:!0}),a=o===null||o.trim().length===0?" (no conventions yet \u2014 filled on the next session start)":"";if(r===null)return e.dryRun?n("would-create",`${t}${a}`,"write"):(await U(t,i+`
763
+ `),n("created",`${t}${a}`,"write"));let c=Ea(r,i,void 0,{appendWhenNoHeader:!0});switch(c.outcome){case"unchanged":return n("skipped","team block already up to date","skip");case"damaged":return n("failed",`begin marker without end marker in ${t} \u2014 remove the <!-- maind:conventions --> lines, then run install --team again`);case"no-header":return n("failed",`no place for the block in ${t}`);case"inserted":case"replaced":{let l=c.outcome==="inserted"?"inserted":"replaced";return e.dryRun?n("would-merge",`${t} (would be ${l})${a}`):(await U(t,c.next),n("merged",`${t} (${l})${a}`))}}}catch(r){return n("failed",r instanceof Error?r.message:String(r))}}var nM,zw=w(()=>{"use strict";Fe();Zr();ie();nM="team:AGENTS.md#conventions";s(qw,"writeTeamConventionsBlock")});import{existsSync as rM,readFileSync as oM}from"node:fs";import{join as iM}from"node:path";function He(){return iM(it(),"config.json")}function Q(){try{let e=He();if(!rM(e))return null;let t=JSON.parse(oM(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(o=>typeof o=="string")),typeof n.devin_hook_output=="boolean"&&(r.devin_hook_output=n.devin_hook_output),typeof n.checkout_memory=="boolean"&&(r.checkout_memory=n.checkout_memory),r}catch{return null}}var Ue=w(()=>{"use strict";re();s(He,"bridgeConfigPath");s(Q,"readBridgeConfig")});function sM(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===qu?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 o=[...r].sort();return o.length===e.length&&o.every(a=>e.includes(a))?null:o}async function Jw(e,t,n=He()){try{let r={},o=await q(n);if(o!==null&&o.trim().length>0){let l=JSON.parse(o);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let i=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=sM(i,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await U(n,JSON.stringify(c,null,2)+`
764
+ `,384)}catch{}}var qu,zu=w(()=>{"use strict";Ue();ie();qu="user declined";s(sM,"nextDeclinedHooks");s(Jw,"recordHookDecisions")});import*as Yw from"node:path";import*as Xw from"node:readline";async function aM(e,t){let n=Yw.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let o;try{o=await q(n)}catch(g){return{target:r,action:"merge",status:"failed",detail:`read: ${Ju(g)}`}}let i,a="create";if(o===null||o.trim().length===0)i={};else{a="merge";try{let g=JSON.parse(o);if(!yi(g))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};i=g}catch(g){return{target:r,action:"merge",status:"failed",detail:`parse: ${Ju(g)}`}}}let c=dM(i,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};let l=t.supersedes?lM(i,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?`
762
765
  Replace the ${t.event} hook \`${l.command}\` in ${n}?
763
766
  ${t.consentDescription}
764
767
  [Y/n]: `:`
765
768
  Merge a ${t.event} hook into ${n}?
766
769
  ${t.consentDescription}
767
- [Y/n]: `;if(!await(e.prompt??lM)(e.out,g))return{target:r,action:"skip",status:"skipped",detail:qu}}let d=i.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={...i,hooks:{...i.hooks??{},[t.event]:u}},f=JSON.stringify(p,null,2)+`
768
- `,h=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 U(n,f,384)}catch(g){return{target:r,action:"merge",status:"failed",detail:`write: ${Ju(g)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n+h}}function sM(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function _i(e,t){let n=e.launch??we({entryPath:oe(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=ze(n);return iM(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:sM(t),supersedes:t.supersedes,skipDetail:s(o=>{let i=`${t.label} already runs maind ${t.subcommand}`;return la(o)?`${i}, 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}`:rn(o)?`${i}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:i},"skipDetail"),consentDescription:t.consentDescription})}async function Xw(e){let t=[];for(let n of je)t.push(await _i(e,n));return t}function aM(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o=0;o<r.length;o++){let i=r[o];if(!yi(i))continue;let a=i.hooks;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=a[c];if(!yi(l))continue;let d=l.command;if(typeof d=="string"&&n.test(d))return{group:o,hook:c,command:d}}}return null}function cM(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!yi(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!yi(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function lM(e,t){e.write(t);let n=Yw.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ju(e){return e instanceof Error?e.message:String(e)}var Ca=w(()=>{"use strict";ie();_t();ve();zu();ve();s(iM,"mergeClaudeHook");s(sM,"targetKeyFor");s(_i,"mergeSubcommandHook");s(Xw,"mergeAllSubcommandHooks");s(aM,"findHookEntry");s(cM,"findExistingHookCommand");s(lM,"promptYesNo");s(yi,"isObject");s(Ju,"errMessage")});import*as Zw from"node:readline";async function Qw(e){let t=e.configPath??He(),n={};try{let a=await q(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:tr,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:tr,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??uM)(e.out,dM)}else return{target:tr,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:tr,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 o={...n,auto_working_paths:!0},i=JSON.stringify(o,null,2)+`
769
- `;if(e.dryRun)return{target:tr,action:"merge",status:"would-merge",detail:t};try{await U(t,i,384)}catch(a){return{target:tr,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:tr,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}async function uM(e,t){e.write(t);let n=Zw.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}var tr,dM,ev=w(()=>{"use strict";Ue();ie();tr="config:auto_working_paths",dM=`
770
+ [Y/n]: `;if(!await(e.prompt??uM)(e.out,g))return{target:r,action:"skip",status:"skipped",detail:qu}}let d=i.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={...i,hooks:{...i.hooks??{},[t.event]:u}},f=JSON.stringify(p,null,2)+`
771
+ `,h=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 U(n,f,384)}catch(g){return{target:r,action:"merge",status:"failed",detail:`write: ${Ju(g)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n+h}}function cM(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function _i(e,t){let n=e.launch??we({entryPath:oe(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=ze(n);return aM(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:cM(t),supersedes:t.supersedes,skipDetail:s(o=>{let i=`${t.label} already runs maind ${t.subcommand}`;return da(o)?`${i}, 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}`:rn(o)?`${i}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:i},"skipDetail"),consentDescription:t.consentDescription})}async function Zw(e){let t=[];for(let n of je)t.push(await _i(e,n));return t}function lM(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o=0;o<r.length;o++){let i=r[o];if(!yi(i))continue;let a=i.hooks;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=a[c];if(!yi(l))continue;let d=l.command;if(typeof d=="string"&&n.test(d))return{group:o,hook:c,command:d}}}return null}function dM(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!yi(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!yi(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function uM(e,t){e.write(t);let n=Xw.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ju(e){return e instanceof Error?e.message:String(e)}var Ta=w(()=>{"use strict";ie();_t();ve();zu();ve();s(aM,"mergeClaudeHook");s(cM,"targetKeyFor");s(_i,"mergeSubcommandHook");s(Zw,"mergeAllSubcommandHooks");s(lM,"findHookEntry");s(dM,"findExistingHookCommand");s(uM,"promptYesNo");s(yi,"isObject");s(Ju,"errMessage")});import*as Qw from"node:readline";async function ev(e){let t=e.configPath??He(),n={};try{let a=await q(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:tr,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:tr,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??fM)(e.out,pM)}else return{target:tr,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:tr,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 o={...n,auto_working_paths:!0},i=JSON.stringify(o,null,2)+`
772
+ `;if(e.dryRun)return{target:tr,action:"merge",status:"would-merge",detail:t};try{await U(t,i,384)}catch(a){return{target:tr,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:tr,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}async function fM(e,t){e.write(t);let n=Qw.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}var tr,pM,tv=w(()=>{"use strict";Ue();ie();tr="config:auto_working_paths",pM=`
770
773
  Enable presence enrichment (auto working_paths)?
771
774
  With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
772
775
  locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
@@ -775,12 +778,12 @@ before editing the same area. Directory names only: never file contents, never
775
778
  absolute paths. Server-side these paths are account-private (org members never
776
779
  see them) and revocable any time on the dashboard consent page or via
777
780
  {"auto_working_paths": false} in the bridge config.
778
- [y/N]: `;s(Qw,"applyWorkingPathsConsent");s(uM,"promptYesNoDefaultNo")});function Yu(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Xu=w(()=>{"use strict";s(Yu,"newModeState")});import{createReadStream as pM,existsSync as fM}from"node:fs";import{stat as mM}from"node:fs/promises";import{createInterface as hM}from"node:readline";async function Zu(e){if(!e||!fM(e))return null;let t;try{t=await mM(e)}catch{return null}let n=new Set,r=0,o=0,i=0;return await new Promise(a=>{let c=pM(e,{encoding:"utf-8"}),l=hM({input:c});l.on("line",d=>{let u=d.trim();if(u){i++;try{let p=JSON.parse(u),f=p.message?.usage;if(!f)return;let h=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=h??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(o+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:o,total_tokens:r+o,lines_seen:i,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var tv=w(()=>{"use strict";s(Zu,"summariseTranscript")});var nv=w(()=>{"use strict"});function bi(e){if(!e)return null;let t=null;for(let n of e.matchAll(yM)){let r=n[1].toLowerCase();gM.has(r)&&(t=r)}return t}var gM,yM,Ta=w(()=>{"use strict";gM=new Set(["low","medium","high","xhigh","max"]),yM=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(bi,"detectEffortLevel")});function eo(e){for(let t of rv)if(e.startsWith(t)){let n=e.slice(t.length);return n.length>0?n:null}return null}var rv,Aa=w(()=>{"use strict";rv=["mcp__maind__","mcp__plugin_maind_maind__"];s(eo,"maindToolName")});import{createReadStream as _M,existsSync as bM,readdirSync as wM}from"node:fs";import{basename as sv,dirname as vM,join as ov}from"node:path";import{createInterface as kM}from"node:readline";function cv(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!EM.test(n)||e.ids.includes(n)||e.ids.length>=av||e.ids.push(n)}function RM(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")continue;let o=eo(r.name);if(o===null||SM.has(o))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?cv(e,i.session_id):o==="announce_session"&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function CM(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 TM(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 o=CM(r.content),i=null;try{let a=JSON.parse(o);a&&a.ok===!0&&(i=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(o);i=a?a[1]:null}cv(e,i)}}function to(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function IM(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 o=AM[r.name];if(!o||!r.input||typeof r.input!="object")continue;let i=r.input[o];typeof i=="string"&&i.length>0&&t.push(i)}return t}function Ia(e){let t=sv(e).replace(/\.jsonl$/,""),n=ov(vM(e),t,"subagents"),r;try{r=wM(n)}catch{return[]}return r.filter(o=>o.endsWith(".jsonl")).sort().map(o=>ov(n,o))}async function iv(e,t,n,r,o,i){bM(e)&&await new Promise(a=>{let c=_M(e,{encoding:"utf-8"}),l=kM({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"){TM(i,f.message.content);return}if(f.message?.role!=="assistant")return;RM(i,f.message.content);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??`${e}#${d}`,_=IM(f.message.content),b=r.get(y);if(b){for(let R of _)b.edited_paths.includes(R)||b.edited_paths.push(R);return}if(n.has(y))return;n.add(y);let v=f.message.usage??{},k=typeof f.timestamp=="string"?Date.parse(f.timestamp):Number.NaN,E=typeof f.message.model=="string"&&f.message.model?f.message.model:"",S={ts:Number.isFinite(k)?k:0,model:E||"<unknown>",synthetic:E===xM,input_tokens:to(v.input_tokens),output_tokens:to(v.output_tokens),cache_read_tokens:to(v.cache_read_input_tokens),cache_creation_tokens:to(v.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(to(v.cache_creation?.ephemeral_1h_input_tokens),to(v.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,S),o.push(S)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function Qu(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 o=e[r];o.ts>0?n=o.ts:n>0&&(o.ts=n)}}async function wi(e){let t=new Set,n=new Map,r=[],o=e?Ia(e):[],i={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:o,coordination_ids:[]};let a=[];await iv(e,nr,t,n,a,i),Qu(a),r.push(...a);for(let c of o){let l=[],d=sv(c).replace(/\.jsonl$/,"");i.pendingAnnounce.clear(),await iv(c,d,t,n,l,i),Qu(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:o,coordination_ids:i.ids}}var nr,xM,SM,EM,av,AM,Na=w(()=>{"use strict";Aa();nr="main",xM="<synthetic>",SM=new Set(["get_session_analysis","get_session_cost_context"]),EM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,av=32;s(cv,"addCoordinationId");s(RM,"noteCoordinationUse");s(CM,"resultText");s(TM,"noteAnnounceResult");AM={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(to,"num");s(IM,"editedPathsOf");s(Ia,"subagentFilesOf");s(iv,"readStream");s(Qu,"fillTimestamps");s(wi,"collectTurns")});import{createReadStream as lv,existsSync as NM}from"node:fs";import{createInterface as dv}from"node:readline";function FM(e,t,n,r,o){let i=`${n?"s":"m"}:${t}`,a=e.get(i);if(!a){e.set(i,{model:t,turns:1,output_tokens:r,first_ts:o,last_ts:o,sidechain:n});return}a.turns++,a.output_tokens+=r,o>0&&((a.first_ts===0||o<a.first_ts)&&(a.first_ts=o),o>a.last_ts&&(a.last_ts=o))}function Oa(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function jM(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
779
- `)}function HM(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),o=n(t);if(r.size<3||o.size<3)return!1;let[i,a]=r.size<=o.size?[r,o]:[o,r],c=0;for(let l of i)a.has(l)&&c++;return c/i.size>=.8}function UM(e,t,n){return OM.test(e)?{polarity:-1,magnitude:no.rework,kind:"rework"}:n&&DM.test(e)?{polarity:-1,magnitude:no.correction,kind:"correction"}:PM.test(e)?{polarity:1,magnitude:no.acceptance,kind:"acceptance"}:t!==null&&HM(t,e)?{polarity:-1,magnitude:no.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function BM(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 KM(e,t){for(let n of Ia(e))await new Promise(r=>{let o=dv({input:lv(n,{encoding:"utf-8"})});o.on("line",i=>{let a=i.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of Oa(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string")continue;let d=eo(l.name);d!==null&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),o.on("error",()=>r()),o.on("close",()=>r())})}async function ep(e,t={}){let n=BM("");if(!e||!NM(e))return n;let r=t.turns??(await wi(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 o=[],i=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=lv(e,{encoding:"utf-8"}),y=dv({input:g}),_=s(b=>{let v=b.trim();if(!v)return;let k;try{k=JSON.parse(v)}catch{return}if(n.lines_seen++,!n.session_id){let D=k.sessionId??k.session_id;typeof D=="string"&&D&&(n.session_id=D)}k.type==="ai-title"&&typeof k.aiTitle=="string"&&k.aiTitle&&(n.ai_title=k.aiTitle),typeof k.slug=="string"&&k.slug&&(n.session_slug=k.slug);let E=k.message?.role,S=k.isSidechain===!0;if(E==="assistant")for(let D of Oa(k.message?.content)){if(D.type!=="tool_use"||typeof D.name!="string")continue;let F=eo(D.name);F!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[F]=(n.maind_tool_calls[F]??0)+1)}if(S)return;if(E==="assistant"){let D=Oa(k.message?.content),F=!1;for(let xt of D)xt.type==="tool_use"&&(n.tool_calls++,F=!0,xt.name==="AskUserQuestion"&&n.agent_questions++);c=F;return}if(E!=="user")return;let R=Oa(k.message?.content),P=jM(R);if(P.includes(MM)){n.interrupts++,o.push({polarity:-1,magnitude:no.interrupt,kind:"interrupt"});return}if(R.some(D=>D.type==="tool_result"&&D.is_error===!0&&typeof D.content=="string"&&D.content.includes($M))){n.tool_denials++,o.push({polarity:-1,magnitude:no.denial,kind:"denial"});return}if(R.some(D=>D.type==="tool_result")||!P.trim())return;n.user_turns++,n.user_chars+=P.length;let x=bi(P);x&&(a=x);let T=UM(P,l,c);l=P,T.kind==="correction"?n.corrections++:T.kind==="rework"?n.reworks++:T.kind==="repeat"?n.repeated_instructions++:T.kind==="acceptance"&&n.acceptances++,T.polarity!==0&&o.push(T),c=!1},"processLine");y.on("line",b=>{try{_(b)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await KM(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||FM(i,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...i.values()].sort((h,g)=>h.first_ts-g.first_ts||h.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return o.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*LM+h.polarity*h.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...h.kind!=="neutral"?{kind:h.kind}:{}}),p+=y,g>0&&o[g-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var uv,OM,DM,PM,MM,$M,LM,no,pv=w(()=>{"use strict";Ta();Aa();Na();uv="2026-10-01",OM=/(\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,DM=/(\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,PM=/(\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,MM="[Request interrupted by user",$M="The user doesn't want to proceed with this tool use",LM=.7,no={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(FM,"bumpModel");s(Oa,"asBlocks");s(jM,"textOf");s(HM,"isRepeat");s(UM,"classifyGenuine");s(BM,"emptyAnalysis");s(KM,"tallySubagentMaindCalls");s(ep,"analyzeSession")});function tp(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 np(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 rp(e,t,n,r="unknown",o){let i={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]}:{},...o?{cost_slices:o.slices,cost_context_ok:o.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...c}=n;i.session_span={...t,...c}}else i.session_span=t;return i}var fv=w(()=>{"use strict";s(tp,"parseIngestResponse");s(np,"describeSliceVerdict");s(rp,"ingestBody")});import{isAbsolute as mv,relative as GM,resolve as hv,sep as gv}from"node:path";function yv(e){return e>Pa[1]?"above_272k":e>Pa[0]?"band_200k_272k":"standard"}function _v(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Da(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function vi(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=Da(d.from);typeof d.object_id!="string"||!op.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:Da(d.to)})}return c},"windows"),o=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=Da(c.from);typeof c.path_prefix!="string"||l===null||o.push({path_prefix:c.path_prefix,from:l,to:Da(c.to)})}let i=[];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"||!op.test(c.object_id)||typeof c.path_prefix=="string"&&i.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&op.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:o,anchors:i}}function Ma(e,t){if(!mv(e))return null;let n=GM(hv(t),hv(e));return!n||n==="."||n.startsWith("..")||mv(n)?null:gv==="/"?n:n.split(gv).join("/")}function VM(e,t){return t===""||e===t||e.startsWith(t+"/")}function sp(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 ap(e,t){for(let n of bv(t))if(VM(e,n.path_prefix))return n.object_id;return null}function qM(e,t){for(let n of bv(t))if(sp(e,n.path_prefix))return n.object_id;return null}function ip(e,t){return e>=t.from&&(t.to===null||e<t.to)}function wv(e,t,n,r){let o=e.ts,i=r?.anchors??[],a=t.map(c=>ap(c,i)).filter(c=>c!==null);if(r&&o>0){let c=r.leases.filter(u=>ip(o,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=>ip(o,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=>ip(o,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>sp(f.path_prefix,u))).sort((f,h)=>h.path_prefix.length-f.path_prefix.length);for(let f of p){let h=qM(f.path_prefix,i);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 cp(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?_=>Ma(_,o):null),a=s(_=>{if(!i)return[];let b=[];for(let v of _.edited_paths){let k=i(v);k!==null&&!b.includes(k)&&b.push(k)}return b},"relOf"),c=s(_=>{for(let b of _){let v=ap(b,r);if(v)return{object_id:v,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])=>_===nr?-1:b===nr?1:0),u=[],p=s(_=>{let b=null;for(let v of u){if(v.ts>_&&_>0)break;b=v.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let v=b.map((E,S)=>({t:E,i:S,rels:a(E)})).sort((E,S)=>E.t.ts-S.t.ts||E.i-S.i),k=null;for(let E of v){let S=c(E.rels);if(S){k=S;break}}!k&&_!==nr&&v.length&&(k=p(v[0].t.ts));for(let E of v){let S=c(E.rels);S&&(k=S),_===nr&&u.push({ts:E.t.ts,seg:k});let R=E.t;if(R.input_tokens+R.output_tokens+R.cache_read_tokens+R.cache_creation_tokens===0)continue;let K=wv(R,E.rels,k,t),x=yv(R.input_tokens+R.cache_read_tokens+R.cache_creation_tokens),T=_v(R.model),D=`${K.object_id??""}|${K.source}|${T}|${x}`,F=f.get(D);F||(F={object_id:K.object_id,attribution_source:K.source,model:T,context_tier:x,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(D,F)),F.input_tokens+=R.input_tokens,F.output_tokens+=R.output_tokens,F.cache_read_tokens+=R.cache_read_tokens,F.cache_creation_tokens+=R.cache_creation_tokens,F.cache_creation_1h_tokens+=R.cache_creation_1h_tokens,F.turns+=1,R.ts>0&&((F.firstMs===0||R.ts<F.firstMs)&&(F.firstMs=R.ts),R.ts>F.lastMs&&(F.lastMs=R.ts))}}let h=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:v,...k}=_;k.first_ts=new Date(b>0?b:h).toISOString(),k.last_ts=new Date(v>0?v:h).toISOString(),g.push(k)}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 Pa,WM,op,lp=w(()=>{"use strict";Na();Pa=[2e5,272e3];s(yv,"contextTierOf");s(_v,"normalizeModelId");WM=Pa[0],op=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Da,"msOf");s(vi,"parseCostContext");s(Ma,"toRepoRelative");s(VM,"underPrefix");s(sp,"prefixesOverlap");s(bv,"sortedAnchors");s(ap,"anchorFor");s(qM,"bestAnchorOverlapping");s(ip,"inWindow");s(wv,"assignTurn");s(cp,"sliceSession")});import{mkdirSync as zM,readFileSync as JM,renameSync as YM,writeFileSync as XM}from"node:fs";import{dirname as ZM,isAbsolute as $a,sep as dp}from"node:path";function QM(e){let t=e.split(dp).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function e$(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function up(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,o=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"),i=new Map,a=[...(e.known??new Map).entries()].filter(([u])=>$a(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 h=p.slice(0,f).join("/");if(!h||e.isDir(h))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)&&o(b)===b)return{root:h,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!$a(u))return null;let p=u.split(dp).join("/"),f=QM(p),h=o(f);if(h){let g=n(h);return i.set(h,g),{root:h,key:g}}for(let[g,y]of a)if(!(!e$(p,g)||p===g)&&!(e.isDir&&e.isDir(g)))return{root:g,key:y};return l(f)},seenLive(){return[...i.entries()].map(([u,p])=>({root:u,key:p}))}}}function pp(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,o=0,i=0;for(let[a,c]of n)(c.turns>o||c.turns===o&&(c.depth>i||c.depth===i&&r!==null&&a<r))&&(r=a,o=c.turns,i=c.depth);return r}function fp(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:Ma(n.split(dp).join("/"),r.root)}}function xv(e){try{let t=JSON.parse(JM(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 ki(e){let t=new Map,n=xv(e);for(let[r,o]of Object.entries(n.checkouts)){if(!$a(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&kv.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}function xi(e,t,n=Date.now()){try{let r=xv(e),o=new Date(n).toISOString(),i=!1;for(let c of t){if(!$a(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>t$)&&(r.checkouts[c.root]={project_key:l,seen_at:o},i=!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],i=!0)}if(!i)return;zM(ZM(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;XM(a,JSON.stringify(r),{mode:384}),YM(a,e)}catch{}}var vv,t$,kv,Sv=w(()=>{"use strict";lp();s(QM,"dirOf");s(e$,"within");s(up,"createCheckoutResolver");s(pp,"dominantProjectKey");s(fp,"relativizerFor");vv=90*24*60*60*1e3,t$=60*60*1e3,kv=/^[a-f0-9]{64}$/;s(xv,"readMemory");s(ki,"loadCheckoutMemory");s(xi,"rememberCheckouts")});import{homedir as n$}from"node:os";import{isAbsolute as m3,join as r$}from"node:path";var o$,mp=w(()=>{"use strict";o$=r$(n$(),".codex","sessions")});var Ev=w(()=>{"use strict";mp()});var hp=w(()=>{"use strict"});var Rv=w(()=>{"use strict";hp()});import{createReadStream as l$,existsSync as d$}from"node:fs";import{createInterface as u$}from"node:readline";function Cv(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function m$(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 h$(e){let t=e.message?.role;if(t==="assistant")return{holder:Cv(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Cv(e.message?.content),r=m$(n);return r.includes(p$)?{holder:"human",genuine:!1}:n.some(i=>i.type==="tool_result"&&i.is_error===!0&&typeof i.content=="string"&&i.content.includes(f$))?{holder:"agent",genuine:!1}:n.some(i=>i.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function gp(e){let t=Iv("");if(!e||!d$(e))return t;let n=null,r=0,o=0,i=null,a="human",c=[];return await new Promise(l=>{let d=l$(e,{encoding:"utf-8"}),u=u$({input:d}),p=s(f=>{let h=f.trim();if(!h)return;let g;try{g=JSON.parse(h)}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)||i!==null&&y<i)return;let _=h$(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,i!==null){let b=y-i;a==="agent"?o+=b:b>=Tv*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<Av&&c.push({offset_seconds:Math.round((i-n)/1e3),duration_seconds:Math.round(b/1e3)}))}i=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(o/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var p$,f$,Tv,Av,Nv=w(()=>{"use strict";p$="[Request interrupted by user",f$="The user doesn't want to proceed with this tool use",Tv=60,Av=200;s(Cv,"asBlocks");s(m$,"textOf");s(Iv,"emptySpan");s(h$,"classify");s(gp,"analyzeSpan")});import{createReadStream as g$,existsSync as y$}from"node:fs";import{createInterface as _$}from"node:readline";function w$(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function La(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function v$(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 yp(e,t={}){if(!e||!y$(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Yu(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),o=t.initialEffort??null,i=t.initialModes?{...t.initialModes}:Yu(),a=t.start??0;return await new Promise(c=>{let l=g$(e,{encoding:"utf-8",start:t.start??0}),d=_$({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let h;try{h=JSON.parse(f)}catch{return}let g=h.sessionId??h.session_id??"",y=h.timestamp?Date.parse(h.timestamp):Date.now(),_=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 b=b$[h.attachment.type];b&&(i[w$(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=v$(h.message?.content),v=bi(b);v&&(o=v);let k={session_id:g,ts:y,text:b,effort_directive:v};n.push({kind:"user",...k});return}if(_==="assistant"){let b=h.message?.usage,v=typeof h.message?.id=="string"&&h.message.id?h.message.id:null,k=typeof h.requestId=="string"&&h.requestId?h.requestId:null,E=v??k,S=E!==null&&r.has(E);E!==null&&!S&&r.add(E);let R={session_id:g,ts:y,model:h.message?.model??null,input_tokens:S?0:La(b?.input_tokens),output_tokens:S?0:La(b?.output_tokens),cache_read_input_tokens:S?0:La(b?.cache_read_input_tokens),cache_creation_input_tokens:S?0:La(b?.cache_creation_input_tokens),effort:o,isSidechain:h.isSidechain===!0,...i.ultracode?{ultracode:!0}:{},...i.planMode?{planMode:!0}:{},...i.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...R})}});let u=s(()=>({events:n,bytesRead:a,effortAtEnd:o,modesAtEnd:{...i},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var b$,Ov=w(()=>{"use strict";Ta();Xu();b$={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(w$,"modeFlagKey");s(La,"num");s(v$,"extractUserText");s(yp,"streamTranscript")});var Dv=w(()=>{"use strict"});import{homedir as k$}from"node:os";import{join as x$}from"node:path";function bp(e){return e.replace(/[/.]/g,"-")}var S$,_p,Pv=w(()=>{"use strict";S$=k$(),_p=x$(S$,".claude","projects");s(bp,"projectPathFromCwd")});var rr=w(()=>{"use strict";Xu();tv();nv();pv();Aa();fv();Na();Sv();mp();Ev();lp();hp();Rv();Nv();Ov();Ta();Dv();Pv()});import{mkdir as E$,readFile as R$,writeFile as C$,rename as T$}from"node:fs/promises";import{existsSync as $v}from"node:fs";import{homedir as A$}from"node:os";import{join as Lv}from"node:path";function Mv(){return{config:null,sessions:{},pending_metrics:[]}}async function ee(){if(!$v(Fa))return Mv();try{let e=await R$(Fa,"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)}
782
- `),Mv()}}async function wt(e){$v(Re)||await E$(Re,{recursive:!0,mode:448});let t=`${Fa}.${process.pid}.tmp`;await C$(t,JSON.stringify(e,null,2),{mode:384}),await T$(t,Fa)}function wp(e){return e.thresholds??e.config?.thresholds??I$}var Re,Fa,I$,Be=w(()=>{"use strict";Re=Lv(A$(),".maind"),Fa=Lv(Re,"state.json"),I$={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(Mv,"emptyState");s(ee,"loadState");s(wt,"saveState");s(wp,"resolveThresholds")});import{execFileSync as N$}from"node:child_process";import{existsSync as O$}from"node:fs";import{join as Fv}from"node:path";function ja(e=D$()){return e?.checkout_memory===!0}function D$(){try{return Q()}catch{return null}}function P$(e){try{let t=N$("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?nn(t):null}catch{return null}}function jv(e,t){try{if(!(t.isCheckoutRoot??(o=>O$(Fv(o,".git"))))(e)||ki(t.memoryPath).has(e))return!1;let r=(t.keyOf??P$)(e);return xi(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var ro,Ha=w(()=>{"use strict";rr();Ue();Be();pe();ro=Fv(Re,"checkout-roots.json");s(ja,"checkoutMemoryAllowed");s(D$,"safeReadConfig");s(P$,"originKey");s(jv,"rememberEditCheckout")});import{rmSync as M$}from"node:fs";import*as Hv from"node:readline";async function vp(e){let t=e.configPath??He(),n=e.memoryPath??ro;if(e.skip)return{target:an,action:"skip",status:"skipped",detail:"--no-hook"};let r={};try{let a=await q(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(r=c)}}catch{}if(typeof r.checkout_memory=="boolean")return{target:an,action:"skip",status:"skipped",detail:`already decided (${r.checkout_memory?"on":"off"}) in ${t}`};let o;if(e.full)o=!0;else if(e.isInteractive){if(e.dryRun)return{target:an,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};o=await(e.promptFn??L$)(e.out,$$)}else return{target:an,action:"skip",status:"skipped",detail:"consent-required: checkout memory stays off \u2014 pass --full, or run install in a terminal to be asked"};if(e.dryRun)return{target:an,action:"merge",status:"would-merge",detail:t};let i={...r,checkout_memory:o};try{await U(t,JSON.stringify(i,null,2)+`
783
- `,384)}catch(a){return{target:an,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}if(!o){let a=!1;try{M$(n,{force:!0}),a=!0}catch{a=!1}return{target:an,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory off${a?`; ${n} removed if it existed`:`; could not remove ${n}`}`}}return{target:an,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory on (${n}, local only; off: checkout_memory=false)`}}async function L$(e,t){e.write(t);let n=Hv.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var an,$$,Uv=w(()=>{"use strict";Ue();Ha();ie();an="config:checkout_memory",$$=`
781
+ [y/N]: `;s(ev,"applyWorkingPathsConsent");s(fM,"promptYesNoDefaultNo")});function Yu(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Xu=w(()=>{"use strict";s(Yu,"newModeState")});import{createReadStream as mM,existsSync as hM}from"node:fs";import{stat as gM}from"node:fs/promises";import{createInterface as yM}from"node:readline";async function Zu(e){if(!e||!hM(e))return null;let t;try{t=await gM(e)}catch{return null}let n=new Set,r=0,o=0,i=0;return await new Promise(a=>{let c=mM(e,{encoding:"utf-8"}),l=yM({input:c});l.on("line",d=>{let u=d.trim();if(u){i++;try{let p=JSON.parse(u),f=p.message?.usage;if(!f)return;let h=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=h??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(o+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:o,total_tokens:r+o,lines_seen:i,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var nv=w(()=>{"use strict";s(Zu,"summariseTranscript")});var rv=w(()=>{"use strict"});function bi(e){if(!e)return null;let t=null;for(let n of e.matchAll(bM)){let r=n[1].toLowerCase();_M.has(r)&&(t=r)}return t}var _M,bM,Aa=w(()=>{"use strict";_M=new Set(["low","medium","high","xhigh","max"]),bM=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(bi,"detectEffortLevel")});function eo(e){for(let t of ov)if(e.startsWith(t)){let n=e.slice(t.length);return n.length>0?n:null}return null}var ov,Ia=w(()=>{"use strict";ov=["mcp__maind__","mcp__plugin_maind_maind__"];s(eo,"maindToolName")});import{createReadStream as wM,existsSync as vM,readdirSync as kM}from"node:fs";import{basename as av,dirname as xM,join as iv}from"node:path";import{createInterface as SM}from"node:readline";function lv(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!CM.test(n)||e.ids.includes(n)||e.ids.length>=cv||e.ids.push(n)}function TM(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")continue;let o=eo(r.name);if(o===null||RM.has(o))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?lv(e,i.session_id):o==="announce_session"&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function AM(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 IM(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 o=AM(r.content),i=null;try{let a=JSON.parse(o);a&&a.ok===!0&&(i=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(o);i=a?a[1]:null}lv(e,i)}}function to(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function OM(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 o=NM[r.name];if(!o||!r.input||typeof r.input!="object")continue;let i=r.input[o];typeof i=="string"&&i.length>0&&t.push(i)}return t}function Na(e){let t=av(e).replace(/\.jsonl$/,""),n=iv(xM(e),t,"subagents"),r;try{r=kM(n)}catch{return[]}return r.filter(o=>o.endsWith(".jsonl")).sort().map(o=>iv(n,o))}async function sv(e,t,n,r,o,i){vM(e)&&await new Promise(a=>{let c=wM(e,{encoding:"utf-8"}),l=SM({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"){IM(i,f.message.content);return}if(f.message?.role!=="assistant")return;TM(i,f.message.content);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??`${e}#${d}`,_=OM(f.message.content),b=r.get(y);if(b){for(let R of _)b.edited_paths.includes(R)||b.edited_paths.push(R);return}if(n.has(y))return;n.add(y);let v=f.message.usage??{},k=typeof f.timestamp=="string"?Date.parse(f.timestamp):Number.NaN,E=typeof f.message.model=="string"&&f.message.model?f.message.model:"",S={ts:Number.isFinite(k)?k:0,model:E||"<unknown>",synthetic:E===EM,input_tokens:to(v.input_tokens),output_tokens:to(v.output_tokens),cache_read_tokens:to(v.cache_read_input_tokens),cache_creation_tokens:to(v.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(to(v.cache_creation?.ephemeral_1h_input_tokens),to(v.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,S),o.push(S)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function Qu(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 o=e[r];o.ts>0?n=o.ts:n>0&&(o.ts=n)}}async function wi(e){let t=new Set,n=new Map,r=[],o=e?Na(e):[],i={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:o,coordination_ids:[]};let a=[];await sv(e,nr,t,n,a,i),Qu(a),r.push(...a);for(let c of o){let l=[],d=av(c).replace(/\.jsonl$/,"");i.pendingAnnounce.clear(),await sv(c,d,t,n,l,i),Qu(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:o,coordination_ids:i.ids}}var nr,EM,RM,CM,cv,NM,Oa=w(()=>{"use strict";Ia();nr="main",EM="<synthetic>",RM=new Set(["get_session_analysis","get_session_cost_context"]),CM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,cv=32;s(lv,"addCoordinationId");s(TM,"noteCoordinationUse");s(AM,"resultText");s(IM,"noteAnnounceResult");NM={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(to,"num");s(OM,"editedPathsOf");s(Na,"subagentFilesOf");s(sv,"readStream");s(Qu,"fillTimestamps");s(wi,"collectTurns")});import{createReadStream as dv,existsSync as DM}from"node:fs";import{createInterface as uv}from"node:readline";function HM(e,t,n,r,o){let i=`${n?"s":"m"}:${t}`,a=e.get(i);if(!a){e.set(i,{model:t,turns:1,output_tokens:r,first_ts:o,last_ts:o,sidechain:n});return}a.turns++,a.output_tokens+=r,o>0&&((a.first_ts===0||o<a.first_ts)&&(a.first_ts=o),o>a.last_ts&&(a.last_ts=o))}function Da(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function UM(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
782
+ `)}function BM(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),o=n(t);if(r.size<3||o.size<3)return!1;let[i,a]=r.size<=o.size?[r,o]:[o,r],c=0;for(let l of i)a.has(l)&&c++;return c/i.size>=.8}function KM(e,t,n){return PM.test(e)?{polarity:-1,magnitude:no.rework,kind:"rework"}:n&&MM.test(e)?{polarity:-1,magnitude:no.correction,kind:"correction"}:$M.test(e)?{polarity:1,magnitude:no.acceptance,kind:"acceptance"}:t!==null&&BM(t,e)?{polarity:-1,magnitude:no.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function GM(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:pv,behaviour_measured:!0}}async function WM(e,t){for(let n of Na(e))await new Promise(r=>{let o=uv({input:dv(n,{encoding:"utf-8"})});o.on("line",i=>{let a=i.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")continue;let d=eo(l.name);d!==null&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),o.on("error",()=>r()),o.on("close",()=>r())})}async function ep(e,t={}){let n=GM("");if(!e||!DM(e))return n;let r=t.turns??(await wi(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 o=[],i=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=dv(e,{encoding:"utf-8"}),y=uv({input:g}),_=s(b=>{let v=b.trim();if(!v)return;let k;try{k=JSON.parse(v)}catch{return}if(n.lines_seen++,!n.session_id){let D=k.sessionId??k.session_id;typeof D=="string"&&D&&(n.session_id=D)}k.type==="ai-title"&&typeof k.aiTitle=="string"&&k.aiTitle&&(n.ai_title=k.aiTitle),typeof k.slug=="string"&&k.slug&&(n.session_slug=k.slug);let E=k.message?.role,S=k.isSidechain===!0;if(E==="assistant")for(let D of Da(k.message?.content)){if(D.type!=="tool_use"||typeof D.name!="string")continue;let F=eo(D.name);F!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[F]=(n.maind_tool_calls[F]??0)+1)}if(S)return;if(E==="assistant"){let D=Da(k.message?.content),F=!1;for(let xt of D)xt.type==="tool_use"&&(n.tool_calls++,F=!0,xt.name==="AskUserQuestion"&&n.agent_questions++);c=F;return}if(E!=="user")return;let R=Da(k.message?.content),P=UM(R);if(P.includes(LM)){n.interrupts++,o.push({polarity:-1,magnitude:no.interrupt,kind:"interrupt"});return}if(R.some(D=>D.type==="tool_result"&&D.is_error===!0&&typeof D.content=="string"&&D.content.includes(FM))){n.tool_denials++,o.push({polarity:-1,magnitude:no.denial,kind:"denial"});return}if(R.some(D=>D.type==="tool_result")||!P.trim())return;n.user_turns++,n.user_chars+=P.length;let x=bi(P);x&&(a=x);let T=KM(P,l,c);l=P,T.kind==="correction"?n.corrections++:T.kind==="rework"?n.reworks++:T.kind==="repeat"?n.repeated_instructions++:T.kind==="acceptance"&&n.acceptances++,T.polarity!==0&&o.push(T),c=!1},"processLine");y.on("line",b=>{try{_(b)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await WM(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||HM(i,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...i.values()].sort((h,g)=>h.first_ts-g.first_ts||h.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return o.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*jM+h.polarity*h.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...h.kind!=="neutral"?{kind:h.kind}:{}}),p+=y,g>0&&o[g-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var pv,PM,MM,$M,LM,FM,jM,no,fv=w(()=>{"use strict";Aa();Ia();Oa();pv="2026-10-01",PM=/(\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,MM=/(\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,$M=/(\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,LM="[Request interrupted by user",FM="The user doesn't want to proceed with this tool use",jM=.7,no={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(HM,"bumpModel");s(Da,"asBlocks");s(UM,"textOf");s(BM,"isRepeat");s(KM,"classifyGenuine");s(GM,"emptyAnalysis");s(WM,"tallySubagentMaindCalls");s(ep,"analyzeSession")});function tp(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 np(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 rp(e,t,n,r="unknown",o){let i={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]}:{},...o?{cost_slices:o.slices,cost_context_ok:o.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...c}=n;i.session_span={...t,...c}}else i.session_span=t;return i}var mv=w(()=>{"use strict";s(tp,"parseIngestResponse");s(np,"describeSliceVerdict");s(rp,"ingestBody")});import{isAbsolute as hv,relative as VM,resolve as gv,sep as yv}from"node:path";function _v(e){return e>Ma[1]?"above_272k":e>Ma[0]?"band_200k_272k":"standard"}function bv(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Pa(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function vi(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=Pa(d.from);typeof d.object_id!="string"||!op.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:Pa(d.to)})}return c},"windows"),o=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=Pa(c.from);typeof c.path_prefix!="string"||l===null||o.push({path_prefix:c.path_prefix,from:l,to:Pa(c.to)})}let i=[];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"||!op.test(c.object_id)||typeof c.path_prefix=="string"&&i.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&op.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:o,anchors:i}}function $a(e,t){if(!hv(e))return null;let n=VM(gv(t),gv(e));return!n||n==="."||n.startsWith("..")||hv(n)?null:yv==="/"?n:n.split(yv).join("/")}function zM(e,t){return t===""||e===t||e.startsWith(t+"/")}function sp(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function wv(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function ap(e,t){for(let n of wv(t))if(zM(e,n.path_prefix))return n.object_id;return null}function JM(e,t){for(let n of wv(t))if(sp(e,n.path_prefix))return n.object_id;return null}function ip(e,t){return e>=t.from&&(t.to===null||e<t.to)}function vv(e,t,n,r){let o=e.ts,i=r?.anchors??[],a=t.map(c=>ap(c,i)).filter(c=>c!==null);if(r&&o>0){let c=r.leases.filter(u=>ip(o,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=>ip(o,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=>ip(o,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>sp(f.path_prefix,u))).sort((f,h)=>h.path_prefix.length-f.path_prefix.length);for(let f of p){let h=JM(f.path_prefix,i);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 cp(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?_=>$a(_,o):null),a=s(_=>{if(!i)return[];let b=[];for(let v of _.edited_paths){let k=i(v);k!==null&&!b.includes(k)&&b.push(k)}return b},"relOf"),c=s(_=>{for(let b of _){let v=ap(b,r);if(v)return{object_id:v,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])=>_===nr?-1:b===nr?1:0),u=[],p=s(_=>{let b=null;for(let v of u){if(v.ts>_&&_>0)break;b=v.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let v=b.map((E,S)=>({t:E,i:S,rels:a(E)})).sort((E,S)=>E.t.ts-S.t.ts||E.i-S.i),k=null;for(let E of v){let S=c(E.rels);if(S){k=S;break}}!k&&_!==nr&&v.length&&(k=p(v[0].t.ts));for(let E of v){let S=c(E.rels);S&&(k=S),_===nr&&u.push({ts:E.t.ts,seg:k});let R=E.t;if(R.input_tokens+R.output_tokens+R.cache_read_tokens+R.cache_creation_tokens===0)continue;let K=vv(R,E.rels,k,t),x=_v(R.input_tokens+R.cache_read_tokens+R.cache_creation_tokens),T=bv(R.model),D=`${K.object_id??""}|${K.source}|${T}|${x}`,F=f.get(D);F||(F={object_id:K.object_id,attribution_source:K.source,model:T,context_tier:x,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(D,F)),F.input_tokens+=R.input_tokens,F.output_tokens+=R.output_tokens,F.cache_read_tokens+=R.cache_read_tokens,F.cache_creation_tokens+=R.cache_creation_tokens,F.cache_creation_1h_tokens+=R.cache_creation_1h_tokens,F.turns+=1,R.ts>0&&((F.firstMs===0||R.ts<F.firstMs)&&(F.firstMs=R.ts),R.ts>F.lastMs&&(F.lastMs=R.ts))}}let h=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:v,...k}=_;k.first_ts=new Date(b>0?b:h).toISOString(),k.last_ts=new Date(v>0?v:h).toISOString(),g.push(k)}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 Ma,qM,op,lp=w(()=>{"use strict";Oa();Ma=[2e5,272e3];s(_v,"contextTierOf");s(bv,"normalizeModelId");qM=Ma[0],op=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Pa,"msOf");s(vi,"parseCostContext");s($a,"toRepoRelative");s(zM,"underPrefix");s(sp,"prefixesOverlap");s(wv,"sortedAnchors");s(ap,"anchorFor");s(JM,"bestAnchorOverlapping");s(ip,"inWindow");s(vv,"assignTurn");s(cp,"sliceSession")});import{mkdirSync as YM,readFileSync as XM,renameSync as ZM,writeFileSync as QM}from"node:fs";import{dirname as e$,isAbsolute as La,sep as dp}from"node:path";function t$(e){let t=e.split(dp).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function n$(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function up(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,o=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"),i=new Map,a=[...(e.known??new Map).entries()].filter(([u])=>La(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 h=p.slice(0,f).join("/");if(!h||e.isDir(h))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)&&o(b)===b)return{root:h,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!La(u))return null;let p=u.split(dp).join("/"),f=t$(p),h=o(f);if(h){let g=n(h);return i.set(h,g),{root:h,key:g}}for(let[g,y]of a)if(!(!n$(p,g)||p===g)&&!(e.isDir&&e.isDir(g)))return{root:g,key:y};return l(f)},seenLive(){return[...i.entries()].map(([u,p])=>({root:u,key:p}))}}}function pp(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,o=0,i=0;for(let[a,c]of n)(c.turns>o||c.turns===o&&(c.depth>i||c.depth===i&&r!==null&&a<r))&&(r=a,o=c.turns,i=c.depth);return r}function fp(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:$a(n.split(dp).join("/"),r.root)}}function Sv(e){try{let t=JSON.parse(XM(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 ki(e){let t=new Map,n=Sv(e);for(let[r,o]of Object.entries(n.checkouts)){if(!La(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&xv.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}function xi(e,t,n=Date.now()){try{let r=Sv(e),o=new Date(n).toISOString(),i=!1;for(let c of t){if(!La(c.root))continue;let l=c.key&&xv.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>r$)&&(r.checkouts[c.root]={project_key:l,seen_at:o},i=!0)}for(let[c,l]of Object.entries(r.checkouts)){let d=Date.parse(l?.seen_at??"");(!Number.isFinite(d)||n-d>kv)&&(delete r.checkouts[c],i=!0)}if(!i)return;YM(e$(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;QM(a,JSON.stringify(r),{mode:384}),ZM(a,e)}catch{}}var kv,r$,xv,Ev=w(()=>{"use strict";lp();s(t$,"dirOf");s(n$,"within");s(up,"createCheckoutResolver");s(pp,"dominantProjectKey");s(fp,"relativizerFor");kv=90*24*60*60*1e3,r$=60*60*1e3,xv=/^[a-f0-9]{64}$/;s(Sv,"readMemory");s(ki,"loadCheckoutMemory");s(xi,"rememberCheckouts")});import{homedir as o$}from"node:os";import{isAbsolute as g3,join as i$}from"node:path";var s$,mp=w(()=>{"use strict";s$=i$(o$(),".codex","sessions")});var Rv=w(()=>{"use strict";mp()});var hp=w(()=>{"use strict"});var Cv=w(()=>{"use strict";hp()});import{createReadStream as u$,existsSync as p$}from"node:fs";import{createInterface as f$}from"node:readline";function Tv(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function g$(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
783
+ `)}function Nv(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 y$(e){let t=e.message?.role;if(t==="assistant")return{holder:Tv(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Tv(e.message?.content),r=g$(n);return r.includes(m$)?{holder:"human",genuine:!1}:n.some(i=>i.type==="tool_result"&&i.is_error===!0&&typeof i.content=="string"&&i.content.includes(h$))?{holder:"agent",genuine:!1}:n.some(i=>i.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function gp(e){let t=Nv("");if(!e||!p$(e))return t;let n=null,r=0,o=0,i=null,a="human",c=[];return await new Promise(l=>{let d=u$(e,{encoding:"utf-8"}),u=f$({input:d}),p=s(f=>{let h=f.trim();if(!h)return;let g;try{g=JSON.parse(h)}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)||i!==null&&y<i)return;let _=y$(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,i!==null){let b=y-i;a==="agent"?o+=b:b>=Av*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<Iv&&c.push({offset_seconds:Math.round((i-n)/1e3),duration_seconds:Math.round(b/1e3)}))}i=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(o/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var m$,h$,Av,Iv,Ov=w(()=>{"use strict";m$="[Request interrupted by user",h$="The user doesn't want to proceed with this tool use",Av=60,Iv=200;s(Tv,"asBlocks");s(g$,"textOf");s(Nv,"emptySpan");s(y$,"classify");s(gp,"analyzeSpan")});import{createReadStream as _$,existsSync as b$}from"node:fs";import{createInterface as w$}from"node:readline";function k$(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function Fa(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function x$(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 yp(e,t={}){if(!e||!b$(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Yu(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),o=t.initialEffort??null,i=t.initialModes?{...t.initialModes}:Yu(),a=t.start??0;return await new Promise(c=>{let l=_$(e,{encoding:"utf-8",start:t.start??0}),d=w$({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let h;try{h=JSON.parse(f)}catch{return}let g=h.sessionId??h.session_id??"",y=h.timestamp?Date.parse(h.timestamp):Date.now(),_=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 b=v$[h.attachment.type];b&&(i[k$(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=x$(h.message?.content),v=bi(b);v&&(o=v);let k={session_id:g,ts:y,text:b,effort_directive:v};n.push({kind:"user",...k});return}if(_==="assistant"){let b=h.message?.usage,v=typeof h.message?.id=="string"&&h.message.id?h.message.id:null,k=typeof h.requestId=="string"&&h.requestId?h.requestId:null,E=v??k,S=E!==null&&r.has(E);E!==null&&!S&&r.add(E);let R={session_id:g,ts:y,model:h.message?.model??null,input_tokens:S?0:Fa(b?.input_tokens),output_tokens:S?0:Fa(b?.output_tokens),cache_read_input_tokens:S?0:Fa(b?.cache_read_input_tokens),cache_creation_input_tokens:S?0:Fa(b?.cache_creation_input_tokens),effort:o,isSidechain:h.isSidechain===!0,...i.ultracode?{ultracode:!0}:{},...i.planMode?{planMode:!0}:{},...i.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...R})}});let u=s(()=>({events:n,bytesRead:a,effortAtEnd:o,modesAtEnd:{...i},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var v$,Dv=w(()=>{"use strict";Aa();Xu();v$={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(k$,"modeFlagKey");s(Fa,"num");s(x$,"extractUserText");s(yp,"streamTranscript")});var Pv=w(()=>{"use strict"});import{homedir as S$}from"node:os";import{join as E$}from"node:path";function bp(e){return e.replace(/[/.]/g,"-")}var R$,_p,Mv=w(()=>{"use strict";R$=S$(),_p=E$(R$,".claude","projects");s(bp,"projectPathFromCwd")});var rr=w(()=>{"use strict";Xu();nv();rv();fv();Ia();mv();Oa();Ev();mp();Rv();lp();hp();Cv();Ov();Dv();Aa();Pv();Mv()});import{mkdir as C$,readFile as T$,writeFile as A$,rename as I$}from"node:fs/promises";import{existsSync as Lv}from"node:fs";import{homedir as N$}from"node:os";import{join as Fv}from"node:path";function $v(){return{config:null,sessions:{},pending_metrics:[]}}async function ee(){if(!Lv(ja))return $v();try{let e=await T$(ja,"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)}
785
+ `),$v()}}async function wt(e){Lv(Re)||await C$(Re,{recursive:!0,mode:448});let t=`${ja}.${process.pid}.tmp`;await A$(t,JSON.stringify(e,null,2),{mode:384}),await I$(t,ja)}function wp(e){return e.thresholds??e.config?.thresholds??O$}var Re,ja,O$,Be=w(()=>{"use strict";Re=Fv(N$(),".maind"),ja=Fv(Re,"state.json"),O$={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s($v,"emptyState");s(ee,"loadState");s(wt,"saveState");s(wp,"resolveThresholds")});import{execFileSync as D$}from"node:child_process";import{existsSync as P$}from"node:fs";import{join as jv}from"node:path";function Ha(e=M$()){return e?.checkout_memory===!0}function M$(){try{return Q()}catch{return null}}function $$(e){try{let t=D$("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?nn(t):null}catch{return null}}function Hv(e,t){try{if(!(t.isCheckoutRoot??(o=>P$(jv(o,".git"))))(e)||ki(t.memoryPath).has(e))return!1;let r=(t.keyOf??$$)(e);return xi(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var ro,Ua=w(()=>{"use strict";rr();Ue();Be();pe();ro=jv(Re,"checkout-roots.json");s(Ha,"checkoutMemoryAllowed");s(M$,"safeReadConfig");s($$,"originKey");s(Hv,"rememberEditCheckout")});import{rmSync as L$}from"node:fs";import*as Uv from"node:readline";async function vp(e){let t=e.configPath??He(),n=e.memoryPath??ro;if(e.skip)return{target:an,action:"skip",status:"skipped",detail:"--no-hook"};let r={};try{let a=await q(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(r=c)}}catch{}if(typeof r.checkout_memory=="boolean")return{target:an,action:"skip",status:"skipped",detail:`already decided (${r.checkout_memory?"on":"off"}) in ${t}`};let o;if(e.full)o=!0;else if(e.isInteractive){if(e.dryRun)return{target:an,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};o=await(e.promptFn??j$)(e.out,F$)}else return{target:an,action:"skip",status:"skipped",detail:"consent-required: checkout memory stays off \u2014 pass --full, or run install in a terminal to be asked"};if(e.dryRun)return{target:an,action:"merge",status:"would-merge",detail:t};let i={...r,checkout_memory:o};try{await U(t,JSON.stringify(i,null,2)+`
786
+ `,384)}catch(a){return{target:an,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}if(!o){let a=!1;try{L$(n,{force:!0}),a=!0}catch{a=!1}return{target:an,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory off${a?`; ${n} removed if it existed`:`; could not remove ${n}`}`}}return{target:an,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory on (${n}, local only; off: checkout_memory=false)`}}async function j$(e,t){e.write(t);let n=Uv.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var an,F$,Bv=w(()=>{"use strict";Ue();Ua();ie();an="config:checkout_memory",F$=`
784
787
  Remember the repositories you edit in (checkout memory)?
785
788
  With this ON, the repo-health hook (before an edit) and the Stop hook (after a
786
789
  turn) record the ROOT directory of each git checkout you edit in, plus its
@@ -791,28 +794,28 @@ never file names, never contents. The file never leaves this machine; entries
791
794
  not seen for 90 days are pruned. Without it, a deleted worktree is still
792
795
  recognised when it follows the \`maind feature start\` naming (<repo>-<name>).
793
796
  Off later: {"checkout_memory": false} in the bridge config.
794
- [Y/n]: `;s(vp,"applyCheckoutMemoryConsent");s(L$,"promptYesNoDefaultYes")});import{existsSync as F$}from"node:fs";import{dirname as j$,join as Bv}from"node:path";function ln(e,t=F$){let n=e;for(;;){if(t(Bv(n,".git")))return n;let r=j$(n);if(r===n)return null;n=r}}var cn,Ua=w(()=>{"use strict";cn=Bv(".maind","code-index.sqlite");s(ln,"findRepoRoot")});import{existsSync as H$}from"node:fs";import{join as U$}from"node:path";function B$(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"}function Kv(e,t,n=H$){if(!B$(t))return null;let r=ln(e,n)??e;return n(U$(r,cn))?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.`}}var Gv=w(()=>{"use strict";Ua();s(B$,"readHookWired");s(Kv,"contextIndexRow")});import*as Sp from"node:path";import*as Vv from"node:readline";function qv(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}function or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W$(e,t,n){if(!or(e)||!or(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let o of r)if(or(o)&&typeof o.command=="string"&&o.command.includes(n))return o.command;return null}async function V$(e,t){let n=Sp.join(e.homeDir,K$),r=qv(t),o=s((g,y,_="merge")=>({target:r,action:_,status:g,detail:y}),"row");if(e.skip)return o("skipped","--no-hook","skip");let i;try{i=await q(n)}catch(g){return o("failed",`read: ${xp(g)}`)}let a={},c=i===null||i.trim().length===0;if(!c){let g;try{g=JSON.parse(i)}catch(_){return o("failed",`parse: ${xp(_)} \u2014 ${n} left untouched`)}if(!or(g))return o("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==kp)return o("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${kp}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!or(a.hooks))return o("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=or(a.hooks)?a.hooks[t.event]:void 0;if(y!==void 0&&!Array.isArray(y))return o("failed",`"hooks.${t.event}" in ${n} is not an array \u2014 left untouched`)}let l=e.launch??we({entryPath:oe(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=ze(l),u=W$(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return o("skipped",rn(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 o("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return o(c?"would-create":"would-merge",`${n} (would prompt for consent in real run)`);if(!await(e.prompt??q$)(e.out,`
797
+ [Y/n]: `;s(vp,"applyCheckoutMemoryConsent");s(j$,"promptYesNoDefaultYes")});import{existsSync as H$}from"node:fs";import{dirname as U$,join as Kv}from"node:path";function ln(e,t=H$){let n=e;for(;;){if(t(Kv(n,".git")))return n;let r=U$(n);if(r===n)return null;n=r}}var cn,Ba=w(()=>{"use strict";cn=Kv(".maind","code-index.sqlite");s(ln,"findRepoRoot")});import{existsSync as B$}from"node:fs";import{join as K$}from"node:path";function G$(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"}function Gv(e,t,n=B$){if(!G$(t))return null;let r=ln(e,n)??e;return n(K$(r,cn))?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.`}}var Wv=w(()=>{"use strict";Ba();s(G$,"readHookWired");s(Gv,"contextIndexRow")});import*as Sp from"node:path";import*as qv from"node:readline";function zv(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}function or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function q$(e,t,n){if(!or(e)||!or(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let o of r)if(or(o)&&typeof o.command=="string"&&o.command.includes(n))return o.command;return null}async function z$(e,t){let n=Sp.join(e.homeDir,W$),r=zv(t),o=s((g,y,_="merge")=>({target:r,action:_,status:g,detail:y}),"row");if(e.skip)return o("skipped","--no-hook","skip");let i;try{i=await q(n)}catch(g){return o("failed",`read: ${xp(g)}`)}let a={},c=i===null||i.trim().length===0;if(!c){let g;try{g=JSON.parse(i)}catch(_){return o("failed",`parse: ${xp(_)} \u2014 ${n} left untouched`)}if(!or(g))return o("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==kp)return o("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${kp}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!or(a.hooks))return o("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=or(a.hooks)?a.hooks[t.event]:void 0;if(y!==void 0&&!Array.isArray(y))return o("failed",`"hooks.${t.event}" in ${n} is not an array \u2014 left untouched`)}let l=e.launch??we({entryPath:oe(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=ze(l),u=q$(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return o("skipped",rn(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 o("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return o(c?"would-create":"would-merge",`${n} (would prompt for consent in real run)`);if(!await(e.prompt??J$)(e.out,`
795
798
  Add a ${t.event} hook to ${n}?
796
799
  ${t.consentDescription}
797
800
  [Y/n]: `))return o("skipped","user declined","skip")}let p=or(a.hooks)?a.hooks:{},f=Array.isArray(p[t.event])?p[t.event]:[],h={...a,version:a.version??kp,hooks:{...p,[t.event]:[...f,{command:d,timeout:t.timeout}]}};if(e.dryRun)return o(c?"would-create":"would-merge",n,c?"write":"merge");try{await U(n,JSON.stringify(h,null,2)+`
798
- `)}catch(g){return o("failed",`write: ${xp(g)}`)}return o(c?"created":"merged",n,c?"write":"merge")}async function Ep(e){if(!e.explicit&&!e.skip&&!Cw(e.presence.ctx,e.presence.probe)){let n=Pt(e.presence.ctx).skipDetail;return Wv.map(r=>({target:qv(r),action:"skip",status:"skipped",detail:n}))}let t=[];for(let n of Wv)t.push(await V$(e,n));return t}async function q$(e,t){e.write(t);let n=Vv.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function xp(e){return e instanceof Error?e.message:String(e)}var K$,kp,G$,Wv,zv=w(()=>{"use strict";ie();_t();Je();Xr();K$=Sp.join(".cursor","hooks.json"),kp=1,G$="on-cursor-session-start",Wv=[{event:"sessionStart",subcommand:G$,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 for teams that work mostly in Cursor, the team option (`install --team`: the conventions in the repository's AGENTS.md, which Cursor reads reliably) is the dependable channel."}];s(qv,"targetKeyFor");s(or,"isObject");s(W$,"findCursorHookCommand");s(V$,"mergeCursorHook");s(Ep,"mergeCursorHooks");s(q$,"promptYesNo");s(xp,"errMessage")});import{existsSync as z$,readdirSync as J$,readFileSync as Y$}from"node:fs";import*as dn from"node:path";function X$(e){let t=e[Yv]?.trim();return t!==void 0&&t.length>0?t:null}function Z$(e,t){let n=t.CLAUDE_CONFIG_DIR?.trim();return n&&dn.isAbsolute(n)?n:dn.join(e,".claude")}function Q$(e){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}function Jv(e){if(!(e===null||e.trim().length===0))try{let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))return;let n=t.enabledPlugins;if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n[Si];return typeof r=="boolean"?r:void 0}catch{return}}function De(e){let t=Q$(e.platform),n=[dn.join(t,"managed-settings.json")],r=e.list(dn.join(t,"managed-settings.d"));if(r!==null)for(let a of[...r].sort())a.startsWith(".")||!a.endsWith(".json")||n.push(dn.join(t,"managed-settings.d",a));let o=null;for(let a of n){let c=Jv(e.read(a));c!==void 0&&(o={value:c,file:a})}let i=(()=>{if(o!==null)return{enabled:o.value,source:"managed",file:o.file};let a=dn.join(Z$(e.homeDir,e.env),"settings.json"),c=Jv(e.read(a));return c!==void 0?{enabled:c,source:"user",file:a}:{enabled:!1,source:null,file:null}})();return!i.enabled&&X$(e.env)!==null?{enabled:!0,source:"env",file:null}:i}function Xv(e){return e.source==="env"?` (this process was started by the plugin, ${Yv})`:e.file?` in ${e.file}`:""}function Ba(e){return`Claude Code hooks: provided by the maind plugin (${Si} is enabled${Xv(e)}) \u2014 none written to settings.json`}function Zv(e){return`Claude Code MCP server: provided by the maind plugin (${Si} is enabled${Xv(e)}) \u2014 nothing written to ~/.claude.json, which would start a second maind server`}function Pe(e,t,n){return{homeDir:e,env:t,platform:n,read:s(r=>{try{return z$(r)?Y$(r,"utf8"):null}catch{return null}},"read"),list:s(r=>{try{return J$(r)}catch{return null}},"list")}}var Si,Yv,oo=w(()=>{"use strict";Si="maind@maind",Yv="MAIND_CLAUDE_PLUGIN";s(X$,"pluginEnvVersion");s(Z$,"claudeConfigDir");s(Q$,"managedSettingsDir");s(Jv,"pluginEntryIn");s(De,"maindPluginState");s(Xv,"where");s(Ba,"pluginRowDetail");s(Zv,"pluginMcpRowDetail");s(Pe,"fsPluginProbe")});import*as un from"node:path";import*as ek from"node:readline";import{parse as Qv,stringify as eL}from"smol-toml";function Ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ei(e,t){if(!Ce(e)||!Ce(e.hooks))return null;let n=e.hooks.SessionStart;if(!Array.isArray(n))return null;for(let r of n)if(!(!Ce(r)||!Array.isArray(r.hooks))){for(let o of r.hooks)if(Ce(o)&&typeof o.command=="string"&&o.command.includes(t))return o.command}return null}function iL(e,t){let n=un.relative(t,e),r=n!==""&&!n.startsWith("..")&&!un.isAbsolute(n)?`~/${n.split(un.sep).join("/")}`:e;return`hook(${J}):${r}`}async function Rp(e){let t=pi(e.presence.ctx),n=iL(t,e.homeDir),r=s((b,v,k="merge")=>({target:n,action:k,status:b,detail:v}),"row");if(e.skip)return r("skipped","--no-hook","skip");if(e.skipCodex)return r("skipped","--skip-codex","skip");if(!e.explicit&&!Ne(Yr(e.presence.ctx),e.presence.probe))return r("skipped",Yr(e.presence.ctx).skipDetail,"skip");let o;try{o=await q(t)}catch(b){return r("failed",`read: ${Ka(b)}`)}let i={},a=o===null||o.trim().length===0;if(!a)try{let b=Qv(o);if(!Ce(b))return r("failed",`${t} is not a TOML table \u2014 left untouched`);i=b}catch(b){return r("failed",`parse: ${Ka(b)} \u2014 ${t} left untouched`)}let c=i.features;if(c!==void 0&&!Ce(c))return r("failed",`[features] in ${t} is not a table \u2014 left untouched`);if(Ce(c)&&(c.hooks===!1||c.codex_hooks===!1))return r("skipped",`hooks are switched off in ${t} ([features] ${c.hooks===!1?"hooks":"codex_hooks"} = false) \u2014 left as it is`,"skip");if(i.hooks!==void 0&&!Ce(i.hooks))return r("failed",`[hooks] in ${t} is not a table \u2014 left untouched`);let l=Ce(i.hooks)?i.hooks.SessionStart:void 0;if(l!==void 0&&!Array.isArray(l))return r("failed",`hooks.SessionStart in ${t} is not an array of tables \u2014 left untouched`);let d=e.launch??we({entryPath:oe(),nodePath:process.execPath,extraArgs:[J,tL],isElectron:process.versions.electron!==void 0}),u=ze(d),p=Ei(i,J)??await sL(e.presence.ctx);if(p!==null){let b=`Codex's SessionStart hook already runs maind ${J}`;return r("skipped",rn(p)?`${b}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${u}`:b,"skip")}if(!e.full){if(!e.isInteractive)return r("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return r(a?"would-create":"would-merge",`${t} (would prompt for consent in real run)`);if(!await(e.prompt??cL)(e.out,`
801
+ `)}catch(g){return o("failed",`write: ${xp(g)}`)}return o(c?"created":"merged",n,c?"write":"merge")}async function Ep(e){if(!e.explicit&&!e.skip&&!Tw(e.presence.ctx,e.presence.probe)){let n=Mt(e.presence.ctx).skipDetail;return Vv.map(r=>({target:zv(r),action:"skip",status:"skipped",detail:n}))}let t=[];for(let n of Vv)t.push(await z$(e,n));return t}async function J$(e,t){e.write(t);let n=qv.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function xp(e){return e instanceof Error?e.message:String(e)}var W$,kp,V$,Vv,Jv=w(()=>{"use strict";ie();_t();Je();Xr();W$=Sp.join(".cursor","hooks.json"),kp=1,V$="on-cursor-session-start",Vv=[{event:"sessionStart",subcommand:V$,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 for teams that work mostly in Cursor, the team option (`install --team`: the conventions in the repository's AGENTS.md, which Cursor reads reliably) is the dependable channel."}];s(zv,"targetKeyFor");s(or,"isObject");s(q$,"findCursorHookCommand");s(z$,"mergeCursorHook");s(Ep,"mergeCursorHooks");s(J$,"promptYesNo");s(xp,"errMessage")});import{existsSync as Y$,readdirSync as X$,readFileSync as Z$}from"node:fs";import*as dn from"node:path";function Q$(e){let t=e[Xv]?.trim();return t!==void 0&&t.length>0?t:null}function eL(e,t){let n=t.CLAUDE_CONFIG_DIR?.trim();return n&&dn.isAbsolute(n)?n:dn.join(e,".claude")}function tL(e){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}function Yv(e){if(!(e===null||e.trim().length===0))try{let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))return;let n=t.enabledPlugins;if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n[Si];return typeof r=="boolean"?r:void 0}catch{return}}function De(e){let t=tL(e.platform),n=[dn.join(t,"managed-settings.json")],r=e.list(dn.join(t,"managed-settings.d"));if(r!==null)for(let a of[...r].sort())a.startsWith(".")||!a.endsWith(".json")||n.push(dn.join(t,"managed-settings.d",a));let o=null;for(let a of n){let c=Yv(e.read(a));c!==void 0&&(o={value:c,file:a})}let i=(()=>{if(o!==null)return{enabled:o.value,source:"managed",file:o.file};let a=dn.join(eL(e.homeDir,e.env),"settings.json"),c=Yv(e.read(a));return c!==void 0?{enabled:c,source:"user",file:a}:{enabled:!1,source:null,file:null}})();return!i.enabled&&Q$(e.env)!==null?{enabled:!0,source:"env",file:null}:i}function Zv(e){return e.source==="env"?` (this process was started by the plugin, ${Xv})`:e.file?` in ${e.file}`:""}function Ka(e){return`Claude Code hooks: provided by the maind plugin (${Si} is enabled${Zv(e)}) \u2014 none written to settings.json`}function Qv(e){return`Claude Code MCP server: provided by the maind plugin (${Si} is enabled${Zv(e)}) \u2014 nothing written to ~/.claude.json, which would start a second maind server`}function Pe(e,t,n){return{homeDir:e,env:t,platform:n,read:s(r=>{try{return Y$(r)?Z$(r,"utf8"):null}catch{return null}},"read"),list:s(r=>{try{return X$(r)}catch{return null}},"list")}}var Si,Xv,oo=w(()=>{"use strict";Si="maind@maind",Xv="MAIND_CLAUDE_PLUGIN";s(Q$,"pluginEnvVersion");s(eL,"claudeConfigDir");s(tL,"managedSettingsDir");s(Yv,"pluginEntryIn");s(De,"maindPluginState");s(Zv,"where");s(Ka,"pluginRowDetail");s(Qv,"pluginMcpRowDetail");s(Pe,"fsPluginProbe")});import*as un from"node:path";import*as tk from"node:readline";import{parse as ek,stringify as nL}from"smol-toml";function Ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ei(e,t){if(!Ce(e)||!Ce(e.hooks))return null;let n=e.hooks.SessionStart;if(!Array.isArray(n))return null;for(let r of n)if(!(!Ce(r)||!Array.isArray(r.hooks))){for(let o of r.hooks)if(Ce(o)&&typeof o.command=="string"&&o.command.includes(t))return o.command}return null}function aL(e,t){let n=un.relative(t,e),r=n!==""&&!n.startsWith("..")&&!un.isAbsolute(n)?`~/${n.split(un.sep).join("/")}`:e;return`hook(${J}):${r}`}async function Rp(e){let t=pi(e.presence.ctx),n=aL(t,e.homeDir),r=s((b,v,k="merge")=>({target:n,action:k,status:b,detail:v}),"row");if(e.skip)return r("skipped","--no-hook","skip");if(e.skipCodex)return r("skipped","--skip-codex","skip");if(!e.explicit&&!Ne(Yr(e.presence.ctx),e.presence.probe))return r("skipped",Yr(e.presence.ctx).skipDetail,"skip");let o;try{o=await q(t)}catch(b){return r("failed",`read: ${Ga(b)}`)}let i={},a=o===null||o.trim().length===0;if(!a)try{let b=ek(o);if(!Ce(b))return r("failed",`${t} is not a TOML table \u2014 left untouched`);i=b}catch(b){return r("failed",`parse: ${Ga(b)} \u2014 ${t} left untouched`)}let c=i.features;if(c!==void 0&&!Ce(c))return r("failed",`[features] in ${t} is not a table \u2014 left untouched`);if(Ce(c)&&(c.hooks===!1||c.codex_hooks===!1))return r("skipped",`hooks are switched off in ${t} ([features] ${c.hooks===!1?"hooks":"codex_hooks"} = false) \u2014 left as it is`,"skip");if(i.hooks!==void 0&&!Ce(i.hooks))return r("failed",`[hooks] in ${t} is not a table \u2014 left untouched`);let l=Ce(i.hooks)?i.hooks.SessionStart:void 0;if(l!==void 0&&!Array.isArray(l))return r("failed",`hooks.SessionStart in ${t} is not an array of tables \u2014 left untouched`);let d=e.launch??we({entryPath:oe(),nodePath:process.execPath,extraArgs:[J,rL],isElectron:process.versions.electron!==void 0}),u=ze(d),p=Ei(i,J)??await cL(e.presence.ctx);if(p!==null){let b=`Codex's SessionStart hook already runs maind ${J}`;return r("skipped",rn(p)?`${b}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${u}`:b,"skip")}if(!e.full){if(!e.isInteractive)return r("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return r(a?"would-create":"would-merge",`${t} (would prompt for consent in real run)`);if(!await(e.prompt??dL)(e.out,`
799
802
  Add a SessionStart hook to ${t}?
800
- ${oL}
801
- [Y/n]: `))return r("skipped","user declined","skip")}let f=Ce(i.hooks)?i.hooks:{},h=Array.isArray(l)?l:[],g={...i,features:{...Ce(c)?c:{},hooks:!0},hooks:{...f,SessionStart:[...h,{hooks:[{type:"command",command:u,timeout:nL,additionalContextLimit:rL}]}]}},y;try{y=eL(g),y.endsWith(`
803
+ ${sL}
804
+ [Y/n]: `))return r("skipped","user declined","skip")}let f=Ce(i.hooks)?i.hooks:{},h=Array.isArray(l)?l:[],g={...i,features:{...Ce(c)?c:{},hooks:!0},hooks:{...f,SessionStart:[...h,{hooks:[{type:"command",command:u,timeout:oL,additionalContextLimit:iL}]}]}},y;try{y=nL(g),y.endsWith(`
802
805
  `)||(y+=`
803
- `);let b=Qv(y),v=aL(b,J);if(v!==1)return r("failed",`expected exactly one ${J} handler after the merge, got ${v}`)}catch(b){return r("failed",`write: ${Ka(b)}`)}let _="Codex runs it after you trust it once: /hooks in Codex";if(e.dryRun)return r(a?"would-create":"would-merge",`${t} \u2014 ${_}`,a?"write":"merge");try{await U(t,y)}catch(b){return r("failed",`write: ${Ka(b)}`)}return r(a?"created":"merged",`${t} \u2014 ${_}`,a?"write":"merge")}async function sL(e){try{let t=await q(un.join(Jr(e),"hooks.json"));if(t===null)return null;let n=JSON.parse(t);return Ei(n,J)}catch{return null}}function aL(e,t){if(!Ce(e)||!Ce(e.hooks)||!Array.isArray(e.hooks.SessionStart))return 0;let n=0;for(let r of e.hooks.SessionStart)if(!(!Ce(r)||!Array.isArray(r.hooks)))for(let o of r.hooks)Ce(o)&&typeof o.command=="string"&&o.command.includes(t)&&n++;return n}async function cL(e,t){e.write(t);let n=ek.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function Ka(e){return e instanceof Error?e.message:String(e)}var tL,nL,rL,oL,Cp=w(()=>{"use strict";ie();_t();Je();Xr();ve();tL="--host=codex",nL=10,rL=4e3,oL="It adds a SessionStart hook to Codex's config.toml \u2014 and `[features] hooks = true`, if that is not set \u2014 that runs 'maind-mcp-bridge on-session-briefing --host=codex' when a Codex session starts (and after a compaction) and returns your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 as `additionalContext`, the JSON Codex documents. 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 'codex' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most session starts add no network call. Every other key in config.toml stays; comments in it do not survive the rewrite (the same as for the MCP entry). Codex runs a new hook only after you trust it: open /hooks in Codex once.";s(Ce,"isObject");s(Ei,"findCodexHookCommand");s(iL,"codexHookTarget");s(Rp,"mergeCodexHook");s(sL,"hooksJsonCommand");s(aL,"countCommands");s(cL,"promptYesNo");s(Ka,"errMessage")});import{createHash as lL}from"node:crypto";import*as Xe from"node:path";import*as nk from"node:readline";function uL(e){return Xe.join(e.homeDir,".copilot","instructions","maind.instructions.md")}function pL(e,t){let n=(e.documentsDirs&&e.documentsDirs.length>0?e.documentsDirs:[Xe.join(e.homeDir,"Documents")]).map(r=>Xe.join(r,"Cline","Rules"));return n.find(r=>t.exists(r))??n[0]}function fL(e){return Xe.join(ma(e),"rules","maind.md")}function ir(e,t){return[{id:"copilot",family:"copilot",label:"GitHub Copilot user instructions",path:uL(e),presence:Mu(e),frontmatter:["name: maind",`description: ${tk}`,'applyTo: "**"'],loads:'VS Code\'s Copilot chat (and the Copilot CLI) adds to every request in every workspace (`applyTo: "**"`)'},{id:"cline",family:"cline",label:"Cline global rule",path:Xe.join(pL(e,t),"maind.md"),presence:Du(e),frontmatter:null,loads:"Cline loads as an always-active global rule in every workspace"},{id:"continue",family:"continue",label:"Continue global rule",path:fL(e),presence:Pu(e),frontmatter:["name: maind",`description: ${tk}`,"alwaysApply: true"],loads:"Continue includes in every workspace (`alwaysApply: true`)"}]}function ok(e){return e==="copilot"||e==="cline"||e==="continue"?e:null}function mL(e,t){return`rules(${e.id}):${hL(e.path,t)}`}function hL(e,t){let n=Xe.relative(t,e);return n!==""&&!n.startsWith("..")&&!Xe.isAbsolute(n)?`~/${n.split(Xe.sep).join("/")}`:e}function Tp(e,t,n){let r=[];e.frontmatter!==null&&r.push("---",...e.frontmatter,"---"),r.push(dL,"",bt.replace(/\r\n/g,`
806
+ `);let b=ek(y),v=lL(b,J);if(v!==1)return r("failed",`expected exactly one ${J} handler after the merge, got ${v}`)}catch(b){return r("failed",`write: ${Ga(b)}`)}let _="Codex runs it after you trust it once: /hooks in Codex";if(e.dryRun)return r(a?"would-create":"would-merge",`${t} \u2014 ${_}`,a?"write":"merge");try{await U(t,y)}catch(b){return r("failed",`write: ${Ga(b)}`)}return r(a?"created":"merged",`${t} \u2014 ${_}`,a?"write":"merge")}async function cL(e){try{let t=await q(un.join(Jr(e),"hooks.json"));if(t===null)return null;let n=JSON.parse(t);return Ei(n,J)}catch{return null}}function lL(e,t){if(!Ce(e)||!Ce(e.hooks)||!Array.isArray(e.hooks.SessionStart))return 0;let n=0;for(let r of e.hooks.SessionStart)if(!(!Ce(r)||!Array.isArray(r.hooks)))for(let o of r.hooks)Ce(o)&&typeof o.command=="string"&&o.command.includes(t)&&n++;return n}async function dL(e,t){e.write(t);let n=tk.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function Ga(e){return e instanceof Error?e.message:String(e)}var rL,oL,iL,sL,Cp=w(()=>{"use strict";ie();_t();Je();Xr();ve();rL="--host=codex",oL=10,iL=4e3,sL="It adds a SessionStart hook to Codex's config.toml \u2014 and `[features] hooks = true`, if that is not set \u2014 that runs 'maind-mcp-bridge on-session-briefing --host=codex' when a Codex session starts (and after a compaction) and returns your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 as `additionalContext`, the JSON Codex documents. 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 'codex' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most session starts add no network call. Every other key in config.toml stays; comments in it do not survive the rewrite (the same as for the MCP entry). Codex runs a new hook only after you trust it: open /hooks in Codex once.";s(Ce,"isObject");s(Ei,"findCodexHookCommand");s(aL,"codexHookTarget");s(Rp,"mergeCodexHook");s(cL,"hooksJsonCommand");s(lL,"countCommands");s(dL,"promptYesNo");s(Ga,"errMessage")});import{createHash as uL}from"node:crypto";import*as Xe from"node:path";import*as rk from"node:readline";function fL(e){return Xe.join(e.homeDir,".copilot","instructions","maind.instructions.md")}function mL(e,t){let n=(e.documentsDirs&&e.documentsDirs.length>0?e.documentsDirs:[Xe.join(e.homeDir,"Documents")]).map(r=>Xe.join(r,"Cline","Rules"));return n.find(r=>t.exists(r))??n[0]}function hL(e){return Xe.join(ha(e),"rules","maind.md")}function ir(e,t){return[{id:"copilot",family:"copilot",label:"GitHub Copilot user instructions",path:fL(e),presence:Mu(e),frontmatter:["name: maind",`description: ${nk}`,'applyTo: "**"'],loads:'VS Code\'s Copilot chat (and the Copilot CLI) adds to every request in every workspace (`applyTo: "**"`)'},{id:"cline",family:"cline",label:"Cline global rule",path:Xe.join(mL(e,t),"maind.md"),presence:Du(e),frontmatter:null,loads:"Cline loads as an always-active global rule in every workspace"},{id:"continue",family:"continue",label:"Continue global rule",path:hL(e),presence:Pu(e),frontmatter:["name: maind",`description: ${nk}`,"alwaysApply: true"],loads:"Continue includes in every workspace (`alwaysApply: true`)"}]}function ik(e){return e==="copilot"||e==="cline"||e==="continue"?e:null}function gL(e,t){return`rules(${e.id}):${yL(e.path,t)}`}function yL(e,t){let n=Xe.relative(t,e);return n!==""&&!n.startsWith("..")&&!Xe.isAbsolute(n)?`~/${n.split(Xe.sep).join("/")}`:e}function Tp(e,t,n){let r=[];e.frontmatter!==null&&r.push("---",...e.frontmatter,"---"),r.push(pL,"",bt.replace(/\r\n/g,`
804
807
  `).trimEnd(),"","### Project conventions","");let o=t.repo??"no repository (organization- and user-wide only)",i=(t.conventions??"").replace(/\r\n/g,`
805
- `).trim();return i.length===0?r.push(`Conventions for ${o}: not loaded yet \u2014 the bridge fills them on the next session start or refresh.`):(r.push(`Conventions for ${o}, refreshed ${gL(n.nowMs)} (mcp-bridge ${n.bridgeVersion}).`,""),r.push(Bu(i,Uu).text)),r.join(`
808
+ `).trim();return i.length===0?r.push(`Conventions for ${o}: not loaded yet \u2014 the bridge fills them on the next session start or refresh.`):(r.push(`Conventions for ${o}, refreshed ${_L(n.nowMs)} (mcp-bridge ${n.bridgeVersion}).`,""),r.push(Bu(i,Uu).text)),r.join(`
806
809
  `)+`
807
- `}function gL(e){return new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}function so(e){let t=e.replace(/^/,"").split(/\r?\n/),n=0;if(t[0]?.trim()==="---"){let r=t.findIndex((o,i)=>i>0&&o.trim()==="---");if(r<0)return!1;n=r+1}for(;n<t.length&&t[n].trim()==="";)n++;return n<t.length&&t[n].trim().startsWith(rk)}function io(e){return e.replace(/\r\n/g,`
810
+ `}function _L(e){return new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}function so(e){let t=e.replace(/^/,"").split(/\r?\n/),n=0;if(t[0]?.trim()==="---"){let r=t.findIndex((o,i)=>i>0&&o.trim()==="---");if(r<0)return!1;n=r+1}for(;n<t.length&&t[n].trim()==="";)n++;return n<t.length&&t[n].trim().startsWith(ok)}function io(e){return e.replace(/\r\n/g,`
808
811
  `).split(`
809
812
  `).map(t=>t.replace(/^(Conventions for .+?), refreshed .*$/,"$1")).join(`
810
- `)}function Ri(e){return lL("sha256").update(io(e)).digest("hex")}function yL(e){return`It writes ${e.path}, a file of the bridge's own that ${e.loads}: the MAIND consultation triggers and the project conventions of the repository you work in, under a line that names that repository and when it was refreshed. The bridge keeps it current \u2014 when a session of this client starts, and when the MAIND extension reports a workspace switch (maind-mcp-bridge refresh-rules) \u2014, at most every 12 h per repository and only when the conventions changed (MAIND_NO_RULES_REFRESH=1 stops that). The conventions come from the same local cache as the session-start hook (~/.maind/guard/briefing-cache.json); a refresh may fetch them from mcp.maind.dev (API key, device id, project key \u2014 never file contents or paths). Nothing is written into your repository. A file of that name without the maind marker is yours and is left untouched.`}async function _L(e,t){let n=mL(t,e.homeDir),r=s((o,i,a="write")=>({target:n,action:a,status:o,detail:i}),"row");if(e.skip)return r("skipped","--no-rules","skip");if(e.explicitFamily!==t.family&&!Ne(t.presence,e.probe))return r("skipped",t.presence.skipDetail,"skip");try{let o=await q(t.path);if(o!==null&&!so(o))return r("skipped",`${t.path} is yours (no maind marker) \u2014 left as it is`,"skip");let i=await e.content(),a=Tp(t,i,{nowMs:e.nowMs??Date.now(),bridgeVersion:e.bridgeVersion??H});if(o!==null)return io(o)===io(a)?(e.dryRun||await e.onChecked?.(t.path,o),r("skipped","already up to date","skip")):e.dryRun?r("would-merge",`${t.path} (would refresh)`,"merge"):(await U(t.path,a),await e.onChecked?.(t.path,a),r("merged",`${t.path} (refreshed)`,"merge"));if(!e.full){if(!e.isInteractive)return r("skipped","consent-required: pass --full to write it non-interactively","skip");if(e.dryRun)return r("would-create",`${t.path} (would prompt for consent in real run)`);if(!await(e.prompt??bL)(e.out,`
813
+ `)}function Ri(e){return uL("sha256").update(io(e)).digest("hex")}function bL(e){return`It writes ${e.path}, a file of the bridge's own that ${e.loads}: the MAIND consultation triggers and the project conventions of the repository you work in, under a line that names that repository and when it was refreshed. The bridge keeps it current \u2014 when a session of this client starts, and when the MAIND extension reports a workspace switch (maind-mcp-bridge refresh-rules) \u2014, at most every 12 h per repository and only when the conventions changed (MAIND_NO_RULES_REFRESH=1 stops that). The conventions come from the same local cache as the session-start hook (~/.maind/guard/briefing-cache.json); a refresh may fetch them from mcp.maind.dev (API key, device id, project key \u2014 never file contents or paths). Nothing is written into your repository. A file of that name without the maind marker is yours and is left untouched.`}async function wL(e,t){let n=gL(t,e.homeDir),r=s((o,i,a="write")=>({target:n,action:a,status:o,detail:i}),"row");if(e.skip)return r("skipped","--no-rules","skip");if(e.explicitFamily!==t.family&&!Ne(t.presence,e.probe))return r("skipped",t.presence.skipDetail,"skip");try{let o=await q(t.path);if(o!==null&&!so(o))return r("skipped",`${t.path} is yours (no maind marker) \u2014 left as it is`,"skip");let i=await e.content(),a=Tp(t,i,{nowMs:e.nowMs??Date.now(),bridgeVersion:e.bridgeVersion??H});if(o!==null)return io(o)===io(a)?(e.dryRun||await e.onChecked?.(t.path,o),r("skipped","already up to date","skip")):e.dryRun?r("would-merge",`${t.path} (would refresh)`,"merge"):(await U(t.path,a),await e.onChecked?.(t.path,a),r("merged",`${t.path} (refreshed)`,"merge"));if(!e.full){if(!e.isInteractive)return r("skipped","consent-required: pass --full to write it non-interactively","skip");if(e.dryRun)return r("would-create",`${t.path} (would prompt for consent in real run)`);if(!await(e.prompt??vL)(e.out,`
811
814
  Write the ${t.label} ${t.path}?
812
- ${yL(t)}
813
- [Y/n]: `))return r("skipped","user declined","skip")}return e.dryRun?r("would-create",t.path):(await U(t.path,a),await e.onChecked?.(t.path,a),r("created",t.path))}catch(o){return r("failed",o instanceof Error?o.message:String(o))}}async function Ap(e,t){let n=[];for(let r of t)n.push(await _L(e,r));return n}async function bL(e,t){e.write(t);let n=nk.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var rk,dL,tk,Ga=w(()=>{"use strict";ba();Fe();Zr();ie();Je();Je();Xr();rk="<!-- maind:rules v1",dL=`${rk} \xB7 written by maind-mcp-bridge (ADR-364): the bridge rewrites this file when it refreshes \u2014 do not edit by hand -->`;s(uL,"copilotInstructionsPath");s(pL,"clineRulesDir");s(fL,"continueRulesPath");tk="MAIND consultation triggers and the project conventions of the repository you work in";s(ir,"ruleChannels");s(ok,"ruleChannelIdForFamily");s(mL,"rulesTargetKey");s(hL,"tildify");s(Tp,"renderRulesFile");s(gL,"stamp");s(so,"isOurRulesFile");s(io,"canonicalRulesContent");s(Ri,"rulesContentHash");s(yL,"ruleConsentDescription");s(_L,"mergeRuleChannel");s(Ap,"mergeRuleChannels");s(bL,"promptYesNo")});async function ik(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let o=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}),i={};try{i=await o.json()}catch{}return o.ok?i.status!=="exchanged"||typeof i.api_key!="string"||!i.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:i.api_key,plan:i.plan??"unknown"}:{ok:!1,reason:i.error??`http_${o.status}`}}catch(o){return o instanceof Error&&o.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:o instanceof Error?o.message:String(o)}}finally{clearTimeout(r)}}var sk=w(()=>{"use strict";s(ik,"exchangeOneClickToken")});async function lk(e){let t="browser-pair";if(e.token!==null)try{let i=wL(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(li(),Jn(i),{apiKey:i,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(i){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:ak(i)}}}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 i=ca(e.bridgeVersion),a=await ik({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:Jb(),clientMeta:{...i}});if(a.ok)return li(),Jn(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,ck(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
814
- `)}let r=n===null?"":` (after exchange failure: ${n})`,o=z();if(o!==null)return{apiKey:o,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 i=await zr(e.bridgeVersion,ck(e));return i===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:i.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${i.plan})${r}`}}}catch(i){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:ak(i)}}}}function wL(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}function ak(e){return e instanceof Error?e.message:String(e)}function ck(e){return e.out??process.stdout}var dk=w(()=>{"use strict";Au();re();sk();s(lk,"pairOrUseToken");s(wL,"validateTokenShape");s(ak,"errMessage");s(ck,"out")});async function uk(e){if(!e.enabled||e.apiKey===null)return;let t=Vr(vL),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:SL(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:xL(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,o=setTimeout(()=>r.abort(),kL);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(o)}}function xL(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}function SL(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}var vL,kL,pk=w(()=>{"use strict";qr();vL="install-completed",kL=3e3;s(uk,"postInstallTelemetry");s(xL,"countStatuses");s(SL,"parseNodeMajor")});function Wa(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function fn(e){return e+1}function Va(e){return(e.text.split(`
815
- `,1)[0]??"").trim().slice(0,200)}function EL(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 RL(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let o=EL(r.childForFieldName("function"));o&&n.add(o)}return[...n]}function Ip(e,t,n,r){for(let o of RL(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:o})}function Ci(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 o=n;for(;o?.type==="member_expression";)o=o.childForFieldName("object");return o?.type==="this"?{name:t,receiver:"this.*"}:o?.type==="identifier"?{name:t,receiver:`${o.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 pn(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 pn(t.childForFieldName("name"));case"parenthesized_type":return pn(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?pn(n[0]):"#"}default:return"#"}}function TL(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Np(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 Ti(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let o=n.childForFieldName("value"),i=pn(n.childForFieldName("type"))??Np(o)??(TL(o)?"#":null);i&&t.set(r.text,i)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let o=pn(n.childForFieldName("type"));o&&t.set(r.text,o)}return t}function mn(e,t,n,r,o={locals:Ti(n)}){let i=new Set,a=s(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(i.has(d))return;i.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?o.thisFields?.get(u.slice(5))??null:o.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",...CL]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(Ci(l.childForFieldName("function")));else if(l.type==="new_expression")a(Ci(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(Ci(d))}}var CL,qa=w(()=>{"use strict";s(Wa,"newResult");s(fn,"line1");s(Va,"signatureOf");s(EL,"calleeName");s(RL,"collectCallTargets");s(Ip,"addCallRefs");s(Ci,"calleeRef");CL=["jsx_opening_element","jsx_self_closing_element"];s(pn,"typeNameOf");s(TL,"isMethodCallResult");s(Np,"newTypeOf");s(Ti,"collectTypeHints");s(mn,"addTsRefs")});function mk(e,t){let n=Wa();for(let r of e.namedChildren)AL(r,t,n);return n}function hk(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function AL(e,t,n){let r=hk(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??NL(r);i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i});return}case"function_definition":{let o=r.childForFieldName("name")?.text;if(!o)return;let i=za(r,t,o,o,"function");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Ip(n,i.nodeKey,a,fk);return}case"class_definition":IL(r,t,n);return;case"expression_statement":{let i=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(i&&i.type==="identifier"){let a=za(r,t,i.text,i.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function IL(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let o=za(e,t,r,r,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let i=e.childForFieldName("superclasses");if(i){for(let c of i.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=hk(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=za(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:o.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&Ip(n,p.nodeKey,f,fk)}}function za(e,t,n,r,o){return{nodeKey:ht(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:fn(e.startPosition.row),endLine:fn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Va(e),doc:null}}function NL(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var fk,gk=w(()=>{"use strict";jn();qa();fk="call";s(mk,"extractPython");s(hk,"unwrapDecorated");s(AL,"handleTopLevel");s(IL,"addClass");s(za,"makeNode");s(NL,"firstDottedName")});function _k(e,t){let n=Wa(),r=t.language!=="typescript";for(let o of e.namedChildren)DL(o,t,n,r);return $L(e,t,n),n}function OL(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function DL(e,t,n,r){if(e.type==="export_statement"&&PL(e,t,n,r))return;let o=OL(e),i=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(o.type){case"import_statement":ML(o,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=yk(o,t,n,"function",r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=FL(o,t,n,r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":Op(o,t,n,"interface");return;case"type_alias_declaration":Op(o,t,n,"type_alias");return;case"enum_declaration":Op(o,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of o.namedChildren){if(a.type!=="variable_declarator")continue;let c=a.childForFieldName("name"),l=a.childForFieldName("value");if(!c||c.type!=="identifier"){l&&mn(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";yk(a,t,n,d?"function":"variable",r,c,l)}return}default:mn(n,t.moduleKey,o,r);return}}function PL(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let o=Pp(e.childForFieldName("source")),i=e.namedChildren.find(l=>l.type==="export_clause"),a=e.namedChildren.find(l=>l.type==="namespace_export");if(o!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:o}),i)for(let l of i.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:o,importedName:d})}else if(a){let l=a.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:o,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:o});return!0}if(i){for(let l of i.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}):mn(n,t.moduleKey,c,r),!0):!1}function ML(e,t,n){let r=Pp(e.childForFieldName("source"));if(r===null)return;let o=e.namedChildren.find(c=>c.type==="import_clause"),i=[],a=s((c,l)=>{i.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of o?.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)}i.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...i)}function $L(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let o=r.childForFieldName("arguments")?.namedChildren[0]??null,i=o?.type==="string"?Pp(o):null;if(i===null)continue;let c=LL(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:i,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:i,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:i,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:i})}}function LL(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function yk(e,t,n,r,o,i,a){let l=(i??e.childForFieldName("name"))?.text;if(!l)return null;let d=Ja(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;mn(n,d.nodeKey,u,o,{locals:Ti(e)})}else a&&mn(n,d.nodeKey,a,o);return d}function Op(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return;let i=Ja(e,t,o,o,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function FL(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return null;let i=Ja(e,t,o,o,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.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:Dp(p)})):[{kind:"extends",ref:Dp(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:f}of u)f&&n.refs.push({fromKey:i.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let c=e.childForFieldName("body");if(!c)return i;let l=jL(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&mn(n,i.nodeKey,g,r,{locals:Ti(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${o}.${u}`,f=Ja(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let h=d.childForFieldName("body");h&&mn(n,f.nodeKey,h,r,{locals:Ti(d),thisFields:l})}return i}function jL(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"),o=pn(n.childForFieldName("type"))??Np(n.childForFieldName("value"));r&&o&&t.set(r.text,o)}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 o=r.childForFieldName("pattern"),i=pn(r.childForFieldName("type"));o?.type==="identifier"&&i&&t.set(o.text,i)}return t}function Ja(e,t,n,r,o){return{nodeKey:ht(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:fn(e.startPosition.row),endLine:fn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Va(e),doc:null}}function Dp(e){if(!e)return null;switch(e.type){case"generic_type":return Dp(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 Ci(e);default:return null}}function Pp(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var bk=w(()=>{"use strict";jn();qa();s(_k,"extractTypescript");s(OL,"unwrapExport");s(DL,"handleTopLevel");s(PL,"handleExportForm");s(ML,"addImport");s($L,"collectDynamicImports");s(LL,"enclosingDeclarator");s(yk,"addFunctionLike");s(Op,"addSimpleNamed");s(FL,"addClass");s(jL,"classFieldTypes");s(Ja,"makeNode");s(Dp,"heritageRef");s(Pp,"stringValue")});import{createRequire as HL}from"node:module";import{join as UL}from"node:path";function kk(e,t){return t?UL(t,wk[e]):HL(import.meta.url).resolve(`tree-sitter-wasms/out/${wk[e]}`)}var wk,vk,xk=w(()=>{"use strict";wk={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},vk="tree-sitter.wasm";s(kk,"grammarPath")});import{join as BL}from"node:path";import Mp from"web-tree-sitter";var KL,Ya,Sk=w(()=>{"use strict";jn();Is();gk();bk();qa();xk();KL=["typescript","tsx","javascript","python"],Ya=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Mp.init(this.assetDir?{locateFile:s(t=>BL(this.assetDir,t||vk),"locateFile")}:void 0),this.parser=new Mp,this.initialized=!0)}supports(t){return KL.includes(t)}async parse(t,n,r){await this.init();let o=this.parser;o.setLanguage(await this.grammar(r));let i=o.parse(n);if(!i)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=i.rootNode,c=mt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:fn(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?mk(a,d):_k(a,d);return i.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 Mp.Language.load(kk(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as GL}from"node:module";function Ek(){return Xa("node:sqlite")}function ao(){if(Ai)return Ai;try{let{DatabaseSync:e}=Ek(),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(),Ai={ok:!0}}finally{t.close()}}catch(e){Ai={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Ai}function WL(e){let{DatabaseSync:t}=Ek(),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(o){try{n.exec("ROLLBACK")}catch{}throw o}},"transaction")}}function VL(e){let t=Xa("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 Rk(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Za(e){let t=Rk(),n=s(()=>{let{DatabaseSync:o}=Xa("node:sqlite"),i=new o(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>i.exec(a),"exec"),close:s(()=>i.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let o=Xa("better-sqlite3"),i=new o(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>{i.exec(a)},"exec"),close:s(()=>{i.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(o){try{return r()}catch(i){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(o)}); better-sqlite3 (${a(i)})`)}}}function Qa(e){let t=Rk(),n=s(o=>{let i=o==="node:sqlite"?WL(e):VL(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:o}},"openAs");if(t==="builtin"){let o=ao();if(!o.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${o.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=ao();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${i})`)}}var Xa,Ai,ec=w(()=>{"use strict";Xa=GL(import.meta.url);s(Ek,"loadBuiltin");Ai=null;s(ao,"probeBuiltinSqlite");s(WL,"openBuiltin");s(VL,"openBetter");s(Rk,"backendOverride");s(Za,"openSqliteReadOnly");s(Qa,"openSqliteDatabase")});function Pk(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 Mk(e,t,n,r){let o=new Map;for(let a of e)o.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let i=s(a=>o.get(String(a.file_path)),"entry");for(let a of t)i(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:sr(a.receiver),receiverType:sr(a.receiver_type)});for(let a of n){let c=i(a);if(!c)continue;let l={fromModuleKey:mt(c.filePath),specifier:String(a.specifier),importedName:sr(a.imported_name),localName:sr(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:sr(a.local_name),specifier:sr(a.specifier),importedName:sr(a.imported_name)};i(a)?.exports.push(c)}return[...o.values()]}var Ck,Tk,Ak,Ik,Nk,Ok,Dk,sr,$k=w(()=>{"use strict";jn();Ck=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Tk="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Ak="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Ik="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Nk="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Ok="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Dk="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(Pk,"factRows");sr=s(e=>e==null?null:String(e),"str");s(Mk,"assembleFacts")});function tc(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 Lk,Ii,Fk=w(()=>{"use strict";ec();Kr();$k();iu();s(tc,"toNodeRow");Lk=400,Ii=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Qa(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(tu)}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,o){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(o){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let h of o.contains)l.run(h.srcKey,h.dstKey,h.kind);let d=Pk(t.path,o),u=this.db.prepare(Tk);for(let h of d.refs)u.run(...h);let p=this.db.prepare(Ak);for(let h of d.imports)p.run(...h);let f=this.db.prepare(Ik);for(let h of d.exports)f.run(...h)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return Mk(t,this.db.prepare(Nk).all(),this.db.prepare(Ok).all(),this.db.prepare(Dk).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 o of t)r.run(o.srcKey,o.dstKey,o.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let o=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)o.run(a);let i=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)i.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?tc(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(tc)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(tc)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(tc)}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 o of t){let i=Buffer.from(o.vec.buffer,o.vec.byteOffset,o.vec.byteLength);n.run(o.nodeKey,o.dim,i,o.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 o=yb(t);if(!o)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
815
+ ${bL(t)}
816
+ [Y/n]: `))return r("skipped","user declined","skip")}return e.dryRun?r("would-create",t.path):(await U(t.path,a),await e.onChecked?.(t.path,a),r("created",t.path))}catch(o){return r("failed",o instanceof Error?o.message:String(o))}}async function Ap(e,t){let n=[];for(let r of t)n.push(await wL(e,r));return n}async function vL(e,t){e.write(t);let n=rk.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var ok,pL,nk,Wa=w(()=>{"use strict";wa();Fe();Zr();ie();Je();Je();Xr();ok="<!-- maind:rules v1",pL=`${ok} \xB7 written by maind-mcp-bridge (ADR-364): the bridge rewrites this file when it refreshes \u2014 do not edit by hand -->`;s(fL,"copilotInstructionsPath");s(mL,"clineRulesDir");s(hL,"continueRulesPath");nk="MAIND consultation triggers and the project conventions of the repository you work in";s(ir,"ruleChannels");s(ik,"ruleChannelIdForFamily");s(gL,"rulesTargetKey");s(yL,"tildify");s(Tp,"renderRulesFile");s(_L,"stamp");s(so,"isOurRulesFile");s(io,"canonicalRulesContent");s(Ri,"rulesContentHash");s(bL,"ruleConsentDescription");s(wL,"mergeRuleChannel");s(Ap,"mergeRuleChannels");s(vL,"promptYesNo")});async function sk(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let o=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}),i={};try{i=await o.json()}catch{}return o.ok?i.status!=="exchanged"||typeof i.api_key!="string"||!i.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:i.api_key,plan:i.plan??"unknown"}:{ok:!1,reason:i.error??`http_${o.status}`}}catch(o){return o instanceof Error&&o.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:o instanceof Error?o.message:String(o)}}finally{clearTimeout(r)}}var ak=w(()=>{"use strict";s(sk,"exchangeOneClickToken")});async function dk(e){let t="browser-pair";if(e.token!==null)try{let i=kL(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(li(),Jn(i),{apiKey:i,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(i){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:ck(i)}}}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 i=la(e.bridgeVersion),a=await sk({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:Yb(),clientMeta:{...i}});if(a.ok)return li(),Jn(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,lk(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
817
+ `)}let r=n===null?"":` (after exchange failure: ${n})`,o=z();if(o!==null)return{apiKey:o,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 i=await zr(e.bridgeVersion,lk(e));return i===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:i.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${i.plan})${r}`}}}catch(i){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:ck(i)}}}}function kL(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}function ck(e){return e instanceof Error?e.message:String(e)}function lk(e){return e.out??process.stdout}var uk=w(()=>{"use strict";Au();re();ak();s(dk,"pairOrUseToken");s(kL,"validateTokenShape");s(ck,"errMessage");s(lk,"out")});async function pk(e){if(!e.enabled||e.apiKey===null)return;let t=Vr(xL),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:RL(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:EL(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,o=setTimeout(()=>r.abort(),SL);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(o)}}function EL(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}function RL(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}var xL,SL,fk=w(()=>{"use strict";qr();xL="install-completed",SL=3e3;s(pk,"postInstallTelemetry");s(EL,"countStatuses");s(RL,"parseNodeMajor")});function Va(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function fn(e){return e+1}function qa(e){return(e.text.split(`
818
+ `,1)[0]??"").trim().slice(0,200)}function CL(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 TL(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let o=CL(r.childForFieldName("function"));o&&n.add(o)}return[...n]}function Ip(e,t,n,r){for(let o of TL(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:o})}function Ci(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 o=n;for(;o?.type==="member_expression";)o=o.childForFieldName("object");return o?.type==="this"?{name:t,receiver:"this.*"}:o?.type==="identifier"?{name:t,receiver:`${o.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 pn(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 pn(t.childForFieldName("name"));case"parenthesized_type":return pn(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?pn(n[0]):"#"}default:return"#"}}function IL(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Np(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 Ti(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let o=n.childForFieldName("value"),i=pn(n.childForFieldName("type"))??Np(o)??(IL(o)?"#":null);i&&t.set(r.text,i)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let o=pn(n.childForFieldName("type"));o&&t.set(r.text,o)}return t}function mn(e,t,n,r,o={locals:Ti(n)}){let i=new Set,a=s(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(i.has(d))return;i.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?o.thisFields?.get(u.slice(5))??null:o.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",...AL]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(Ci(l.childForFieldName("function")));else if(l.type==="new_expression")a(Ci(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(Ci(d))}}var AL,za=w(()=>{"use strict";s(Va,"newResult");s(fn,"line1");s(qa,"signatureOf");s(CL,"calleeName");s(TL,"collectCallTargets");s(Ip,"addCallRefs");s(Ci,"calleeRef");AL=["jsx_opening_element","jsx_self_closing_element"];s(pn,"typeNameOf");s(IL,"isMethodCallResult");s(Np,"newTypeOf");s(Ti,"collectTypeHints");s(mn,"addTsRefs")});function hk(e,t){let n=Va();for(let r of e.namedChildren)NL(r,t,n);return n}function gk(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function NL(e,t,n){let r=gk(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??DL(r);i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i});return}case"function_definition":{let o=r.childForFieldName("name")?.text;if(!o)return;let i=Ja(r,t,o,o,"function");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Ip(n,i.nodeKey,a,mk);return}case"class_definition":OL(r,t,n);return;case"expression_statement":{let i=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(i&&i.type==="identifier"){let a=Ja(r,t,i.text,i.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function OL(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let o=Ja(e,t,r,r,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let i=e.childForFieldName("superclasses");if(i){for(let c of i.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=gk(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=Ja(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:o.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&Ip(n,p.nodeKey,f,mk)}}function Ja(e,t,n,r,o){return{nodeKey:ht(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:fn(e.startPosition.row),endLine:fn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:qa(e),doc:null}}function DL(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var mk,yk=w(()=>{"use strict";jn();za();mk="call";s(hk,"extractPython");s(gk,"unwrapDecorated");s(NL,"handleTopLevel");s(OL,"addClass");s(Ja,"makeNode");s(DL,"firstDottedName")});function bk(e,t){let n=Va(),r=t.language!=="typescript";for(let o of e.namedChildren)ML(o,t,n,r);return FL(e,t,n),n}function PL(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function ML(e,t,n,r){if(e.type==="export_statement"&&$L(e,t,n,r))return;let o=PL(e),i=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(o.type){case"import_statement":LL(o,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=_k(o,t,n,"function",r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=HL(o,t,n,r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":Op(o,t,n,"interface");return;case"type_alias_declaration":Op(o,t,n,"type_alias");return;case"enum_declaration":Op(o,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of o.namedChildren){if(a.type!=="variable_declarator")continue;let c=a.childForFieldName("name"),l=a.childForFieldName("value");if(!c||c.type!=="identifier"){l&&mn(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";_k(a,t,n,d?"function":"variable",r,c,l)}return}default:mn(n,t.moduleKey,o,r);return}}function $L(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let o=Pp(e.childForFieldName("source")),i=e.namedChildren.find(l=>l.type==="export_clause"),a=e.namedChildren.find(l=>l.type==="namespace_export");if(o!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:o}),i)for(let l of i.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:o,importedName:d})}else if(a){let l=a.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:o,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:o});return!0}if(i){for(let l of i.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}):mn(n,t.moduleKey,c,r),!0):!1}function LL(e,t,n){let r=Pp(e.childForFieldName("source"));if(r===null)return;let o=e.namedChildren.find(c=>c.type==="import_clause"),i=[],a=s((c,l)=>{i.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of o?.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)}i.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...i)}function FL(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let o=r.childForFieldName("arguments")?.namedChildren[0]??null,i=o?.type==="string"?Pp(o):null;if(i===null)continue;let c=jL(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:i,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:i,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:i,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:i})}}function jL(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function _k(e,t,n,r,o,i,a){let l=(i??e.childForFieldName("name"))?.text;if(!l)return null;let d=Ya(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;mn(n,d.nodeKey,u,o,{locals:Ti(e)})}else a&&mn(n,d.nodeKey,a,o);return d}function Op(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return;let i=Ya(e,t,o,o,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function HL(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return null;let i=Ya(e,t,o,o,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.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:Dp(p)})):[{kind:"extends",ref:Dp(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:f}of u)f&&n.refs.push({fromKey:i.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let c=e.childForFieldName("body");if(!c)return i;let l=UL(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&mn(n,i.nodeKey,g,r,{locals:Ti(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${o}.${u}`,f=Ya(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let h=d.childForFieldName("body");h&&mn(n,f.nodeKey,h,r,{locals:Ti(d),thisFields:l})}return i}function UL(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"),o=pn(n.childForFieldName("type"))??Np(n.childForFieldName("value"));r&&o&&t.set(r.text,o)}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 o=r.childForFieldName("pattern"),i=pn(r.childForFieldName("type"));o?.type==="identifier"&&i&&t.set(o.text,i)}return t}function Ya(e,t,n,r,o){return{nodeKey:ht(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:fn(e.startPosition.row),endLine:fn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:qa(e),doc:null}}function Dp(e){if(!e)return null;switch(e.type){case"generic_type":return Dp(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 Ci(e);default:return null}}function Pp(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var wk=w(()=>{"use strict";jn();za();s(bk,"extractTypescript");s(PL,"unwrapExport");s(ML,"handleTopLevel");s($L,"handleExportForm");s(LL,"addImport");s(FL,"collectDynamicImports");s(jL,"enclosingDeclarator");s(_k,"addFunctionLike");s(Op,"addSimpleNamed");s(HL,"addClass");s(UL,"classFieldTypes");s(Ya,"makeNode");s(Dp,"heritageRef");s(Pp,"stringValue")});import{createRequire as BL}from"node:module";import{join as KL}from"node:path";function xk(e,t){return t?KL(t,vk[e]):BL(import.meta.url).resolve(`tree-sitter-wasms/out/${vk[e]}`)}var vk,kk,Sk=w(()=>{"use strict";vk={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},kk="tree-sitter.wasm";s(xk,"grammarPath")});import{join as GL}from"node:path";import Mp from"web-tree-sitter";var WL,Xa,Ek=w(()=>{"use strict";jn();Is();yk();wk();za();Sk();WL=["typescript","tsx","javascript","python"],Xa=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Mp.init(this.assetDir?{locateFile:s(t=>GL(this.assetDir,t||kk),"locateFile")}:void 0),this.parser=new Mp,this.initialized=!0)}supports(t){return WL.includes(t)}async parse(t,n,r){await this.init();let o=this.parser;o.setLanguage(await this.grammar(r));let i=o.parse(n);if(!i)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=i.rootNode,c=mt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:fn(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?hk(a,d):bk(a,d);return i.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 Mp.Language.load(xk(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as VL}from"node:module";function Rk(){return Za("node:sqlite")}function ao(){if(Ai)return Ai;try{let{DatabaseSync:e}=Rk(),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(),Ai={ok:!0}}finally{t.close()}}catch(e){Ai={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Ai}function qL(e){let{DatabaseSync:t}=Rk(),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(o){try{n.exec("ROLLBACK")}catch{}throw o}},"transaction")}}function zL(e){let t=Za("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 Ck(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Qa(e){let t=Ck(),n=s(()=>{let{DatabaseSync:o}=Za("node:sqlite"),i=new o(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>i.exec(a),"exec"),close:s(()=>i.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let o=Za("better-sqlite3"),i=new o(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>{i.exec(a)},"exec"),close:s(()=>{i.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(o){try{return r()}catch(i){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(o)}); better-sqlite3 (${a(i)})`)}}}function ec(e){let t=Ck(),n=s(o=>{let i=o==="node:sqlite"?qL(e):zL(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:o}},"openAs");if(t==="builtin"){let o=ao();if(!o.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${o.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=ao();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${i})`)}}var Za,Ai,tc=w(()=>{"use strict";Za=VL(import.meta.url);s(Rk,"loadBuiltin");Ai=null;s(ao,"probeBuiltinSqlite");s(qL,"openBuiltin");s(zL,"openBetter");s(Ck,"backendOverride");s(Qa,"openSqliteReadOnly");s(ec,"openSqliteDatabase")});function Mk(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 $k(e,t,n,r){let o=new Map;for(let a of e)o.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let i=s(a=>o.get(String(a.file_path)),"entry");for(let a of t)i(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:sr(a.receiver),receiverType:sr(a.receiver_type)});for(let a of n){let c=i(a);if(!c)continue;let l={fromModuleKey:mt(c.filePath),specifier:String(a.specifier),importedName:sr(a.imported_name),localName:sr(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:sr(a.local_name),specifier:sr(a.specifier),importedName:sr(a.imported_name)};i(a)?.exports.push(c)}return[...o.values()]}var Tk,Ak,Ik,Nk,Ok,Dk,Pk,sr,Lk=w(()=>{"use strict";jn();Tk=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Ak="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Ik="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Nk="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Ok="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Dk="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Pk="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(Mk,"factRows");sr=s(e=>e==null?null:String(e),"str");s($k,"assembleFacts")});function nc(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 Fk,Ii,jk=w(()=>{"use strict";tc();Kr();Lk();iu();s(nc,"toNodeRow");Fk=400,Ii=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=ec(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(tu)}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,o){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(o){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let h of o.contains)l.run(h.srcKey,h.dstKey,h.kind);let d=Mk(t.path,o),u=this.db.prepare(Ak);for(let h of d.refs)u.run(...h);let p=this.db.prepare(Ik);for(let h of d.imports)p.run(...h);let f=this.db.prepare(Nk);for(let h of d.exports)f.run(...h)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return $k(t,this.db.prepare(Ok).all(),this.db.prepare(Dk).all(),this.db.prepare(Pk).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 o of t)r.run(o.srcKey,o.dstKey,o.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let o=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)o.run(a);let i=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)i.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?nc(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(nc)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(nc)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(nc)}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 o of t){let i=Buffer.from(o.vec.buffer,o.vec.byteOffset,o.vec.byteLength);n.run(o.nodeKey,o.dim,i,o.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 o=_b(t);if(!o)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
816
819
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
817
820
  WHERE nodes_fts MATCH ? AND n.kind = ?
818
821
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
@@ -825,7 +828,7 @@ ${yL(t)}
825
828
  FROM nodes n
826
829
  WHERE n.kind = 'module'
827
830
  ORDER BY imports_in DESC, symbol_count DESC
828
- 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(i=>i.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),o=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let i=0;i<n.length;i+=Lk)for(let a of n.slice(i,i+Lk))r.run(a),o.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let i of Ck)this.db.prepare(i).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
831
+ 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(i=>i.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),o=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let i=0;i<n.length;i+=Fk)for(let a of n.slice(i,i+Fk))r.run(a),o.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let i of Tk)this.db.prepare(i).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
829
832
  node_key, kind, name, qualified_name, file_path, language,
830
833
  start_line, end_line, start_byte, end_byte, signature, doc
831
834
  ) 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)
@@ -835,110 +838,110 @@ ${yL(t)}
835
838
  content_hash = excluded.content_hash,
836
839
  mtime_ms = excluded.mtime_ms,
837
840
  size = excluded.size,
838
- indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as qL}from"node:crypto";function co(e){return qL("sha256").update(e,"utf8").digest("hex")}function jk(e){return{node_key_hash:co(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:co(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?co(e.signature):null}}function Hk(e){return{src_key_hash:co(e.srcKey),dst_key_hash:co(e.dstKey),kind:e.kind}}function Uk(e,t,n){return{node_key_hash:co(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Bk=w(()=>{"use strict";s(co,"sha256");s(jk,"toCloudNode");s(Hk,"toCloudEdge");s(Uk,"toCloudEmbedding")});import{randomUUID as zL}from"node:crypto";function $p(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Kk(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Gk(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var lo,uo,JL,Lp=w(()=>{"use strict";Kr();Bk();lo=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},uo=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(Ur),lastSyncedAt:Kk(await this.store.getMeta(ru))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(jk),n=(await this.store.getAllEdges()).map(Hk),r=await this.store.getMeta(Qt)??Zt,o=await this.store.getMeta(Ur),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=zL(),l={project_key:this.cfg.projectKey,head_commit:o,schema_version:r,file_count:i,lang_dist:a},d=0,u=$p(t,this.chunk),p=$p(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 h=t.map(_=>_.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:h,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ru,String(Date.now())),o&&await this.store.setMeta(hb,o),{nodes:t.length,edges:n.length,pruned:Gk(g.nodes_deleted),edgesPruned:Gk(g.edges_deleted),embeddings:y,headCommit:o}}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}),i=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Uk(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&i[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=$p(a,JL),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(Ys),n=await this.store.getMeta(Xs),r=Kk(await this.store.getMeta(Zs));if(!t||!n||!r)throw new lo("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(()=>""),o=null;try{o=r?JSON.parse(r):null}catch{o=null}if(!t.ok||!o||o.ok!==!0){let i=o?.error;throw new lo(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return o}},JL=250;s($p,"chunkArray");s(Kk,"numOrNull");s(Gk,"numOr0")});var jp={};Z(jp,{CodeIndexSync:()=>uo,DEFAULT_DB_RELPATH:()=>Fp,SyncError:()=>lo,createCodeIndexSync:()=>XL,createNodeCodeIndex:()=>rc,openIndexReader:()=>ZL,openSqliteDatabase:()=>Qa,openSqliteReadOnly:()=>Za,probeBuiltinSqlite:()=>ao});import{mkdirSync as YL}from"node:fs";import{posix as nc}from"node:path";function rc(e){let t=e.dbPath??nc.join(e.repoRoot,Fp);YL(nc.dirname(t),{recursive:!0}),e.dbPath===void 0&&Go(nc.dirname(t));let n=new Ii(t),r=new Ya;return new ii({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function XL(e){let t=e.dbPath??nc.join(e.repoRoot,Fp),n=e.projectKey??c_(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 Ii(t);return new uo(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function ZL(e){return pu(Za(e).db)}var Fp,oc=w(()=>{"use strict";hd();Sk();su();fu();Fk();ec();Lp();Os();Lp();ec();Fp=".maind/code-index.sqlite";s(rc,"createNodeCodeIndex");s(XL,"createCodeIndexSync");s(ZL,"openIndexReader")});import{execFileSync as Wk}from"node:child_process";import{existsSync as Vk,realpathSync as qk}from"node:fs";import{createRequire as QL}from"node:module";import{basename as eF,dirname as tF,isAbsolute as zk,join as nF,relative as Jk,resolve as ic,sep as Yk}from"node:path";function sc(){let e=ao();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return QL(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 Xk(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 Me(e=process.cwd()){try{let t=Wk("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 Qk(e,t=Me(),n=process.cwd()){let r=zk(e)?[e]:[ic(t,e),ic(n,e)];for(let o of r){let i=tF(o);if(!Vk(i))continue;let a;try{a=qk(i)}catch{continue}let c=ex(a);if(c===null)continue;let l=Jk(c,nF(a,eF(o)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Yk).join("/")}}return null}function po(e,t=Me(),n=process.cwd()){let r=zk(e)?[e]:[ic(t,e),ic(n,e)];for(let o of r){if(!Vk(o))continue;let i;try{i=qk(o)}catch{continue}let a=ex(i);if(a===null)continue;let c=Jk(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Yk).join("/")}}return null}function ex(e){try{let t=Wk("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 tx(){return rc({repoRoot:Me()})}function nx(e){return rc({repoRoot:e})}var Zk,hn=w(()=>{"use strict";oc();s(sc,"probeNativeStore");s(Xk,"isNativeStoreUnavailable");Zk="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(Me,"resolveRepoRoot");s(Qk,"resolveRepoRootForPath");s(po,"resolveRepoRootForDir");s(ex,"gitToplevelOf");s(tx,"defaultEngineFactory");s(nx,"engineForRoot")});async function ar(e){return Lt("get_session_briefing",{tools:["claude-code"]},e)}async function Lt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Ni,o=new AbortController,i=setTimeout(()=>o.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:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:rF,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 rx(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:o.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(_=>_.text().catch(()=>"")).catch(()=>"");let p=await fetch(r,{method:"POST",headers:u,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!p.ok)return null;let h=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await rx(p):await p.text();if(h.trim().length===0)return null;let g=JSON.parse(h);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(i)}}async function rx(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i="",a=s(()=>{if(o.length===0)return;let c=o.join(`
841
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as JL}from"node:crypto";function co(e){return JL("sha256").update(e,"utf8").digest("hex")}function Hk(e){return{node_key_hash:co(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:co(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?co(e.signature):null}}function Uk(e){return{src_key_hash:co(e.srcKey),dst_key_hash:co(e.dstKey),kind:e.kind}}function Bk(e,t,n){return{node_key_hash:co(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Kk=w(()=>{"use strict";s(co,"sha256");s(Hk,"toCloudNode");s(Uk,"toCloudEdge");s(Bk,"toCloudEmbedding")});import{randomUUID as YL}from"node:crypto";function $p(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Gk(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Wk(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var lo,uo,XL,Lp=w(()=>{"use strict";Kr();Kk();lo=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},uo=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(Ur),lastSyncedAt:Gk(await this.store.getMeta(ru))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Hk),n=(await this.store.getAllEdges()).map(Uk),r=await this.store.getMeta(Qt)??Zt,o=await this.store.getMeta(Ur),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=YL(),l={project_key:this.cfg.projectKey,head_commit:o,schema_version:r,file_count:i,lang_dist:a},d=0,u=$p(t,this.chunk),p=$p(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 h=t.map(_=>_.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:h,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ru,String(Date.now())),o&&await this.store.setMeta(gb,o),{nodes:t.length,edges:n.length,pruned:Wk(g.nodes_deleted),edgesPruned:Wk(g.edges_deleted),embeddings:y,headCommit:o}}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}),i=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Bk(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&i[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=$p(a,XL),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(Xs),n=await this.store.getMeta(Zs),r=Gk(await this.store.getMeta(Qs));if(!t||!n||!r)throw new lo("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(()=>""),o=null;try{o=r?JSON.parse(r):null}catch{o=null}if(!t.ok||!o||o.ok!==!0){let i=o?.error;throw new lo(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return o}},XL=250;s($p,"chunkArray");s(Gk,"numOrNull");s(Wk,"numOr0")});var jp={};Z(jp,{CodeIndexSync:()=>uo,DEFAULT_DB_RELPATH:()=>Fp,SyncError:()=>lo,createCodeIndexSync:()=>QL,createNodeCodeIndex:()=>oc,openIndexReader:()=>eF,openSqliteDatabase:()=>ec,openSqliteReadOnly:()=>Qa,probeBuiltinSqlite:()=>ao});import{mkdirSync as ZL}from"node:fs";import{posix as rc}from"node:path";function oc(e){let t=e.dbPath??rc.join(e.repoRoot,Fp);ZL(rc.dirname(t),{recursive:!0}),e.dbPath===void 0&&Go(rc.dirname(t));let n=new Ii(t),r=new Xa;return new ii({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function QL(e){let t=e.dbPath??rc.join(e.repoRoot,Fp),n=e.projectKey??l_(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 Ii(t);return new uo(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function eF(e){return pu(Qa(e).db)}var Fp,ic=w(()=>{"use strict";hd();Ek();su();fu();jk();tc();Lp();Os();Lp();tc();Fp=".maind/code-index.sqlite";s(oc,"createNodeCodeIndex");s(QL,"createCodeIndexSync");s(eF,"openIndexReader")});import{execFileSync as Vk}from"node:child_process";import{existsSync as qk,realpathSync as zk}from"node:fs";import{createRequire as tF}from"node:module";import{basename as nF,dirname as rF,isAbsolute as Jk,join as oF,relative as Yk,resolve as sc,sep as Xk}from"node:path";function ac(){let e=ao();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return tF(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 Zk(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 Me(e=process.cwd()){try{let t=Vk("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 ex(e,t=Me(),n=process.cwd()){let r=Jk(e)?[e]:[sc(t,e),sc(n,e)];for(let o of r){let i=rF(o);if(!qk(i))continue;let a;try{a=zk(i)}catch{continue}let c=tx(a);if(c===null)continue;let l=Yk(c,oF(a,nF(o)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Xk).join("/")}}return null}function po(e,t=Me(),n=process.cwd()){let r=Jk(e)?[e]:[sc(t,e),sc(n,e)];for(let o of r){if(!qk(o))continue;let i;try{i=zk(o)}catch{continue}let a=tx(i);if(a===null)continue;let c=Yk(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Xk).join("/")}}return null}function tx(e){try{let t=Vk("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 nx(){return oc({repoRoot:Me()})}function rx(e){return oc({repoRoot:e})}var Qk,hn=w(()=>{"use strict";ic();s(ac,"probeNativeStore");s(Zk,"isNativeStoreUnavailable");Qk="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(Me,"resolveRepoRoot");s(ex,"resolveRepoRootForPath");s(po,"resolveRepoRootForDir");s(tx,"gitToplevelOf");s(nx,"defaultEngineFactory");s(rx,"engineForRoot")});async function ar(e){return Ft("get_session_briefing",{tools:["claude-code"]},e)}async function Ft(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Ni,o=new AbortController,i=setTimeout(()=>o.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:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:iF,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 ox(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:o.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(_=>_.text().catch(()=>"")).catch(()=>"");let p=await fetch(r,{method:"POST",headers:u,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!p.ok)return null;let h=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await ox(p):await p.text();if(h.trim().length===0)return null;let g=JSON.parse(h);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(i)}}async function ox(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i="",a=s(()=>{if(o.length===0)return;let c=o.join(`
839
842
  `).trim();o=[],c.length>0&&(i=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(`
840
- `))!==-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/,""))}}return a(),i}var Ni,rF,gn=w(()=>{"use strict";Ni="https://mcp.maind.dev/mcp",rF="2025-06-18";s(ar,"fetchSessionBriefing");s(Lt,"fetchToolText");s(rx,"readSseMessage")});function ox(e){try{let t=Buffer.concat(e).toString("utf-8").trim();if(!t)return{};let n=JSON.parse(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}async function V(){let e=process.stdin;if(e.isTTY)return{};let t=[],n=0;return await new Promise(r=>{let o=!1,i,a=s(l=>{o||(o=!0,clearTimeout(i),r(l))},"settle"),c=s(l=>{clearTimeout(i),i=setTimeout(()=>{let d=n;setImmediate(()=>{o||n!==d||a(ox(t))})},l)},"arm");c(1e3),e.on("data",l=>{o||(t.push(typeof l=="string"?Buffer.from(l,"utf-8"):l),n+=1,c(200))}),e.on("end",()=>a(ox(t))),e.on("error",()=>a({}))})}function fo(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Ze(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var ke=w(()=>{"use strict";s(ox,"parsePayload");s(V,"readHookInput");s(fo,"transcriptPathOf");s(Ze,"toolFilePathOf")});function cr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function lr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function Oi(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function ac(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Hp(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Di=w(()=>{"use strict";s(cr,"denyPayload");s(lr,"advisoryPayload");s(Oi,"postAdvisoryPayload");s(ac,"postFailureAdvisoryPayload");s(Hp,"promptAdvisoryPayload")});function oF(e){return yn(e)&&/[\\/]\.claude[^\\/]*[\\/]projects[\\/]/.test(e)}function iF(e){return yn(e)&&/[\\/]sessions[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/]rollout-[^\\/]+\.jsonl$/.test(e)}function ix(e){for(let t of e)if(t==="--host=codex")return"codex";return null}function Pi(e,t=process.env,n=null){return n==="codex"?"codex":yn(e.cursor_version)?"cursor":oF(e.transcript_path)?"claude-code":iF(e.transcript_path)?"codex":yn(t.CURSOR_VERSION)?"cursor":yn(t.DEVIN_PROJECT_DIR)?"devin":yn(t.CLAUDE_PROJECT_DIR)||t.CLAUDECODE==="1"?"claude-code":"unknown"}function sx(e,t=process.env){return Pi(e,t)==="cursor"}function _n(e){return e==="cursor"||e==="devin"||e==="codex"}function st(e,t=process.env){return _n(Pi(e,t))}function sF(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 de(e,t=process.env,n=Q,r=null){let o=Pi(e,t,r);return{host:o,devinOutput:o==="devin"?sF(t,n()):!1}}function aF(e){switch(e.kind){case"text":return e.text;case"deny":return cr(e.reason);case"context":switch(e.event){case"UserPromptSubmit":return Hp(e.text);case"PreToolUse":return lr(e.text);case"PostToolUse":return Oi(e.text);case"PostToolUseFailure":return ac(e.text)}}}function cF(e){return e.kind==="deny"?JSON.stringify({permission:"deny",user_message:e.reason,agent_message:e.reason}):null}function lF(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"?Hp(e.text):e.event==="PostToolUse"?Oi(e.text):null}}function dF(e){return e.kind!=="text"?null:JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.text.replace(/\s+$/,"")}})}function me(e,t){switch(e.host){case"claude-code":case"unknown":return aF(t);case"cursor":return cF(t);case"devin":return e.devinOutput?lF(t):null;case"codex":return dF(t)}}function xe(e,t){let n=t.kind==="deny"?{kind:"deny",reason:"x"}:{...t,text:"x"};return me(e,n)!==null}function cc(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}function lc(e,t=process.env){return e.host==="devin"&&yn(t.DEVIN_PROJECT_DIR)?t.DEVIN_PROJECT_DIR.trim():e.host==="cursor"&&yn(t.CURSOR_PROJECT_DIR)?t.CURSOR_PROJECT_DIR.trim():null}var yn,$e=w(()=>{"use strict";Ue();Di();yn=s(e=>typeof e=="string"&&e.trim().length>0,"filled");s(oF,"isClaudeCodeTranscript");s(iF,"isCodexTranscript");s(ix,"hostHintFromArgv");s(Pi,"detectHookHost");s(sx,"runsUnderCursor");s(_n,"isForeignHost");s(st,"guardStandsDown");s(sF,"devinOutputEnabled");s(de,"resolveHookTarget");s(aF,"claudeCodeBytes");s(cF,"cursorBytes");s(lF,"devinBytes");s(dF,"codexBytes");s(me,"renderHookOutput");s(xe,"hostDelivers");s(cc,"writeHookStdout");s(lc,"hostProjectDir")});import{existsSync as uF,readFileSync as pF}from"node:fs";import{join as Up}from"node:path";function ax(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function Bp(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function lx(e,t={}){return e.some(n=>Bp(Oe(n,t,[cx])[0]))}function Mi(e,t){let n=Oe(e,t,[cx])[0],r=Oe(e,t,[fF])[0];return{channel:Bp(n)?"core":Bp(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function dx(e,t){let n=[Up(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(Up(t,".claude","settings.json"),Up(t,".claude","settings.local.json")),n.map(r=>{try{return uF(r)?pF(r,"utf8"):null}catch{return null}})}var cx,fF,dc=w(()=>{"use strict";ve();s(ax,"hookOf");cx=ax(je,J),fF=ax(Qr,"guard-inject");s(Bp,"isRunnable");s(lx,"coreBriefingWiredIn");s(Mi,"briefingChannel");s(dx,"claudeSettingsSources")});function ux(e){return e==="on"?!0:e==="off"?!1:null}function he(e=process.env,t=Q()){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:ux(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:ux(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function dr(e,t=He()){let n={};try{let o=await q(t);if(o!==null&&o.trim().length>0){let i=JSON.parse(o);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await U(t,JSON.stringify(r,null,2)+`
841
- `,384)}var vt=w(()=>{"use strict";Ue();ie();s(ux,"envSwitch");s(he,"resolveGuardConfig");s(dr,"writeGuardConfig")});function pc(e){if(!e)return null;let t=e.split(`
843
+ `))!==-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/,""))}}return a(),i}var Ni,iF,gn=w(()=>{"use strict";Ni="https://mcp.maind.dev/mcp",iF="2025-06-18";s(ar,"fetchSessionBriefing");s(Ft,"fetchToolText");s(ox,"readSseMessage")});function ix(e){try{let t=Buffer.concat(e).toString("utf-8").trim();if(!t)return{};let n=JSON.parse(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}async function V(){let e=process.stdin;if(e.isTTY)return{};let t=[],n=0;return await new Promise(r=>{let o=!1,i,a=s(l=>{o||(o=!0,clearTimeout(i),r(l))},"settle"),c=s(l=>{clearTimeout(i),i=setTimeout(()=>{let d=n;setImmediate(()=>{o||n!==d||a(ix(t))})},l)},"arm");c(1e3),e.on("data",l=>{o||(t.push(typeof l=="string"?Buffer.from(l,"utf-8"):l),n+=1,c(200))}),e.on("end",()=>a(ix(t))),e.on("error",()=>a({}))})}function fo(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Ze(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var ke=w(()=>{"use strict";s(ix,"parsePayload");s(V,"readHookInput");s(fo,"transcriptPathOf");s(Ze,"toolFilePathOf")});function cr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function lr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function Oi(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function cc(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Hp(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Di=w(()=>{"use strict";s(cr,"denyPayload");s(lr,"advisoryPayload");s(Oi,"postAdvisoryPayload");s(cc,"postFailureAdvisoryPayload");s(Hp,"promptAdvisoryPayload")});function sF(e){return yn(e)&&/[\\/]\.claude[^\\/]*[\\/]projects[\\/]/.test(e)}function aF(e){return yn(e)&&/[\\/]sessions[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/]rollout-[^\\/]+\.jsonl$/.test(e)}function sx(e){for(let t of e)if(t==="--host=codex")return"codex";return null}function Pi(e,t=process.env,n=null){return n==="codex"?"codex":yn(e.cursor_version)?"cursor":sF(e.transcript_path)?"claude-code":aF(e.transcript_path)?"codex":yn(t.CURSOR_VERSION)?"cursor":yn(t.DEVIN_PROJECT_DIR)?"devin":yn(t.CLAUDE_PROJECT_DIR)||t.CLAUDECODE==="1"?"claude-code":"unknown"}function ax(e,t=process.env){return Pi(e,t)==="cursor"}function _n(e){return e==="cursor"||e==="devin"||e==="codex"}function st(e,t=process.env){return _n(Pi(e,t))}function cF(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 de(e,t=process.env,n=Q,r=null){let o=Pi(e,t,r);return{host:o,devinOutput:o==="devin"?cF(t,n()):!1}}function lF(e){switch(e.kind){case"text":return e.text;case"deny":return cr(e.reason);case"context":switch(e.event){case"UserPromptSubmit":return Hp(e.text);case"PreToolUse":return lr(e.text);case"PostToolUse":return Oi(e.text);case"PostToolUseFailure":return cc(e.text)}}}function dF(e){return e.kind==="deny"?JSON.stringify({permission:"deny",user_message:e.reason,agent_message:e.reason}):null}function uF(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"?Hp(e.text):e.event==="PostToolUse"?Oi(e.text):null}}function pF(e){return e.kind!=="text"?null:JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.text.replace(/\s+$/,"")}})}function me(e,t){switch(e.host){case"claude-code":case"unknown":return lF(t);case"cursor":return dF(t);case"devin":return e.devinOutput?uF(t):null;case"codex":return pF(t)}}function xe(e,t){let n=t.kind==="deny"?{kind:"deny",reason:"x"}:{...t,text:"x"};return me(e,n)!==null}function lc(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}function dc(e,t=process.env){return e.host==="devin"&&yn(t.DEVIN_PROJECT_DIR)?t.DEVIN_PROJECT_DIR.trim():e.host==="cursor"&&yn(t.CURSOR_PROJECT_DIR)?t.CURSOR_PROJECT_DIR.trim():null}var yn,$e=w(()=>{"use strict";Ue();Di();yn=s(e=>typeof e=="string"&&e.trim().length>0,"filled");s(sF,"isClaudeCodeTranscript");s(aF,"isCodexTranscript");s(sx,"hostHintFromArgv");s(Pi,"detectHookHost");s(ax,"runsUnderCursor");s(_n,"isForeignHost");s(st,"guardStandsDown");s(cF,"devinOutputEnabled");s(de,"resolveHookTarget");s(lF,"claudeCodeBytes");s(dF,"cursorBytes");s(uF,"devinBytes");s(pF,"codexBytes");s(me,"renderHookOutput");s(xe,"hostDelivers");s(lc,"writeHookStdout");s(dc,"hostProjectDir")});import{existsSync as fF,readFileSync as mF}from"node:fs";import{join as Up}from"node:path";function cx(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function Bp(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function dx(e,t={}){return e.some(n=>Bp(Oe(n,t,[lx])[0]))}function Mi(e,t){let n=Oe(e,t,[lx])[0],r=Oe(e,t,[hF])[0];return{channel:Bp(n)?"core":Bp(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function ux(e,t){let n=[Up(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(Up(t,".claude","settings.json"),Up(t,".claude","settings.local.json")),n.map(r=>{try{return fF(r)?mF(r,"utf8"):null}catch{return null}})}var lx,hF,uc=w(()=>{"use strict";ve();s(cx,"hookOf");lx=cx(je,J),hF=cx(Qr,"guard-inject");s(Bp,"isRunnable");s(dx,"coreBriefingWiredIn");s(Mi,"briefingChannel");s(ux,"claudeSettingsSources")});function px(e){return e==="on"?!0:e==="off"?!1:null}function he(e=process.env,t=Q()){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:px(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:px(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function dr(e,t=He()){let n={};try{let o=await q(t);if(o!==null&&o.trim().length>0){let i=JSON.parse(o);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await U(t,JSON.stringify(r,null,2)+`
844
+ `,384)}var vt=w(()=>{"use strict";Ue();ie();s(px,"envSwitch");s(he,"resolveGuardConfig");s(dr,"writeGuardConfig")});function fc(e){if(!e)return null;let t=e.split(`
842
845
  `),n=t.findIndex(o=>o.startsWith("=== Project Conventions"));if(n<0)return null;let r=[];for(let o=n;o<t.length&&t[o].trim()!=="";o++)r.push(t[o]);return r.length>1?r.join(`
843
- `):null}function mF(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(`
844
- `),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 o=s((i,a)=>(i??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:o(n.briefing,i=>i.title?`- ${i.title}${i.id?` (${i.id})`:""}${i.summary?` \u2014 ${i.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:o(n.skill_index,i=>i.id?`- ${i.id}${i.summary?`: ${i.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:o(n.memory_index,i=>i.title?`- ${i.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:o(n.convention_index,i=>i.id?`- ${i.id}${i.title?`: ${i.title}`:""}`:null),more:"search_lessons"}),r.filter(i=>i.lines.length>0)}function fc(e,t,n,r=9e3){let o=[];if(t){let[d,...u]=t.split(`
845
- `);o.push({title:d,lines:u,more:"get_conventions"})}o.push(...mF(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of o){let u=`
846
-
847
- ${d.title}`;if(uc(c+u)>a){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let f=`
848
- ${d.lines[p]}`;if(uc(c+f)<=a){c+=f;continue}l=!1;let h=`
849
- (+${d.lines.length-p} more \u2014 via ${d.more})`;uc(c+h)<=r&&(c+=h);break}if(!l)break}if(!l){let d=`
850
- \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;uc(c+d)<=r&&(c+=d)}return{text:c+`
851
- `,complete:l}}var uc,mc=w(()=>{"use strict";uc=s(e=>Buffer.byteLength(e,"utf8"),"bytes");s(pc,"extractConventionsBlock");s(mF,"briefingSections");s(fc,"composeInjection")});import{existsSync as fx}from"node:fs";import{mkdir as hF,readFile as gF,readdir as yF,rename as _F,stat as bF,unlink as wF,writeFile as vF}from"node:fs/promises";import{join as $i}from"node:path";function mx(e){return $i(Kp,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function Ft(e){try{let t=mx(e);if(!fx(t))return{};let n=JSON.parse(await gF(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Le(e,t){await hF(Kp,{recursive:!0,mode:448});let n=mx(e),r=`${n}.tmp`;await vF(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await _F(r,n)}async function hx(e=7*24*60*60*1e3,t=Date.now()){await px(Kp,".json",e,t),await px(Gp,".jsonl",e,t)}async function px(e,t,n,r){try{if(!fx(e))return;for(let o of await yF(e)){if(!o.endsWith(t))continue;let i=$i(e,o);try{let a=await bF(i);r-a.mtimeMs>n&&await wF(i)}catch{}}}catch{}}var Te,Kp,Gp,at=w(()=>{"use strict";Be();Te=$i(Re,"guard"),Kp=$i(Te,"sessions"),Gp=$i(Te,"triggers");s(mx,"sessionFile");s(Ft,"loadGuardSession");s(Le,"saveGuardSession");s(hx,"sweepOldGuardSessions");s(px,"sweepDir")});import{existsSync as kF}from"node:fs";import{appendFile as xF,mkdir as SF,open as EF}from"node:fs/promises";import{join as RF}from"node:path";async function te(e){try{await SF(Te,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
852
- `;await xF(ur,t,{mode:384})}catch{}}async function gx(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(!kF(ur))return t;let n=await EF(ur,"r");try{let r=(await n.stat()).size,o=Math.max(0,r-e),i=Buffer.alloc(r-o);await n.read(i,0,i.length,o);let c=i.toString("utf8").split(`
853
- `);for(let l of o>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 ur,jt=w(()=>{"use strict";at();ur=RF(Te,"events.jsonl");s(te,"appendGuardEvent");s(gx,"readGuardEventCounts")});var kx={};Z(kx,{BRIEFING_CACHE_FILE:()=>mo,UNAVAILABLE_LINE:()=>wx,carriesBriefing:()=>bx,deliverSessionBriefing:()=>hc,formatInjection:()=>vx,resolveBriefingInjection:()=>ho,runGuardInject:()=>$F,runsUnderCursor:()=>sx});import{existsSync as CF}from"node:fs";import{mkdir as TF,readFile as AF,rename as IF,writeFile as NF}from"node:fs/promises";import{homedir as yx}from"node:os";import{dirname as OF,join as DF}from"node:path";async function ho(e,t,n={}){let r=n.nowMs??Date.now(),o=n.cacheFile??mo,i=n.fetcher??ar,a=await HF(o),c=a!==null&&a.format===_x&&r-Date.parse(a.fetched_at)<PF&&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 i({onInitialize:s(p=>{d=pc(p)},"onInitialize"),apiKey:t,deviceId:BF(),projectKey:e,bridgeVersion:H,timeoutMs:MF});if(u!==null){let p=d;return await UF(o,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:_x,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return a!==null?{text:a.text,via:"stale-cache",...l(a),projectKey:a.project_key}:{text:null,via:"none"}}async function $F(){try{if(he().mode==="off")return 0;let t=await V();return lx(dx(yx(),jF(t)))||De(Pe(yx(),process.env,process.platform)).enabled&&!(Q()?.declined_hooks??[]).includes(J)?0:await hc("guard",t)}catch{return 0}}function bx(e){return e==="resume"||e==="fork"}function LF(e,t){let n=lc(e,t);if(n===null)return ne();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:yt(n)}function FF(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function hc(e,t,n={}){let r=n.env??process.env,o=de(t,r,n.readConfig??Q,n.hostHint??null);if(!xe(o,{kind:"text",event:"SessionStart"}))return 0;let i=n.write??FF,a=s(async v=>{let k=me(o,{kind:"text",event:"SessionStart",text:v});k!==null&&await i(k)},"write"),c=_n(o.host)?{host:o.host}:{},l=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(l===null)return 0;await hx();let d=typeof t.source=="string"?t.source:"startup";if(bx(d)){let v=await Ft(l);return await Le(l,{...v,carryover:!0}),0}let u=(n.apiKey??z)();if(u===null)return 0;let p=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),f=(n.projectKey??(()=>LF(o,r)))(),h=o.host==="codex"&&n.inject?.fetcher===void 0?{...n.inject,fetcher:s(v=>ar({...v,clientFamily:"codex"}),"fetcher")}:n.inject,g=await ho(f,u,h),y=await Ft(l);if(g.text===null)return await Le(l,{...y,inject_failed:!0}),await te({event:"inject_fail",session_id:l,cwd:p,project_key:f??void 0,...e==="core"?{detail:"core"}:{},...c}),await a(wx),0;let _=vx(g.text,g.via,g.conventions??null,e);await a(_.text),await Le(l,{...y,injected:!0});let b=_.complete?g.via:`${g.via}+budget`;return await te({event:"inject_ok",session_id:l,cwd:p,project_key:f??void 0,detail:e==="core"?`core:${b}`:b,...c}),0}function jF(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 vx(e,t,n=null,r="guard"){let o=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",i=`Session briefing${n?" + project conventions":""}`,a=(r==="core"?`[maind] ${i}, delivered by the bridge's session-start hook (ADR-359)${o} \u2014 `:`[maind guard] ${i}, injected deterministically (ADR-284)${o} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return fc(a,n,e)}async function HF(e){try{if(!CF(e))return null;let t=JSON.parse(await AF(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 UF(e,t){try{await TF(OF(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await NF(n,JSON.stringify(t,null,2),{mode:384}),await IF(n,e)}catch{}}function BF(){try{return ae()}catch{return null}}var mo,PF,_x,MF,wx,pr=w(()=>{"use strict";Ue();re();ke();$e();dc();oo();ve();pe();Fe();vt();mc();jt();at();gn();mo=DF(Te,"briefing-cache.json"),PF=12*60*60*1e3,_x=2,MF=3e3;s(ho,"resolveBriefingInjection");s($F,"runGuardInject");s(bx,"carriesBriefing");s(LF,"sessionProjectKey");s(FF,"writeStdout");s(hc,"deliverSessionBriefing");wx=`[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.
854
- `;s(jF,"projectDirOf");s(vx,"formatInjection");s(HF,"readCache");s(UF,"writeCache");s(BF,"safeDeviceId")});var Ix={};Z(Ix,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>Tx,AGENTS_MD_REFRESH_INTERVAL_MS:()=>Rx,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>Cx,AGENTS_MD_REFRESH_STATE_FILE:()=>Ex,gitToplevel:()=>gc,isSet:()=>Li,isWithin:()=>Ax,loadProjectConventions:()=>fr,realpathOrResolve:()=>Vp,refreshAgentsMdConventions:()=>Wp,refreshAgentsMdForSession:()=>tj});import{execFileSync as KF}from"node:child_process";import{createHash as GF}from"node:crypto";import{mkdir as WF,readFile as VF,realpath as qF,rename as zF,writeFile as JF}from"node:fs/promises";import{dirname as YF,isAbsolute as XF,join as Sx,relative as ZF,resolve as QF}from"node:path";async function fr(e,t,n){if(e===null)return null;let r=n.clientFamily??"mcp-bridge",o=await ho(t,e,{fetcher:n.allowFetch?i=>ar({...i,clientFamily:r}):async()=>null,...n.cacheFile!==void 0?{cacheFile:n.cacheFile}:{}});return o.text===null||o.via==="stale-cache"&&o.projectKey!==void 0&&o.projectKey!==t?null:o.conventions??null}async function Wp(e,t){let n=t.err??(r=>process.stderr.write(`${r}
855
- `));try{let r=t.env??process.env;if(nj(r))return{status:"skipped",reason:"opt-out"};let o=t.cwd??process.cwd(),i=(t.gitToplevel??gc)(o);if(i===null)return qp(r)&&n(`maind: AGENTS.md team block skipped \u2014 ${o} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Vp(i),c=[];for(let E of await(t.findRoots??ga)(o)){let S=await Vp(E);Ax(S,a)&&!c.includes(S)&&c.push(S)}c.includes(a)||c.push(a);let l=null,d=null;for(let E of c){let S=Sx(E,"AGENTS.md"),R=await q(S);if(R!==null&&jw(R)){l=S,d=R;break}}if(l===null||d===null)return qp(r)&&n(`maind: AGENTS.md team block skipped \u2014 no AGENTS.md with a team conventions block between the working directory and ${a} (install --team writes one; the bridge never writes above the repository root)`),{status:"skipped",reason:"no-team-block"};let u=t.nowMs??Date.now(),p=t.stateFile??Ex,f=await oj(p),h=rj(l),g=f.roots[h]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<Rx)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((E,S)=>fr(S,E,{allowFetch:!0,clientFamily:e??void 0})))(t.projectKey,t.apiKey);if(_===null||_.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=xa(_,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??H},{team:!0}),v=Sa(d,b,void 0,{replaceOnly:!0});if(v.outcome==="damaged")return n(`maind: AGENTS.md team block not refreshed \u2014 begin marker without end marker in ${l}; remove the <!-- maind:conventions --> lines and run install --team again`),{status:"skipped",reason:"damaged"};if(v.outcome==="no-header"||v.outcome==="inserted")return{status:"skipped",reason:"no-team-block"};if(v.changed&&await U(l,v.next),await ij(p,f,h,u),!v.changed)return{status:"unchanged",file:l};let k=Fw(b);return n(`maind: AGENTS.md team conventions block refreshed (${k} conventions)`),{status:"refreshed",file:l,conventions:k}}catch(r){let o=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md team block not refreshed \u2014 ${o}`),{status:"failed",error:o}}}async function tj(e,t){let n=await Wp(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-team-block"||t.listRoots===void 0)return n;let r=t.env??process.env,o=t.err??(l=>process.stderr.write(`${l}
856
- `)),i;try{i=await t.listRoots()}catch{i=null}if(i===null||i.length===0)return qp(r)&&o("maind: AGENTS.md team block skipped \u2014 the working directory gave no repository with a team block, "+(i===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 i){if(l===a)continue;let d=await Wp(e,{...t,cwd:l,projectKey:(t.projectKeyFor??yt)(l)??t.projectKey});xx(d)>xx(c)&&(c=d)}return c}function xx(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function gc(e){try{let t=KF("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 Ax(e,t){let n=ZF(t,e);return n===""||!n.startsWith("..")&&!XF(n)}async function Vp(e){try{return await qF(e)}catch{return QF(e)}}function nj(e){return Li(e[Cx])}function qp(e){return Li(e[Tx])}function Li(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function rj(e){return GF("sha256").update(e).digest("hex")}async function oj(e){let t={version:1,roots:{}};try{let n=JSON.parse(await VF(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[o,i]of Object.entries(n.roots))i&&typeof i.checked_at=="string"&&(r[o]={checked_at:i.checked_at});return{version:1,roots:r}}catch{return t}}async function ij(e,t,n,r){let o={};for(let[a,c]of Object.entries(t.roots)){let l=Date.parse(c.checked_at);!Number.isNaN(l)&&r-l<ej&&(o[a]=c)}o[n]={checked_at:new Date(r).toISOString()},await WF(YF(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;await JF(i,JSON.stringify({version:1,roots:o},null,2),{mode:384}),await zF(i,e)}var Ex,Rx,Cx,Tx,ej,yc=w(()=>{"use strict";gn();pr();at();Zr();ie();Fu();pe();Fe();Ex=Sx(Te,"agents-md-refresh.json"),Rx=12*60*60*1e3,Cx="MAIND_NO_AGENTS_MD_REFRESH",Tx="MAIND_DEBUG",ej=30*24*60*60*1e3;s(fr,"loadProjectConventions");s(Wp,"refreshAgentsMdConventions");s(tj,"refreshAgentsMdForSession");s(xx,"rank");s(gc,"gitToplevel");s(Ax,"isWithin");s(Vp,"realpathOrResolve");s(nj,"isOptedOut");s(qp,"isDebug");s(Li,"isSet");s(rj,"fileKey");s(oj,"readState");s(ij,"writeState")});var Xp={};Z(Xp,{REFRESH_RULES_USAGE:()=>_c,RULES_REFRESH_INTERVAL_MS:()=>Nx,RULES_REFRESH_OPT_OUT_ENV:()=>zp,RULES_REFRESH_STATE_FILE:()=>Jp,recordRulesCheck:()=>wc,refreshRulesForSession:()=>wj,refreshUserRules:()=>Yp,repoDisplayName:()=>Ox,repoIdentity:()=>go,runRefreshRules:()=>vj});import{execFileSync as sj}from"node:child_process";import{createHash as aj}from"node:crypto";import{existsSync as cj,statSync as lj}from"node:fs";import{mkdir as dj,readFile as uj,rename as pj,writeFile as fj}from"node:fs/promises";import{homedir as mj}from"node:os";import{basename as hj,dirname as gj,join as yj,resolve as _j}from"node:path";function go(e){let t=gc(e);if(t===null)return{root:null,name:null,projectKey:null,key:"none"};let n=null;try{n=sj("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||null}catch{n=null}let r=n===null?null:nn(n);return{root:t,name:Ox(n,t),projectKey:r,key:r??Nu(`path:${t}`)}}function Ox(e,t){let n=e===null?null:Ou(e);if(n!==null){let r=n.split("/").filter(o=>o.length>0);if(r.length>=3)return r.slice(-2).join("/");if(r.length>=1)return r[r.length-1]}return hj(t)}async function Yp(e,t={}){let n=t.env??process.env;if(Li(n[zp]))return{outcome:"opted_out",repo:null,files:[]};try{let r=t.homeDir??mj(),o=(t.identity??go)(e),i=t.channels??ir(Mt({projectRoot:e,homeDir:r,platform:process.platform,env:n}),ce),a=t.only===void 0?i:i.filter(v=>t.only?.includes(v.id)),c=[];for(let v of a){let k=await q(v.path);k!==null&&so(k)&&c.push({channel:v,raw:k})}if(c.length===0)return{outcome:"no_channels",repo:o.name,files:[]};let l=t.nowMs??Date.now(),d=t.stateFile??Jp,u=await Dx(d),p=c.filter(({channel:v,raw:k})=>{if(t.force===!0)return!0;let E=u.files[bc(v.path)];if(E===void 0||E.repo!==o.key)return!0;let S=Date.parse(E.checked_at);return Number.isNaN(S)||l-S>=Nx?!0:E.content!==Ri(k)});if(p.length===0)return{outcome:"throttled",repo:o.name,files:[]};let f=(t.apiKey??z)();if(f===null)return{outcome:"failed",repo:o.name,files:[],error:"not paired \u2014 run `maind-mcp-bridge --reauth`"};let g=await(t.loadConventions??((v,k)=>fr(k,v,{allowFetch:!0,clientFamily:t.clientFamily??"mcp-bridge"})))(o.projectKey,f);if(g===null||g.trim().length===0)return{outcome:"failed",repo:o.name,files:[],error:`no conventions for ${o.name??"this directory"} \u2014 the MAIND server was not reachable and nothing is cached for it`};let y=[],_=[],b=0;for(let{channel:v,raw:k}of p){let E=Tp(v,{repo:o.name,conventions:g},{nowMs:l,bridgeVersion:t.bridgeVersion??H});try{if(io(k)===io(E)){b++,u.files[bc(v.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Ri(k)};continue}let S=await q(v.path);if(S===null||!so(S))continue;await U(v.path,E),y.push(v.path),u.files[bc(v.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Ri(E)}}catch(S){_.push(`${v.path}: ${S instanceof Error?S.message:String(S)}`)}}return await Px(d,u,l),y.length>0?{outcome:"refreshed",repo:o.name,files:y}:_.length>0?{outcome:"failed",repo:o.name,files:[],error:_.join("; ")}:{outcome:b>0?"unchanged":"no_channels",repo:o.name,files:[]}}catch(r){return{outcome:"failed",repo:null,files:[],error:r instanceof Error?r.message:String(r)}}}async function wc(e,t,n,r={}){try{let o=r.nowMs??Date.now(),i=r.stateFile??Jp,a=await Dx(i);a.files[bc(e)]={repo:n,checked_at:new Date(o).toISOString(),content:Ri(t)},await Px(i,a,o)}catch{}}async function wj(e,t={}){let n=ok(e);if(n===null)return null;let r=t.err??(o=>process.stderr.write(`${o}
857
- `));try{let o=t.identity??go,i=null,a=t.cwd??process.cwd();if(o(a).root!==null)i=a;else if(t.listRoots!==void 0){let l=null;try{l=await t.listRoots()}catch{l=null}i=(l??[]).find(d=>o(d).root!==null)??null}if(i===null)return null;let c=await Yp(i,{...t,only:[n],clientFamily:e??void 0});return c.outcome==="refreshed"?r(`maind: user-level rules refreshed with the conventions for ${c.repo??"this directory"} (${c.files.join(", ")})`):c.outcome==="failed"&&r(`maind: user-level rules not refreshed \u2014 ${c.error??"unknown error"}`),c}catch{return null}}async function vj(e,t={}){let n=t.out??(d=>void process.stdout.write(d)),r=t.errOut??(d=>void process.stderr.write(d)),o=null,i=!1,a=!1;for(let d=0;d<e.length;d++){let u=e[d];if(u==="--json")i=!0;else if(u==="--force")a=!0;else{if(u==="-h"||u==="--help")return n(_c),0;if(u==="--project-root"||u.startsWith("--project-root=")){let p=u.includes("=")?u.slice(u.indexOf("=")+1):e[d+1];if(u.includes("=")||d++,p===void 0||p.length===0||!u.includes("=")&&p.startsWith("--"))return r(`refresh-rules: --project-root requires a directory
858
- ${_c}`),2;o=p}else return r(`refresh-rules: unknown argument ${u}
859
- ${_c}`),2}}let c=_j(t.cwd??process.cwd(),o??".");if(!xj(c))return r(`refresh-rules: ${c} is not a directory
846
+ `):null}function gF(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(`
847
+ `),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 o=s((i,a)=>(i??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:o(n.briefing,i=>i.title?`- ${i.title}${i.id?` (${i.id})`:""}${i.summary?` \u2014 ${i.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:o(n.skill_index,i=>i.id?`- ${i.id}${i.summary?`: ${i.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:o(n.memory_index,i=>i.title?`- ${i.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:o(n.convention_index,i=>i.id?`- ${i.id}${i.title?`: ${i.title}`:""}`:null),more:"search_lessons"}),r.filter(i=>i.lines.length>0)}function mc(e,t,n,r=9e3){let o=[];if(t){let[d,...u]=t.split(`
848
+ `);o.push({title:d,lines:u,more:"get_conventions"})}o.push(...gF(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of o){let u=`
849
+
850
+ ${d.title}`;if(pc(c+u)>a){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let f=`
851
+ ${d.lines[p]}`;if(pc(c+f)<=a){c+=f;continue}l=!1;let h=`
852
+ (+${d.lines.length-p} more \u2014 via ${d.more})`;pc(c+h)<=r&&(c+=h);break}if(!l)break}if(!l){let d=`
853
+ \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;pc(c+d)<=r&&(c+=d)}return{text:c+`
854
+ `,complete:l}}var pc,hc=w(()=>{"use strict";pc=s(e=>Buffer.byteLength(e,"utf8"),"bytes");s(fc,"extractConventionsBlock");s(gF,"briefingSections");s(mc,"composeInjection")});import{existsSync as mx}from"node:fs";import{mkdir as yF,readFile as _F,readdir as bF,rename as wF,stat as vF,unlink as kF,writeFile as xF}from"node:fs/promises";import{join as $i}from"node:path";function hx(e){return $i(Kp,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function jt(e){try{let t=hx(e);if(!mx(t))return{};let n=JSON.parse(await _F(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Le(e,t){await yF(Kp,{recursive:!0,mode:448});let n=hx(e),r=`${n}.tmp`;await xF(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await wF(r,n)}async function gx(e=7*24*60*60*1e3,t=Date.now()){await fx(Kp,".json",e,t),await fx(Gp,".jsonl",e,t)}async function fx(e,t,n,r){try{if(!mx(e))return;for(let o of await bF(e)){if(!o.endsWith(t))continue;let i=$i(e,o);try{let a=await vF(i);r-a.mtimeMs>n&&await kF(i)}catch{}}}catch{}}var Te,Kp,Gp,at=w(()=>{"use strict";Be();Te=$i(Re,"guard"),Kp=$i(Te,"sessions"),Gp=$i(Te,"triggers");s(hx,"sessionFile");s(jt,"loadGuardSession");s(Le,"saveGuardSession");s(gx,"sweepOldGuardSessions");s(fx,"sweepDir")});import{existsSync as SF}from"node:fs";import{appendFile as EF,mkdir as RF,open as CF}from"node:fs/promises";import{join as TF}from"node:path";async function te(e){try{await RF(Te,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
855
+ `;await EF(ur,t,{mode:384})}catch{}}async function yx(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(!SF(ur))return t;let n=await CF(ur,"r");try{let r=(await n.stat()).size,o=Math.max(0,r-e),i=Buffer.alloc(r-o);await n.read(i,0,i.length,o);let c=i.toString("utf8").split(`
856
+ `);for(let l of o>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 ur,Ht=w(()=>{"use strict";at();ur=TF(Te,"events.jsonl");s(te,"appendGuardEvent");s(yx,"readGuardEventCounts")});var xx={};Z(xx,{BRIEFING_CACHE_FILE:()=>mo,UNAVAILABLE_LINE:()=>vx,carriesBriefing:()=>wx,deliverSessionBriefing:()=>gc,formatInjection:()=>kx,resolveBriefingInjection:()=>ho,runGuardInject:()=>FF,runsUnderCursor:()=>ax});import{existsSync as AF}from"node:fs";import{mkdir as IF,readFile as NF,rename as OF,writeFile as DF}from"node:fs/promises";import{homedir as _x}from"node:os";import{dirname as PF,join as MF}from"node:path";async function ho(e,t,n={}){let r=n.nowMs??Date.now(),o=n.cacheFile??mo,i=n.fetcher??ar,a=await BF(o),c=a!==null&&a.format===bx&&r-Date.parse(a.fetched_at)<$F&&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 i({onInitialize:s(p=>{d=fc(p)},"onInitialize"),apiKey:t,deviceId:GF(),projectKey:e,bridgeVersion:H,timeoutMs:LF});if(u!==null){let p=d;return await KF(o,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:bx,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return a!==null?{text:a.text,via:"stale-cache",...l(a),projectKey:a.project_key}:{text:null,via:"none"}}async function FF(){try{if(he().mode==="off")return 0;let t=await V();return dx(ux(_x(),UF(t)))||De(Pe(_x(),process.env,process.platform)).enabled&&!(Q()?.declined_hooks??[]).includes(J)?0:await gc("guard",t)}catch{return 0}}function wx(e){return e==="resume"||e==="fork"}function jF(e,t){let n=dc(e,t);if(n===null)return ne();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:yt(n)}function HF(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function gc(e,t,n={}){let r=n.env??process.env,o=de(t,r,n.readConfig??Q,n.hostHint??null);if(!xe(o,{kind:"text",event:"SessionStart"}))return 0;let i=n.write??HF,a=s(async v=>{let k=me(o,{kind:"text",event:"SessionStart",text:v});k!==null&&await i(k)},"write"),c=_n(o.host)?{host:o.host}:{},l=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(l===null)return 0;await gx();let d=typeof t.source=="string"?t.source:"startup";if(wx(d)){let v=await jt(l);return await Le(l,{...v,carryover:!0}),0}let u=(n.apiKey??z)();if(u===null)return 0;let p=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),f=(n.projectKey??(()=>jF(o,r)))(),h=o.host==="codex"&&n.inject?.fetcher===void 0?{...n.inject,fetcher:s(v=>ar({...v,clientFamily:"codex"}),"fetcher")}:n.inject,g=await ho(f,u,h),y=await jt(l);if(g.text===null)return await Le(l,{...y,inject_failed:!0}),await te({event:"inject_fail",session_id:l,cwd:p,project_key:f??void 0,...e==="core"?{detail:"core"}:{},...c}),await a(vx),0;let _=kx(g.text,g.via,g.conventions??null,e);await a(_.text),await Le(l,{...y,injected:!0});let b=_.complete?g.via:`${g.via}+budget`;return await te({event:"inject_ok",session_id:l,cwd:p,project_key:f??void 0,detail:e==="core"?`core:${b}`:b,...c}),0}function UF(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 kx(e,t,n=null,r="guard"){let o=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",i=`Session briefing${n?" + project conventions":""}`,a=(r==="core"?`[maind] ${i}, delivered by the bridge's session-start hook (ADR-359)${o} \u2014 `:`[maind guard] ${i}, injected deterministically (ADR-284)${o} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return mc(a,n,e)}async function BF(e){try{if(!AF(e))return null;let t=JSON.parse(await NF(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 KF(e,t){try{await IF(PF(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await DF(n,JSON.stringify(t,null,2),{mode:384}),await OF(n,e)}catch{}}function GF(){try{return ae()}catch{return null}}var mo,$F,bx,LF,vx,pr=w(()=>{"use strict";Ue();re();ke();$e();uc();oo();ve();pe();Fe();vt();hc();Ht();at();gn();mo=MF(Te,"briefing-cache.json"),$F=12*60*60*1e3,bx=2,LF=3e3;s(ho,"resolveBriefingInjection");s(FF,"runGuardInject");s(wx,"carriesBriefing");s(jF,"sessionProjectKey");s(HF,"writeStdout");s(gc,"deliverSessionBriefing");vx=`[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.
857
+ `;s(UF,"projectDirOf");s(kx,"formatInjection");s(BF,"readCache");s(KF,"writeCache");s(GF,"safeDeviceId")});var Nx={};Z(Nx,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>Ax,AGENTS_MD_REFRESH_INTERVAL_MS:()=>Cx,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>Tx,AGENTS_MD_REFRESH_STATE_FILE:()=>Rx,gitToplevel:()=>yc,isSet:()=>Li,isWithin:()=>Ix,loadProjectConventions:()=>fr,realpathOrResolve:()=>Vp,refreshAgentsMdConventions:()=>Wp,refreshAgentsMdForSession:()=>rj});import{execFileSync as WF}from"node:child_process";import{createHash as VF}from"node:crypto";import{mkdir as qF,readFile as zF,realpath as JF,rename as YF,writeFile as XF}from"node:fs/promises";import{dirname as ZF,isAbsolute as QF,join as Ex,relative as ej,resolve as tj}from"node:path";async function fr(e,t,n){if(e===null)return null;let r=n.clientFamily??"mcp-bridge",o=await ho(t,e,{fetcher:n.allowFetch?i=>ar({...i,clientFamily:r}):async()=>null,...n.cacheFile!==void 0?{cacheFile:n.cacheFile}:{}});return o.text===null||o.via==="stale-cache"&&o.projectKey!==void 0&&o.projectKey!==t?null:o.conventions??null}async function Wp(e,t){let n=t.err??(r=>process.stderr.write(`${r}
858
+ `));try{let r=t.env??process.env;if(oj(r))return{status:"skipped",reason:"opt-out"};let o=t.cwd??process.cwd(),i=(t.gitToplevel??yc)(o);if(i===null)return qp(r)&&n(`maind: AGENTS.md team block skipped \u2014 ${o} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Vp(i),c=[];for(let E of await(t.findRoots??ya)(o)){let S=await Vp(E);Ix(S,a)&&!c.includes(S)&&c.push(S)}c.includes(a)||c.push(a);let l=null,d=null;for(let E of c){let S=Ex(E,"AGENTS.md"),R=await q(S);if(R!==null&&Hw(R)){l=S,d=R;break}}if(l===null||d===null)return qp(r)&&n(`maind: AGENTS.md team block skipped \u2014 no AGENTS.md with a team conventions block between the working directory and ${a} (install --team writes one; the bridge never writes above the repository root)`),{status:"skipped",reason:"no-team-block"};let u=t.nowMs??Date.now(),p=t.stateFile??Rx,f=await sj(p),h=ij(l),g=f.roots[h]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<Cx)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((E,S)=>fr(S,E,{allowFetch:!0,clientFamily:e??void 0})))(t.projectKey,t.apiKey);if(_===null||_.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=Sa(_,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??H},{team:!0}),v=Ea(d,b,void 0,{replaceOnly:!0});if(v.outcome==="damaged")return n(`maind: AGENTS.md team block not refreshed \u2014 begin marker without end marker in ${l}; remove the <!-- maind:conventions --> lines and run install --team again`),{status:"skipped",reason:"damaged"};if(v.outcome==="no-header"||v.outcome==="inserted")return{status:"skipped",reason:"no-team-block"};if(v.changed&&await U(l,v.next),await aj(p,f,h,u),!v.changed)return{status:"unchanged",file:l};let k=jw(b);return n(`maind: AGENTS.md team conventions block refreshed (${k} conventions)`),{status:"refreshed",file:l,conventions:k}}catch(r){let o=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md team block not refreshed \u2014 ${o}`),{status:"failed",error:o}}}async function rj(e,t){let n=await Wp(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-team-block"||t.listRoots===void 0)return n;let r=t.env??process.env,o=t.err??(l=>process.stderr.write(`${l}
859
+ `)),i;try{i=await t.listRoots()}catch{i=null}if(i===null||i.length===0)return qp(r)&&o("maind: AGENTS.md team block skipped \u2014 the working directory gave no repository with a team block, "+(i===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 i){if(l===a)continue;let d=await Wp(e,{...t,cwd:l,projectKey:(t.projectKeyFor??yt)(l)??t.projectKey});Sx(d)>Sx(c)&&(c=d)}return c}function Sx(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function yc(e){try{let t=WF("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 Ix(e,t){let n=ej(t,e);return n===""||!n.startsWith("..")&&!QF(n)}async function Vp(e){try{return await JF(e)}catch{return tj(e)}}function oj(e){return Li(e[Tx])}function qp(e){return Li(e[Ax])}function Li(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function ij(e){return VF("sha256").update(e).digest("hex")}async function sj(e){let t={version:1,roots:{}};try{let n=JSON.parse(await zF(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[o,i]of Object.entries(n.roots))i&&typeof i.checked_at=="string"&&(r[o]={checked_at:i.checked_at});return{version:1,roots:r}}catch{return t}}async function aj(e,t,n,r){let o={};for(let[a,c]of Object.entries(t.roots)){let l=Date.parse(c.checked_at);!Number.isNaN(l)&&r-l<nj&&(o[a]=c)}o[n]={checked_at:new Date(r).toISOString()},await qF(ZF(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;await XF(i,JSON.stringify({version:1,roots:o},null,2),{mode:384}),await YF(i,e)}var Rx,Cx,Tx,Ax,nj,_c=w(()=>{"use strict";gn();pr();at();Zr();ie();Fu();pe();Fe();Rx=Ex(Te,"agents-md-refresh.json"),Cx=12*60*60*1e3,Tx="MAIND_NO_AGENTS_MD_REFRESH",Ax="MAIND_DEBUG",nj=30*24*60*60*1e3;s(fr,"loadProjectConventions");s(Wp,"refreshAgentsMdConventions");s(rj,"refreshAgentsMdForSession");s(Sx,"rank");s(yc,"gitToplevel");s(Ix,"isWithin");s(Vp,"realpathOrResolve");s(oj,"isOptedOut");s(qp,"isDebug");s(Li,"isSet");s(ij,"fileKey");s(sj,"readState");s(aj,"writeState")});var Xp={};Z(Xp,{REFRESH_RULES_USAGE:()=>bc,RULES_REFRESH_INTERVAL_MS:()=>Ox,RULES_REFRESH_OPT_OUT_ENV:()=>zp,RULES_REFRESH_STATE_FILE:()=>Jp,recordRulesCheck:()=>vc,refreshRulesForSession:()=>kj,refreshUserRules:()=>Yp,repoDisplayName:()=>Dx,repoIdentity:()=>go,runRefreshRules:()=>xj});import{execFileSync as cj}from"node:child_process";import{createHash as lj}from"node:crypto";import{existsSync as dj,statSync as uj}from"node:fs";import{mkdir as pj,readFile as fj,rename as mj,writeFile as hj}from"node:fs/promises";import{homedir as gj}from"node:os";import{basename as yj,dirname as _j,join as bj,resolve as wj}from"node:path";function go(e){let t=yc(e);if(t===null)return{root:null,name:null,projectKey:null,key:"none"};let n=null;try{n=cj("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||null}catch{n=null}let r=n===null?null:nn(n);return{root:t,name:Dx(n,t),projectKey:r,key:r??Nu(`path:${t}`)}}function Dx(e,t){let n=e===null?null:Ou(e);if(n!==null){let r=n.split("/").filter(o=>o.length>0);if(r.length>=3)return r.slice(-2).join("/");if(r.length>=1)return r[r.length-1]}return yj(t)}async function Yp(e,t={}){let n=t.env??process.env;if(Li(n[zp]))return{outcome:"opted_out",repo:null,files:[]};try{let r=t.homeDir??gj(),o=(t.identity??go)(e),i=t.channels??ir($t({projectRoot:e,homeDir:r,platform:process.platform,env:n}),ce),a=t.only===void 0?i:i.filter(v=>t.only?.includes(v.id)),c=[];for(let v of a){let k=await q(v.path);k!==null&&so(k)&&c.push({channel:v,raw:k})}if(c.length===0)return{outcome:"no_channels",repo:o.name,files:[]};let l=t.nowMs??Date.now(),d=t.stateFile??Jp,u=await Px(d),p=c.filter(({channel:v,raw:k})=>{if(t.force===!0)return!0;let E=u.files[wc(v.path)];if(E===void 0||E.repo!==o.key)return!0;let S=Date.parse(E.checked_at);return Number.isNaN(S)||l-S>=Ox?!0:E.content!==Ri(k)});if(p.length===0)return{outcome:"throttled",repo:o.name,files:[]};let f=(t.apiKey??z)();if(f===null)return{outcome:"failed",repo:o.name,files:[],error:"not paired \u2014 run `maind-mcp-bridge --reauth`"};let g=await(t.loadConventions??((v,k)=>fr(k,v,{allowFetch:!0,clientFamily:t.clientFamily??"mcp-bridge"})))(o.projectKey,f);if(g===null||g.trim().length===0)return{outcome:"failed",repo:o.name,files:[],error:`no conventions for ${o.name??"this directory"} \u2014 the MAIND server was not reachable and nothing is cached for it`};let y=[],_=[],b=0;for(let{channel:v,raw:k}of p){let E=Tp(v,{repo:o.name,conventions:g},{nowMs:l,bridgeVersion:t.bridgeVersion??H});try{if(io(k)===io(E)){b++,u.files[wc(v.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Ri(k)};continue}let S=await q(v.path);if(S===null||!so(S))continue;await U(v.path,E),y.push(v.path),u.files[wc(v.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Ri(E)}}catch(S){_.push(`${v.path}: ${S instanceof Error?S.message:String(S)}`)}}return await Mx(d,u,l),y.length>0?{outcome:"refreshed",repo:o.name,files:y}:_.length>0?{outcome:"failed",repo:o.name,files:[],error:_.join("; ")}:{outcome:b>0?"unchanged":"no_channels",repo:o.name,files:[]}}catch(r){return{outcome:"failed",repo:null,files:[],error:r instanceof Error?r.message:String(r)}}}async function vc(e,t,n,r={}){try{let o=r.nowMs??Date.now(),i=r.stateFile??Jp,a=await Px(i);a.files[wc(e)]={repo:n,checked_at:new Date(o).toISOString(),content:Ri(t)},await Mx(i,a,o)}catch{}}async function kj(e,t={}){let n=ik(e);if(n===null)return null;let r=t.err??(o=>process.stderr.write(`${o}
860
+ `));try{let o=t.identity??go,i=null,a=t.cwd??process.cwd();if(o(a).root!==null)i=a;else if(t.listRoots!==void 0){let l=null;try{l=await t.listRoots()}catch{l=null}i=(l??[]).find(d=>o(d).root!==null)??null}if(i===null)return null;let c=await Yp(i,{...t,only:[n],clientFamily:e??void 0});return c.outcome==="refreshed"?r(`maind: user-level rules refreshed with the conventions for ${c.repo??"this directory"} (${c.files.join(", ")})`):c.outcome==="failed"&&r(`maind: user-level rules not refreshed \u2014 ${c.error??"unknown error"}`),c}catch{return null}}async function xj(e,t={}){let n=t.out??(d=>void process.stdout.write(d)),r=t.errOut??(d=>void process.stderr.write(d)),o=null,i=!1,a=!1;for(let d=0;d<e.length;d++){let u=e[d];if(u==="--json")i=!0;else if(u==="--force")a=!0;else{if(u==="-h"||u==="--help")return n(bc),0;if(u==="--project-root"||u.startsWith("--project-root=")){let p=u.includes("=")?u.slice(u.indexOf("=")+1):e[d+1];if(u.includes("=")||d++,p===void 0||p.length===0||!u.includes("=")&&p.startsWith("--"))return r(`refresh-rules: --project-root requires a directory
861
+ ${bc}`),2;o=p}else return r(`refresh-rules: unknown argument ${u}
862
+ ${bc}`),2}}let c=wj(t.cwd??process.cwd(),o??".");if(!Ej(c))return r(`refresh-rules: ${c} is not a directory
860
863
  `),2;let l=await Yp(c,{...t,force:a});return n(i?JSON.stringify({outcome:l.outcome,repo:l.repo,files:l.files})+`
861
- `:kj(l)+`
864
+ `:Sj(l)+`
862
865
  `),l.outcome==="failed"&&i&&r(`refresh-rules: ${l.error??"failed"}
863
- `),l.outcome==="failed"?1:0}function kj(e){let t=e.repo??"this directory (no repository)";switch(e.outcome){case"refreshed":return`maind: refreshed ${e.files.length} rule file(s) with the conventions for ${t}: ${e.files.join(", ")}`;case"unchanged":return`maind: rule files already carry the current conventions for ${t}`;case"throttled":return`maind: rule files were checked for ${t} less than 12 h ago (--force to check now)`;case"no_channels":return"maind: no user-level rule files to refresh (install sets them up with your consent)";case"opted_out":return`maind: ${zp} is set \u2014 nothing refreshed`;case"failed":return`maind: rule files not refreshed \u2014 ${e.error??"unknown error"}`}}function xj(e){try{return cj(e)&&lj(e).isDirectory()}catch{return!1}}function bc(e){return aj("sha256").update(e).digest("hex")}async function Dx(e){let t={version:1,files:{}};try{let n=JSON.parse(await uj(e,"utf8"));if(!n||typeof n.files!="object"||n.files===null)return t;let r={};for(let[o,i]of Object.entries(n.files))i&&typeof i.repo=="string"&&typeof i.checked_at=="string"&&typeof i.content=="string"&&(r[o]={repo:i.repo,checked_at:i.checked_at,content:i.content});return{version:1,files:r}}catch{return t}}async function Px(e,t,n){let r={};for(let[i,a]of Object.entries(t.files)){let c=Date.parse(a.checked_at);!Number.isNaN(c)&&n-c<bj&&(r[i]=a)}await dj(gj(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await fj(o,JSON.stringify({version:1,files:r},null,2),{mode:384}),await pj(o,e)}var zp,Jp,Nx,bj,_c,vc=w(()=>{"use strict";yc();re();at();ie();Je();Ga();pe();Fe();zp="MAIND_NO_RULES_REFRESH",Jp=yj(Te,"rules-refresh.json"),Nx=12*60*60*1e3,bj=30*24*60*60*1e3;s(go,"repoIdentity");s(Ox,"repoDisplayName");s(Yp,"refreshUserRules");s(wc,"recordRulesCheck");s(wj,"refreshRulesForSession");_c=["Usage: maind-mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]","","Refreshes the user-level rule files that exist (GitHub Copilot, Cline, Continue)","with the conventions of the repository at <dir> (default: the current directory;","its git root). Never creates a file. At most once per 12 h per repository and","only when the content changed; --force skips the 12 h. MAIND_NO_RULES_REFRESH=1","makes it a no-op. Exit 0 refreshed/unchanged/throttled/no_channels/opted_out,","2 usage error, 1 failure. --json prints {outcome, repo, files}.",""].join(`
864
- `);s(vj,"runRefreshRules");s(kj,"humanLine");s(xj,"isDirectory");s(bc,"fileKey");s(Dx,"readState");s(Px,"writeState")});import*as Mx from"node:os";async function $x(e){let t=Date.now(),n;try{n=gw(e)}catch(x){if(x instanceof Ye)return process.stderr.write(`error: ${x.message}
865
- `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw x}if(n.help)return yw(),0;for(let x of n.notices)process.stdout.write(`${x}
866
- `);let o=!!process.stdin.isTTY&&!n.nonInteractive,i=Mx.homedir();if(i.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
867
- `),2;if(n.hooksOnly)return Ij({homeDir:i,isInteractive:o,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:Mt({projectRoot:i,homeDir:i,platform:process.platform,env:process.env}),probe:ce,noRules:n.noRules,cwd:process.cwd()});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let x=await ga(process.cwd());if(x.length===0)a=await kw(process.cwd());else if(x.length===1||!n.team)a=x[0];else{let T=await Sw(x,o);if(T===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick the one --team writes into.
866
+ `),l.outcome==="failed"?1:0}function Sj(e){let t=e.repo??"this directory (no repository)";switch(e.outcome){case"refreshed":return`maind: refreshed ${e.files.length} rule file(s) with the conventions for ${t}: ${e.files.join(", ")}`;case"unchanged":return`maind: rule files already carry the current conventions for ${t}`;case"throttled":return`maind: rule files were checked for ${t} less than 12 h ago (--force to check now)`;case"no_channels":return"maind: no user-level rule files to refresh (install sets them up with your consent)";case"opted_out":return`maind: ${zp} is set \u2014 nothing refreshed`;case"failed":return`maind: rule files not refreshed \u2014 ${e.error??"unknown error"}`}}function Ej(e){try{return dj(e)&&uj(e).isDirectory()}catch{return!1}}function wc(e){return lj("sha256").update(e).digest("hex")}async function Px(e){let t={version:1,files:{}};try{let n=JSON.parse(await fj(e,"utf8"));if(!n||typeof n.files!="object"||n.files===null)return t;let r={};for(let[o,i]of Object.entries(n.files))i&&typeof i.repo=="string"&&typeof i.checked_at=="string"&&typeof i.content=="string"&&(r[o]={repo:i.repo,checked_at:i.checked_at,content:i.content});return{version:1,files:r}}catch{return t}}async function Mx(e,t,n){let r={};for(let[i,a]of Object.entries(t.files)){let c=Date.parse(a.checked_at);!Number.isNaN(c)&&n-c<vj&&(r[i]=a)}await pj(_j(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await hj(o,JSON.stringify({version:1,files:r},null,2),{mode:384}),await mj(o,e)}var zp,Jp,Ox,vj,bc,kc=w(()=>{"use strict";_c();re();at();ie();Je();Wa();pe();Fe();zp="MAIND_NO_RULES_REFRESH",Jp=bj(Te,"rules-refresh.json"),Ox=12*60*60*1e3,vj=30*24*60*60*1e3;s(go,"repoIdentity");s(Dx,"repoDisplayName");s(Yp,"refreshUserRules");s(vc,"recordRulesCheck");s(kj,"refreshRulesForSession");bc=["Usage: maind-mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]","","Refreshes the user-level rule files that exist (GitHub Copilot, Cline, Continue)","with the conventions of the repository at <dir> (default: the current directory;","its git root). Never creates a file. At most once per 12 h per repository and","only when the content changed; --force skips the 12 h. MAIND_NO_RULES_REFRESH=1","makes it a no-op. Exit 0 refreshed/unchanged/throttled/no_channels/opted_out,","2 usage error, 1 failure. --json prints {outcome, repo, files}.",""].join(`
867
+ `);s(xj,"runRefreshRules");s(Sj,"humanLine");s(Ej,"isDirectory");s(wc,"fileKey");s(Px,"readState");s(Mx,"writeState")});import*as $x from"node:os";async function Lx(e){let t=Date.now(),n;try{n=yw(e)}catch(x){if(x instanceof Ye)return process.stderr.write(`error: ${x.message}
868
+ `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw x}if(n.help)return _w(),0;for(let x of n.notices)process.stdout.write(`${x}
869
+ `);let o=!!process.stdin.isTTY&&!n.nonInteractive,i=$x.homedir();if(i.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
870
+ `),2;if(n.hooksOnly)return Oj({homeDir:i,isInteractive:o,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:$t({projectRoot:i,homeDir:i,platform:process.platform,env:process.env}),probe:ce,noRules:n.noRules,cwd:process.cwd()});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let x=await ya(process.cwd());if(x.length===0)a=await xw(process.cwd());else if(x.length===1||!n.team)a=x[0];else{let T=await Ew(x,o);if(T===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick the one --team writes into.
868
871
  `);for(let D of x)process.stderr.write(` candidate: ${D}
869
- `);return 2}a=T}}let c=new mi,l=(process.env.MAIND_MCP_URL??"").trim()||Sj;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
872
+ `);return 2}a=T}}let c=new mi,l=(process.env.MAIND_MCP_URL??"").trim()||Rj;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
870
873
  `),process.stdout.write(`maind install \u2014 project root: ${a}${n.team?" (--team writes AGENTS.md and .mcp.json here)":" (nothing is written here without --team)"}
871
874
  `),process.stdout.write(` \u2014 mcp endpoint: ${l}
872
875
 
873
- `);let d=Mt({projectRoot:a,homeDir:i,platform:process.platform,env:process.env,bridgeEntry:oe()}),u=fi(d);if(u=pw(u,n.client),n.skipCodex&&(u=u.filter(x=>x.key!=="codex-cli")),u.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
876
+ `);let d=$t({projectRoot:a,homeDir:i,platform:process.platform,env:process.env,bridgeEntry:oe()}),u=fi(d);if(u=fw(u,n.client),n.skipCodex&&(u=u.filter(x=>x.key!=="codex-cli")),u.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
874
877
  `:`error: no client targets selected (did you skip all of them?)
875
- `),c.print(process.stdout),2;let p=await lk({bridgeVersion:H,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(`
878
+ `),c.print(process.stdout),2;let p=await dk({bridgeVersion:H,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(`
876
879
  pairing failed: ${p.result.detail??"unknown"}
877
880
  Skipping remaining steps.
878
- `),c.print(process.stdout),2;let f=De(Pe(i,process.env,process.platform));for(let x of u){if(x.scope==="project"&&!n.team){c.add({target:x.key,action:"skip",status:"skipped",detail:f.enabled?"a repository file \u2014 install --team writes it (ADR-364); the maind plugin carries the server for you":"a repository file \u2014 install --team writes it (ADR-364); ~/.claude.json carries the server for you"});continue}if(x.key==="claude-code-user"&&f.enabled){c.add({target:x.key,action:"skip",status:"skipped",detail:Zv(f)});continue}let T=Tw({target:x,explicitFamily:n.client,probe:ce});if(T!==null){c.add(T);continue}let D=ow({mcpUrl:l,clientFamily:x.clientFamilyEnv}),F;x.kind==="json"?F=await Ow(x,D,n.dryRun):F=await Pw(x,D,n.dryRun),c.add(F)}let h=go(a),g=Fx(()=>fr(p.apiKey,h.projectKey,{allowFetch:!n.dryRun,clientFamily:"mcp-bridge"}));c.add(await Vu(i,n.dryRun)),n.team?c.add(await Vw({projectRoot:a,conventions:g,dryRun:n.dryRun})):c.add({target:Ej,action:"skip",status:"skipped",detail:Cj});let y={homeDir:i,isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},_=await Lx(y,f);for(let x of _)c.add(x);let b=Kv(a,_);b!==null&&c.add(b),c.add(await vp({isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout})),c.add(await Qw({isInteractive:o,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let v=u.some(x=>x.clientFamilyEnv==="cursor");if(v){let x=await Ep({...y,explicit:n.client==="cursor",presence:{ctx:d,probe:ce}});for(let T of x)c.add(T)}(n.client===null||n.client==="codex")&&c.add(await Rp({...y,skipCodex:n.skipCodex,explicit:n.client==="codex",presence:{ctx:d,probe:ce}}));let k=ir(d,ce).filter(x=>n.client===null||x.family===n.client);if(k.length>0){let x=await Ap({homeDir:i,isInteractive:o,full:n.full,skip:n.noRules,dryRun:n.dryRun,out:process.stdout,explicitFamily:n.client,probe:ce,content:s(async()=>({repo:h.name,conventions:await g()}),"content"),onChecked:s((T,D)=>wc(T,D,h.key),"onChecked")},k);for(let T of x)c.add(T)}!n.team&&v&&(n.client==="cursor"||Ne(Pt(d),ce))&&c.add({target:Rj,action:"advise",status:"skipped",detail:Tj});let E=sc();E.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${E.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await uk({enabled:n.telemetry||n.full,installerVersion:H,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let S=c.exitCode(),R=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
881
+ `),c.print(process.stdout),2;let f=De(Pe(i,process.env,process.platform));for(let x of u){if(x.scope==="project"&&!n.team){c.add({target:x.key,action:"skip",status:"skipped",detail:f.enabled?"a repository file \u2014 install --team writes it (ADR-364); the maind plugin carries the server for you":"a repository file \u2014 install --team writes it (ADR-364); ~/.claude.json carries the server for you"});continue}if(x.key==="claude-code-user"&&f.enabled){c.add({target:x.key,action:"skip",status:"skipped",detail:Qv(f)});continue}let T=Aw({target:x,explicitFamily:n.client,probe:ce});if(T!==null){c.add(T);continue}let D=iw({mcpUrl:l,clientFamily:x.clientFamilyEnv}),F;x.kind==="json"?F=await Dw(x,D,n.dryRun):F=await Mw(x,D,n.dryRun),c.add(F)}let h=go(a),g=jx(()=>fr(p.apiKey,h.projectKey,{allowFetch:!n.dryRun,clientFamily:"mcp-bridge"}));c.add(await Vu(i,n.dryRun)),n.team?c.add(await qw({projectRoot:a,conventions:g,dryRun:n.dryRun})):c.add({target:Cj,action:"skip",status:"skipped",detail:Aj});let y={homeDir:i,isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},_=await Fx(y,f);for(let x of _)c.add(x);let b=Gv(a,_);b!==null&&c.add(b),c.add(await vp({isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout})),c.add(await ev({isInteractive:o,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let v=u.some(x=>x.clientFamilyEnv==="cursor");if(v){let x=await Ep({...y,explicit:n.client==="cursor",presence:{ctx:d,probe:ce}});for(let T of x)c.add(T)}(n.client===null||n.client==="codex")&&c.add(await Rp({...y,skipCodex:n.skipCodex,explicit:n.client==="codex",presence:{ctx:d,probe:ce}}));let k=ir(d,ce).filter(x=>n.client===null||x.family===n.client);if(k.length>0){let x=await Ap({homeDir:i,isInteractive:o,full:n.full,skip:n.noRules,dryRun:n.dryRun,out:process.stdout,explicitFamily:n.client,probe:ce,content:s(async()=>({repo:h.name,conventions:await g()}),"content"),onChecked:s((T,D)=>vc(T,D,h.key),"onChecked")},k);for(let T of x)c.add(T)}!n.team&&v&&(n.client==="cursor"||Ne(Mt(d),ce))&&c.add({target:Tj,action:"advise",status:"skipped",detail:Ij});let E=ac();E.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${E.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await pk({enabled:n.telemetry||n.full,installerVersion:H,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let S=c.exitCode(),R=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
879
882
  DRY RUN finished in ${R}s. No files were modified. Re-run without --dry-run to apply.
880
883
  `):process.stdout.write(`
881
884
  Finished in ${R}s. Restart your MCP client so it picks up the new server entry.
882
885
  `);let P=we({entryPath:oe(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),K=P.fallbackReason===null?`${ze(P)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${K}
883
886
  `),S===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.
884
- `),S}async function Lx(e,t){if(t.enabled&&!e.skip)return[{target:Zp,action:"skip",status:"skipped",detail:Ba(t)}];let n=await Xw(e);return e.dryRun||await zw(je,n),n}function Fx(e){let t=null;return()=>t??=e()}async function Qp(e,t){let n=[];n.push(await Vu(e.homeDir,e.dryRun)),n.push(...await Ep({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(await Rp({...e,skipCodex:!1,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let r=(t.identity??go)(t.cwd),o=(t.apiKey??Aj)(),i=Fx(()=>fr(o,r.projectKey,{allowFetch:!e.dryRun,clientFamily:"mcp-bridge"}));return n.push(...await Ap({...e,skip:t.noRules,explicitFamily:null,probe:t.probe,content:s(async()=>({repo:r.name,conventions:await i()}),"content"),onChecked:s((a,c)=>wc(a,c,r.key),"onChecked")},ir(t.ctx,t.probe))),n}function Aj(){try{return z()}catch{return null}}async function Ij(e,t){let n=new mi;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
887
+ `),S}async function Fx(e,t){if(t.enabled&&!e.skip)return[{target:Zp,action:"skip",status:"skipped",detail:Ka(t)}];let n=await Zw(e);return e.dryRun||await Jw(je,n),n}function jx(e){let t=null;return()=>t??=e()}async function Qp(e,t){let n=[];n.push(await Vu(e.homeDir,e.dryRun)),n.push(...await Ep({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(await Rp({...e,skipCodex:!1,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let r=(t.identity??go)(t.cwd),o=(t.apiKey??Nj)(),i=jx(()=>fr(o,r.projectKey,{allowFetch:!e.dryRun,clientFamily:"mcp-bridge"}));return n.push(...await Ap({...e,skip:t.noRules,explicitFamily:null,probe:t.probe,content:s(async()=>({repo:r.name,conventions:await i()}),"content"),onChecked:s((a,c)=>vc(a,c,r.key),"onChecked")},ir(t.ctx,t.probe))),n}function Nj(){try{return z()}catch{return null}}async function Oj(e,t){let n=new mi;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
885
888
  `),e.out.write(`maind install --hooks-only \u2014 the user-level channels: Claude Code hooks in ~/.claude/settings.json; Cursor's and Codex's hooks and the Copilot, Cline and Continue rule files where those clients are installed
886
- `);let r=De(Pe(e.homeDir,process.env,process.platform));for(let o of await Lx(e,r))n.add(o);n.add(await vp({isInteractive:e.isInteractive,full:e.full,skip:e.skip,dryRun:e.dryRun,out:e.out}));for(let o of await Qp(e,t))n.add(o);return n.print(e.out),e.out.write(e.dryRun?`
889
+ `);let r=De(Pe(e.homeDir,process.env,process.platform));for(let o of await Fx(e,r))n.add(o);n.add(await vp({isInteractive:e.isInteractive,full:e.full,skip:e.skip,dryRun:e.dryRun,out:e.out}));for(let o of await Qp(e,t))n.add(o);return n.print(e.out),e.out.write(e.dryRun?`
887
890
  DRY RUN finished. No files were modified.
888
891
  `:`
889
892
  Claude Code reads hooks when a session starts; Cursor reloads ~/.cursor/hooks.json by itself; Codex asks you to trust a new hook once (/hooks).
890
- `),n.exitCode()}var Sj,Ej,Rj,Cj,Tj,Zp,ef=w(()=>{"use strict";Fe();_w();bw();Fu();Je();_t();ie();Xr();Dw();Mw();Gw();qw();Ca();zu();ve();ev();Uv();Gv();zv();oo();Cp();Ga();dk();pk();hn();yc();re();vc();Sj="https://mcp.maind.dev/mcp",Ej="repository",Rj="team-option",Cj="nothing written into the repository (ADR-364) \u2014 install --team writes the AGENTS.md conventions block and the project .mcp.json",Tj="Cursor can drop the context of its sessionStart hook in a race Cursor confirms \u2014 for teams that work mostly in Cursor, install --team puts the conventions into the repository's AGENTS.md, which Cursor reads reliably";s($x,"runInstall");Zp="hooks:~/.claude/settings.json";s(Lx,"claudeCodeHooks");s(Fx,"memo");s(Qp,"setUpUserChannels");s(Aj,"safeApiKey");s(Ij,"runHooksOnly")});import{mkdirSync as Kx,rmdirSync as Gx,statSync as Dj}from"node:fs";import{join as Wx}from"node:path";import{setTimeout as Pj}from"node:timers/promises";function Vx(e){return Wx(e,".maind","index-refresh.lock")}function Sc(e,t=Date.now()){let n=Vx(e);try{if(t-Dj(n).mtimeMs<Mj)return!1;Gx(n)}catch{}try{return Kx(n,{recursive:!1}),!0}catch{return!1}}function Fi(e){try{Gx(Vx(e))}catch{}}async function qx(e,t,n={}){let r=n.now??Date.now,o=n.sleep??(a=>Pj(a).then(()=>{})),i=r()+(n.waitMs??3e4);try{Kx(Wx(e,".maind"),{recursive:!0})}catch{}for(;!Sc(e,r());){if(r()>=i)return{locked:!1};await o(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Fi(e)}}var Mj,tf=w(()=>{"use strict";Mj=30*6e4;s(Vx,"lockPath");s(Sc,"acquireLock");s(Fi,"releaseLock");s(qx,"withIndexLock")});import{execFile as lS}from"node:child_process";import{randomUUID as o1}from"node:crypto";function d1(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return cf.test(t)?t:o1()}function lf(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function u1(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 p1(e){return await new Promise(t=>{lS("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(f1(r))})})}function f1(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 m1(){return await new Promise(e=>{lS("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 h1(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function g1(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),o=cf.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:o,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(i=>{cf.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var cS,dS,i1,s1,a1,c1,l1,cf,Tc,df=w(()=>{"use strict";Ue();cS=45e3,dS=3e4,i1=5,s1=120,a1=3e4,c1=15*6e4,l1=1500,cf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(d1,"resolveClientSessionId");s(lf,"autoAnnounceDisabled");s(u1,"autoWorkingPathsEnabled");Tc=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;nestedProjectKeys;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??Q)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??m1,this.gitBranchObject=t.gitBranchObject??p1,this.log=t.log??(o=>process.stderr.write(o+`
891
- `)),this.machineLabel=h1(r?.machine_label),this.enabled=this.projectKey!==null&&!lf(n,r),this.workingPathsEnabled=u1(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??g1(n,d1(n)),this.sessionMeta=t.sessionMeta??null,this.nestedProjectKeys=t.nestedProjectKeys??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<cS||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<cS||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<i1||(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,l1).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(a1*2**(this.consecutiveFailures-1),c1);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 i=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 (${i} \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:s1,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let i=await this.gitBranch();if(i&&(r.branch=i),this.lastBranch=i,i)try{let a=await this.gitBranchObject(i);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.nestedProjectKeys!==null)try{let a=this.nestedProjectKeys();a.length>0&&(r.nested_project_keys=[...a])}catch{}if(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 o=await this.postToolCall("announce_session",r);if(t==="active"&&o!==null&&typeof o=="object"){let i=o;if(i.ok===!0&&typeof i.session_id=="string")try{this.identity.adopt(i.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(o!=null){let i={sessionId:this.sessionId,branch:this.lastBranch},a=typeof o=="object"?o:null;if(a!==null&&a.ok===!0)this.snapshot.write(o,i);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,i)}}}catch{}}};s(p1,"defaultGitBranchObject");s(f1,"normalizeObjectId");s(m1,"defaultGitBranch");s(h1,"normalizeMachineLabel");s(g1,"staticIdentity")});import{mkdirSync as uS,readdirSync as hS,readFileSync as y1,renameSync as pS,statSync as _1,unlinkSync as uf,writeFileSync as fS}from"node:fs";import{homedir as b1}from"node:os";import{join as yo}from"node:path";function gS(){return yo(b1(),".maind","presence")}function yS(e,t){return yo(e,t)}function _S(e){let t=e.baseDir??gS(),n=yS(t,e.projectKey),r=e.pid??process.pid,o=e.ppid??process.ppid,i=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=s(d=>{if(c!==null&&c!==d)try{uf(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:o,cwd:i,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[],...(()=>{let y=us(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};uS(n,{recursive:!0,mode:448});let h=yo(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;fS(g,JSON.stringify(f),{mode:384}),pS(g,h),l(h),mS(n,a(),h)}catch{}},endSession(){try{c&&uf(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:o,cwd:i,branch:u.branch,peers:[],conflicts:[],announce_error:d};uS(n,{recursive:!0,mode:448});let f=yo(n,`${u.sessionId}.json`),h=`${f}.tmp-${r}`;fS(h,JSON.stringify(p),{mode:384}),pS(h,f),l(f),mS(n,a(),f)}catch{}}}}function mS(e,t,n){try{for(let r of hS(e)){if(!r.endsWith(".json"))continue;let o=yo(e,r);if(o!==n)try{t-_1(o).mtimeMs>w1&&uf(o)}catch{}}}catch{}}function gr(e,t=gS()){try{let n=yS(t,e),r=[];for(let o of hS(n))if(o.endsWith(".json"))try{let i=JSON.parse(y1(yo(n,o),"utf8")),a=v1(i);a&&r.push(a)}catch{}return r.sort((o,i)=>i.written_at.localeCompare(o.written_at)),r}catch{return[]}}function v1(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=us(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var w1,ji=w(()=>{"use strict";Oo();w1=120*6e4;s(gS,"presenceSnapshotBaseDir");s(yS,"projectDir");s(_S,"createSnapshotStore");s(mS,"pruneStale");s(gr,"readSnapshots");s(v1,"parseSnapshot")});import{execFileSync as O1}from"node:child_process";import{createHash as D1,randomUUID as P1}from"node:crypto";import{existsSync as M1,mkdirSync as $1,readdirSync as L1,readFileSync as vS,renameSync as F1,statSync as ff,unlinkSync as kS,writeFileSync as j1}from"node:fs";import{homedir as H1}from"node:os";import{basename as U1,join as bn}from"node:path";function _o(e){return bn(e??bn(H1(),".maind","presence"),"identity")}function Bi(e,t){if(e){let n=U1(e).replace(/\.jsonl$/i,"");if(Ui.test(n))return n.toLowerCase()}return t&&Ui.test(t)?t.toLowerCase():null}function xS(e){let t=e.nowMs??Date.now();$1(e.dir,{recursive:!0,mode:448});let n=bn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,o={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(vS(n,"utf8"));l.session_id===e.sessionId&&(o={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let i=e.transcriptPath??o.transcript_path,a=e.model??o.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(),...i?{transcript_path:i}:{},...a?{model:a}:{}};j1(r,JSON.stringify(c,null,2)+`
892
- `,{mode:384}),F1(r,n),V1(e.dir,t)}function SS(e,t,n,r=Date.now()){try{let o=ff(bn(e,`${t}.json`));return r-o.mtimeMs>n}catch{return!0}}function ES(e,t){try{kS(bn(e,`${t}.json`))}catch{}}function V1(e,t){try{for(let n of L1(e))if(n.endsWith(".json"))try{let r=ff(bn(e,n));t-r.mtimeMs>K1&&kS(bn(e,n))}catch{}}catch{}}function q1(e){return RS(e)?.file??null}function RS(e){let t=bn(e.dir,`${e.agentPid}.json`);try{if(!M1(t))return null;let n=ff(t);if(n.mtimeMs<e.bridgeStartMs-G1)return null;let r=JSON.parse(vS(t,"utf8"));if(typeof r!="object"||r===null)return null;let o=r;return o.v!==1||typeof o.transcript_stem!="string"||!Ui.test(o.transcript_stem)||typeof o.session_id!="string"||typeof o.cwd!="string"||o.agent_pid!==e.agentPid||!z1(o.cwd,e.cwd)?null:{file:o,mtimeMs:n.mtimeMs}}catch{return null}}function wS(e){return e.replace(/\/+$/,"")}function z1(e,t){let n=wS(e),r=wS(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function J1(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=D1("sha1").update(n).update(e,"utf8").digest(),o=Buffer.from(r.subarray(0,16));o[6]=o[6]&15|80,o[8]=o[8]&63|128;let i=o.toString("hex");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Y1(e){if(process.platform==="win32")return null;try{let t=O1("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function X1(){try{return ae()}catch{return null}}var Ui,B1,K1,G1,W1,Ac,Ic=w(()=>{"use strict";re();Ui=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,B1=8,K1=48*60*6e4,G1=6e4,W1="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(_o,"identityDirPath");s(Bi,"transcriptStemOf");s(xS,"writeAgentIdentityFile");s(SS,"identityFileStale");s(ES,"deleteAgentIdentityFile");s(V1,"pruneIdentityDir");s(q1,"readAgentIdentityFile");s(RS,"readAgentIdentityEntry");s(wS,"normDir");s(z1,"sameSessionTree");s(J1,"uuidV5");s(Y1,"processStartTime");Ac=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??_o(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Ui.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 o=(t.deviceId??X1)(),i=(t.ppidStart??Y1)(this.agentPid);if(o!==null&&i!==null&&t.projectKey!==null){this.id=J1(`${o}|${this.agentPid}|${i}|${t.projectKey}`,W1),this.source="derived";return}this.id=P1(),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(!Ui.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>B1&&this.aliases.shift())}activityAtMs(){return RS({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 q1({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(X1,"defaultDeviceId")});import{applyEdits as cH,modify as lH,parse as dH}from"jsonc-parser";function gf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function IS(e){return gf(e)&&typeof e.command=="string"}function yf(e){if(e===null||e.trim().length===0)return[];let t=[],n=dH(e,t,{allowTrailingComma:!0});if(t.length>0||!gf(n))return[];let r=[];return gf(n.mcpServers)&&IS(n.mcpServers.maind)&&r.push(["mcpServers","maind"]),IS(n.maind)&&r.push(["maind"]),r}function NS(e,t){let n=yf(e);if(e===null||n.length===0)return null;let r=e;for(let o of n)r=cH(r,lH(r,o,void 0,{}));return{file:t,raw:e,next:r,removed:n}}function OS(e,t,n){return n?e===null?`No maind server in ~/.claude.json next to the maind plugin \u2014 Claude Code runs one maind server.
893
+ `),n.exitCode()}var Rj,Cj,Tj,Aj,Ij,Zp,ef=w(()=>{"use strict";Fe();bw();ww();Fu();Je();_t();ie();Xr();Pw();$w();Ww();zw();Ta();zu();ve();tv();Bv();Wv();Jv();oo();Cp();Wa();uk();fk();hn();_c();re();kc();Rj="https://mcp.maind.dev/mcp",Cj="repository",Tj="team-option",Aj="nothing written into the repository (ADR-364) \u2014 install --team writes the AGENTS.md conventions block and the project .mcp.json",Ij="Cursor can drop the context of its sessionStart hook in a race Cursor confirms \u2014 for teams that work mostly in Cursor, install --team puts the conventions into the repository's AGENTS.md, which Cursor reads reliably";s(Lx,"runInstall");Zp="hooks:~/.claude/settings.json";s(Fx,"claudeCodeHooks");s(jx,"memo");s(Qp,"setUpUserChannels");s(Nj,"safeApiKey");s(Oj,"runHooksOnly")});import{mkdirSync as Gx,rmdirSync as Wx,statSync as Mj}from"node:fs";import{join as Vx}from"node:path";import{setTimeout as $j}from"node:timers/promises";function qx(e){return Vx(e,".maind","index-refresh.lock")}function Ec(e,t=Date.now()){let n=qx(e);try{if(t-Mj(n).mtimeMs<Lj)return!1;Wx(n)}catch{}try{return Gx(n,{recursive:!1}),!0}catch{return!1}}function Fi(e){try{Wx(qx(e))}catch{}}async function zx(e,t,n={}){let r=n.now??Date.now,o=n.sleep??(a=>$j(a).then(()=>{})),i=r()+(n.waitMs??3e4);try{Gx(Vx(e,".maind"),{recursive:!0})}catch{}for(;!Ec(e,r());){if(r()>=i)return{locked:!1};await o(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Fi(e)}}var Lj,tf=w(()=>{"use strict";Lj=30*6e4;s(qx,"lockPath");s(Ec,"acquireLock");s(Fi,"releaseLock");s(zx,"withIndexLock")});import{execFile as dS}from"node:child_process";import{randomUUID as s1}from"node:crypto";function p1(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return cf.test(t)?t:s1()}function lf(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function f1(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 m1(e){return await new Promise(t=>{dS("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(h1(r))})})}function h1(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 g1(){return await new Promise(e=>{dS("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 y1(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function _1(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),o=cf.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:o,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(i=>{cf.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var lS,uS,a1,c1,l1,d1,u1,cf,Ac,df=w(()=>{"use strict";Ue();lS=45e3,uS=3e4,a1=5,c1=120,l1=3e4,d1=15*6e4,u1=1500,cf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(p1,"resolveClientSessionId");s(lf,"autoAnnounceDisabled");s(f1,"autoWorkingPathsEnabled");Ac=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;nestedProjectKeys;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??Q)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??g1,this.gitBranchObject=t.gitBranchObject??m1,this.log=t.log??(o=>process.stderr.write(o+`
894
+ `)),this.machineLabel=y1(r?.machine_label),this.enabled=this.projectKey!==null&&!lf(n,r),this.workingPathsEnabled=f1(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??_1(n,p1(n)),this.sessionMeta=t.sessionMeta??null,this.nestedProjectKeys=t.nestedProjectKeys??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<lS||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<lS||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<a1||(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,u1).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(l1*2**(this.consecutiveFailures-1),d1);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 i=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 (${i} \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:c1,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let i=await this.gitBranch();if(i&&(r.branch=i),this.lastBranch=i,i)try{let a=await this.gitBranchObject(i);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.nestedProjectKeys!==null)try{let a=this.nestedProjectKeys();a.length>0&&(r.nested_project_keys=[...a])}catch{}if(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 o=await this.postToolCall("announce_session",r);if(t==="active"&&o!==null&&typeof o=="object"){let i=o;if(i.ok===!0&&typeof i.session_id=="string")try{this.identity.adopt(i.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(o!=null){let i={sessionId:this.sessionId,branch:this.lastBranch},a=typeof o=="object"?o:null;if(a!==null&&a.ok===!0)this.snapshot.write(o,i);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,i)}}}catch{}}};s(m1,"defaultGitBranchObject");s(h1,"normalizeObjectId");s(g1,"defaultGitBranch");s(y1,"normalizeMachineLabel");s(_1,"staticIdentity")});import{mkdirSync as pS,readdirSync as gS,readFileSync as b1,renameSync as fS,statSync as w1,unlinkSync as uf,writeFileSync as mS}from"node:fs";import{homedir as v1}from"node:os";import{join as yo}from"node:path";function yS(){return yo(v1(),".maind","presence")}function _S(e,t){return yo(e,t)}function bS(e){let t=e.baseDir??yS(),n=_S(t,e.projectKey),r=e.pid??process.pid,o=e.ppid??process.ppid,i=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=s(d=>{if(c!==null&&c!==d)try{uf(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:o,cwd:i,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[],...(()=>{let y=us(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};pS(n,{recursive:!0,mode:448});let h=yo(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;mS(g,JSON.stringify(f),{mode:384}),fS(g,h),l(h),hS(n,a(),h)}catch{}},endSession(){try{c&&uf(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:o,cwd:i,branch:u.branch,peers:[],conflicts:[],announce_error:d};pS(n,{recursive:!0,mode:448});let f=yo(n,`${u.sessionId}.json`),h=`${f}.tmp-${r}`;mS(h,JSON.stringify(p),{mode:384}),fS(h,f),l(f),hS(n,a(),f)}catch{}}}}function hS(e,t,n){try{for(let r of gS(e)){if(!r.endsWith(".json"))continue;let o=yo(e,r);if(o!==n)try{t-w1(o).mtimeMs>k1&&uf(o)}catch{}}}catch{}}function gr(e,t=yS()){try{let n=_S(t,e),r=[];for(let o of gS(n))if(o.endsWith(".json"))try{let i=JSON.parse(b1(yo(n,o),"utf8")),a=x1(i);a&&r.push(a)}catch{}return r.sort((o,i)=>i.written_at.localeCompare(o.written_at)),r}catch{return[]}}function x1(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=us(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var k1,ji=w(()=>{"use strict";Oo();k1=120*6e4;s(yS,"presenceSnapshotBaseDir");s(_S,"projectDir");s(bS,"createSnapshotStore");s(hS,"pruneStale");s(gr,"readSnapshots");s(x1,"parseSnapshot")});import{execFileSync as P1}from"node:child_process";import{createHash as M1,randomUUID as $1}from"node:crypto";import{existsSync as L1,mkdirSync as F1,readdirSync as j1,readFileSync as kS,renameSync as H1,statSync as ff,unlinkSync as xS,writeFileSync as U1}from"node:fs";import{homedir as B1}from"node:os";import{basename as K1,join as bn}from"node:path";function _o(e){return bn(e??bn(B1(),".maind","presence"),"identity")}function Bi(e,t){if(e){let n=K1(e).replace(/\.jsonl$/i,"");if(Ui.test(n))return n.toLowerCase()}return t&&Ui.test(t)?t.toLowerCase():null}function SS(e){let t=e.nowMs??Date.now();F1(e.dir,{recursive:!0,mode:448});let n=bn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,o={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(kS(n,"utf8"));l.session_id===e.sessionId&&(o={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let i=e.transcriptPath??o.transcript_path,a=e.model??o.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(),...i?{transcript_path:i}:{},...a?{model:a}:{}};U1(r,JSON.stringify(c,null,2)+`
895
+ `,{mode:384}),H1(r,n),z1(e.dir,t)}function ES(e,t,n,r=Date.now()){try{let o=ff(bn(e,`${t}.json`));return r-o.mtimeMs>n}catch{return!0}}function RS(e,t){try{xS(bn(e,`${t}.json`))}catch{}}function z1(e,t){try{for(let n of j1(e))if(n.endsWith(".json"))try{let r=ff(bn(e,n));t-r.mtimeMs>W1&&xS(bn(e,n))}catch{}}catch{}}function J1(e){return CS(e)?.file??null}function CS(e){let t=bn(e.dir,`${e.agentPid}.json`);try{if(!L1(t))return null;let n=ff(t);if(n.mtimeMs<e.bridgeStartMs-V1)return null;let r=JSON.parse(kS(t,"utf8"));if(typeof r!="object"||r===null)return null;let o=r;return o.v!==1||typeof o.transcript_stem!="string"||!Ui.test(o.transcript_stem)||typeof o.session_id!="string"||typeof o.cwd!="string"||o.agent_pid!==e.agentPid||!Y1(o.cwd,e.cwd)?null:{file:o,mtimeMs:n.mtimeMs}}catch{return null}}function vS(e){return e.replace(/\/+$/,"")}function Y1(e,t){let n=vS(e),r=vS(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function X1(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=M1("sha1").update(n).update(e,"utf8").digest(),o=Buffer.from(r.subarray(0,16));o[6]=o[6]&15|80,o[8]=o[8]&63|128;let i=o.toString("hex");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Z1(e){if(process.platform==="win32")return null;try{let t=P1("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function Q1(){try{return ae()}catch{return null}}var Ui,G1,W1,V1,q1,Ic,Nc=w(()=>{"use strict";re();Ui=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,G1=8,W1=48*60*6e4,V1=6e4,q1="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(_o,"identityDirPath");s(Bi,"transcriptStemOf");s(SS,"writeAgentIdentityFile");s(ES,"identityFileStale");s(RS,"deleteAgentIdentityFile");s(z1,"pruneIdentityDir");s(J1,"readAgentIdentityFile");s(CS,"readAgentIdentityEntry");s(vS,"normDir");s(Y1,"sameSessionTree");s(X1,"uuidV5");s(Z1,"processStartTime");Ic=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??_o(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Ui.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 o=(t.deviceId??Q1)(),i=(t.ppidStart??Z1)(this.agentPid);if(o!==null&&i!==null&&t.projectKey!==null){this.id=X1(`${o}|${this.agentPid}|${i}|${t.projectKey}`,q1),this.source="derived";return}this.id=$1(),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(!Ui.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>G1&&this.aliases.shift())}activityAtMs(){return CS({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 J1({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(Q1,"defaultDeviceId")});import{applyEdits as dH,modify as uH,parse as pH}from"jsonc-parser";function gf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function NS(e){return gf(e)&&typeof e.command=="string"}function yf(e){if(e===null||e.trim().length===0)return[];let t=[],n=pH(e,t,{allowTrailingComma:!0});if(t.length>0||!gf(n))return[];let r=[];return gf(n.mcpServers)&&NS(n.mcpServers.maind)&&r.push(["mcpServers","maind"]),NS(n.maind)&&r.push(["maind"]),r}function OS(e,t){let n=yf(e);if(e===null||n.length===0)return null;let r=e;for(let o of n)r=dH(r,uH(r,o,void 0,{}));return{file:t,raw:e,next:r,removed:n}}function DS(e,t,n){return n?e===null?`No maind server in ~/.claude.json next to the maind plugin \u2014 Claude Code runs one maind server.
893
896
  `:[`The maind plugin is enabled and brings its own MCP server, and ${e.file} still registers one \u2014 Claude Code starts both:`,"",...e.removed.map(o=>` remove ${o.join(".")}`),"",t?"Applying (a file that changed since it was read is left alone). Claude Code rewrites this file while it runs \u2014 close its sessions first, then restart it:":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --remove-duplicate-mcp --yes (with Claude Code closed \u2014 it rewrites this file while it runs)"].join(`
894
897
  `)+`
895
898
  `:`The maind plugin is not enabled \u2014 the maind server in ~/.claude.json is the one Claude Code runs; nothing to remove.
896
- `}var _f=w(()=>{"use strict";s(gf,"isObject");s(IS,"isServerEntry");s(yf,"claudeUserMaindPaths");s(NS,"planDuplicateMcpRemoval");s(OS,"renderDuplicateMcpPlan")});import{createHash as uH}from"node:crypto";function mH(e){let t=new Set;return e.filter(n=>!t.has(n.sha256)&&(t.add(n.sha256),!0))}function bf(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
899
+ `}var _f=w(()=>{"use strict";s(gf,"isObject");s(NS,"isServerEntry");s(yf,"claudeUserMaindPaths");s(OS,"planDuplicateMcpRemoval");s(DS,"renderDuplicateMcpPlan")});import{createHash as fH}from"node:crypto";function gH(e){let t=new Set;return e.filter(n=>!t.has(n.sha256)&&(t.add(n.sha256),!0))}function bf(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
897
900
  `,n);if(r<0){t.push({text:e.slice(n),eol:""});break}let o=r>n&&e[r-1]==="\r";t.push({text:e.slice(n,o?r-1:r),eol:o?`\r
898
901
  `:`
899
- `}),n=r+1}return t}function hH(e){let t=bf(e),n=[],r=null;for(let o=0;o<t.length;o++){if(!t[o].text.startsWith(er))continue;let i=fH.find(a=>o+a.lines<=t.length&&PS(t.slice(o,o+a.lines).map(c=>c.text).join(`
900
- `))===a.sha256);if(i===void 0){r=`a "${er}" section (line ${o+1}) that is not a block the installer wrote \u2014 edited by hand, or an unknown variant`;continue}n.push({kind:"preamble",from:o,to:o+i.lines-1}),o+=i.lines-1}for(let o=0;o<t.length;o++){if(t[o].text.trim()!==wa)continue;let i=t.findIndex((c,l)=>l>o&&c.text.trim()===va);if(i<0){r=`a conventions block without its end marker (line ${o+1})`;break}let a=t.slice(o+1,i).some(c=>c.text.trim().startsWith(hi));n.push({kind:a?"team-conventions":"conventions",from:o,to:i}),o=i}return n.sort((o,i)=>o.from-i.from),{blocks:n,manual:r}}function gH(e,t){let n=bf(e),r=new Array(n.length).fill(!1);for(let a of t)if(a.kind!=="team-conventions"){for(let c=a.from;c<=a.to;c++)r[c]=!0;for(let c=a.from-1;c>=0&&!r[c]&&Oc(n[c]);c--)r[c]=!0}let o=0;for(;o<n.length&&r[o];)o++;if(o>0)for(;o<n.length&&Oc(n[o]);o++)r[o]=!0;let i=n.filter((a,c)=>!r[c]);return i.every(Oc)?null:i.map(a=>a.text+a.eol).join("")}function MS(e,t,n){let r=hH(n);if(r.blocks.length===0&&r.manual===null)return null;let o=s(p=>`${yH[p.kind]} (lines ${p.from+1}\u2013${p.to+1})`,"describe"),i=r.blocks.filter(p=>p.kind!=="team-conventions"),a=r.blocks.filter(p=>p.kind==="team-conventions");if(r.manual!==null)return{rel:e,path:t,raw:n,action:"manual",next:null,removes:[],keeps:[r.manual]};if(i.length===0)return{rel:e,path:t,raw:n,action:"keep",next:null,removes:[],keeps:a.map(o)};let c=gH(n,r.blocks),l=i.map(o);if(c===null)return{rel:e,path:t,raw:n,action:"delete",next:null,removes:l,keeps:[]};let d=bf(c).filter(p=>!Oc(p)).length-a.reduce((p,f)=>p+(f.to-f.from+1),0),u=[...a.map(o),...d>0?[`${d} line${d===1?"":"s"} of yours`]:[]];return{rel:e,path:t,raw:n,action:"edit",next:c,removes:l,keeps:u}}function yr(e){return e.some(t=>t.action==="edit"||t.action==="delete"||t.action==="manual")}function Dc(e){return e.filter(t=>t.action!=="keep").map(t=>{if(t.action==="manual")return`${t.rel} (by hand)`;let n=[...new Set(t.removes.map(r=>r.replace(/ \(lines.*$/,"")))];return`${t.rel} (${n.join(" + ")})`}).join(", ")}var DS,PS,pH,fH,Oc,yH,Ki=w(()=>{"use strict";ba();Zr();DS=["CLAUDE.md","AGENTS.md",".github/copilot-instructions.md",".cursorrules",".windsurfrules"],PS=s(e=>uH("sha256").update(e).digest("hex"),"sha256"),pH={lines:70,sha256:"2c7687dc2fd58b7c96d7f31c7b530c06c3fffe8710c6404a7e421ca7c8bf7714"},fH=mH([{lines:bt.split(`
901
- `).length,sha256:PS(bt)},pH,{lines:57,sha256:"72f5d6423e98eb01b2854b44dff290f2d8be1af1c8995f059dba5118530aafce"},{lines:56,sha256:"bf77aeeed9e96b8d0bfcba1feee0592256e2d49d64b53977bbd8f5b8323e5387"},{lines:21,sha256:"afdaf4a151cfd6fc9258392d86593e0604dae7518ffa8918cfc92bab9d5fd41b"}]);s(mH,"dedupe");s(bf,"splitLines");Oc=s(e=>e.text.trim()==="","isBlank");s(hH,"scanRepoFile");s(gH,"cutBlocks");yH={preamble:"maind preamble",conventions:"conventions block","team-conventions":"team conventions block (install --team)"};s(MS,"planRepoFile");s(yr,"hasMigratableBlocks");s(Dc,"summarizeRepoBlocks")});import{parse as _H}from"jsonc-parser";function wf(e,t){let n=e.split(/[.+-]/).slice(0,3).map(o=>Number.parseInt(o,10)||0),r=t.split(/[.+-]/).slice(0,3).map(o=>Number.parseInt(o,10)||0);for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function kf(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=_H(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,o=r.servers?.maind??r.mcpServers?.maind,i=o?.transport??o;return!i||typeof i.command!="string"?null:{command:i.command,args:Array.isArray(i.args)?i.args.filter(a=>typeof a=="string"):[]}}function bo(e,t){let n=`npm i -g ${wn}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Pc(e){let t=[],n=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${wn}`),r=[e.runningVersion,...e.nodeTrees.map(y=>y.bridgeVersion).filter(y=>y!==null)],o=e.latestVersion??r.sort(wf).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(y=>y.bridgeVersion!==null);if(e.nodeTrees.length>0){let y=e.pathWinner?.node??null,_=e.nodeTrees.find(v=>v.node===y);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)."}):_&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${_.node} tree (${_.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let v=e.nodeTrees.find(k=>k.node===e.nvmDefault);v&&v.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${v.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:bo(o,v.node)})}if(new Set(i.map(v=>v.bridgeVersion)).size>1)for(let v of i.filter(k=>wf(k.bridgeVersion,o)<0))t.push({check:"node-trees",level:"warn",message:`${v.node} carries bridge ${v.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:bo(o,v.node)})}let a=!1,c=new Map,l=s((y,_)=>{let b=c.get(y)??{version:e.installVersionOf(y),clients:[]};b.clients.push(_),c.set(y,b)},"noteInstall");for(let y of e.clientConfigs){let _=kf(y);if(_===null)continue;if(y.present===!1){t.push({check:"client-config",level:"warn",message:`${y.label}: ${y.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(a=!0,/(^|\/)npx(\.cmd)?$/.test(_.command)&&_.args.some(k=>k.includes(wn))){t.push({check:"client-config",level:"warn",message:`${y.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${bo(o)}, then set "command": "maind-mcp-bridge" (no args) in ${y.path}`});continue}let v=/(^|[\\/])node(\.exe)?$/.test(_.command);if(v&&_.args.length>0){let k=_.args[0];if(!e.fileExists(k)){t.push({check:"client-config",level:"error",message:`${y.label} runs ${k}, which does not exist.`,fix:`re-run \`npx -y ${wn}@${o} install\` to rewrite the entry`});continue}l(k,y.label)}else if(_.command.includes("/")||_.command.includes("\\")){if(!e.fileExists(_.command)){t.push({check:"client-config",level:"error",message:`${y.label} points at ${_.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${y.path} (after ${bo(o)})`});continue}}else if(_.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${y.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:bo(o,e.nvmDefault)});continue}v||(_.command.includes("/")||_.command.includes("\\")?l(_.command,y.label):_.command==="maind-mcp-bridge"&&e.pathWinner&&l(e.pathWinner.path,y.label)),t.push({check:"client-config",level:"ok",message:`${y.label}: ${[_.command,..._.args].join(" ")}`})}if(!a&&e.plugin?.enabled!==!0&&t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${wn} install`}),e.latestVersion!==null)for(let[y,_]of c){let b=_.clients.join(", ");if(_.version===null)t.push({check:"version",level:"info",message:`${b}: cannot tell which bridge version ${y} is.`});else if(wf(_.version,e.latestVersion)<0){let v=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(y)?.[1]??null;t.push({check:"version",level:"warn",message:`${b} run bridge ${_.version} (${y}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:v?bo(e.latestVersion,v):`npx -y ${wn}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${b} run bridge ${_.version} (published: ${e.latestVersion}).`})}for(let{dir:y,maind:_}of e.npxStaleDirs)t.push({check:"npx-cache",level:_?"error":"info",message:_?`a half-built better-sqlite3 was left in ${y} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${y} (another tool's npx entry, not maind's).`,fix:`rm -rf '${y.replace(/'/g,"'\\''")}'`});let d=e.envApiKey??e.apiKey;(e.deviceId===null||!$S.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"}),d===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):wH.test(d)?t.push({check:"credentials",level:e.deviceId!==null&&$S.test(e.deviceId)?"ok":"info",message:`key ${d.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 u=e.connection;if(u===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):u.outcome==="ok"||u.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${u.outcome==="ok"?"succeeded":"was paired"} at ${u.at} (bridge ${u.bridge_version}).`}):t.push({check:"connection",level:"error",message:u.outcome==="auth_failed"?`the server rejected the last connection (${u.at}${u.detail?`: ${u.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${u.at}${u.detail?`: ${u.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 y=Oe(e.claudeSettings,{fileExists:s(b=>e.fileExists(b),"fileExists")}),_=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let b of y){if(b.status==="missing"||b.status==="superseded")continue;if(b.status!=="ok"){t.push({check:"hooks",level:b.status==="broken"?"error":"warn",message:b.detail});continue}let v=b.command?/(\S+\/build\/index\.js)/.exec(b.command)?.[1]??null:null,k=v?e.installVersionOf(v):null;k!==null&&_!==null&&k!==_&&t.push({check:"hooks",level:"warn",message:`${b.event}/${b.subcommand} runs bridge ${k}, the MCP server runs ${_} \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"} ${b.subcommand}`})}t.some(b=>b.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}let p=e.plugin?.enabled===!0;if(p){let y=(e.declinedHooks??[]).includes(J),_=e.guardMode??"off",b=y&&e.claudeSettings!==null&&Mi(e.claudeSettings,{guardMode:_,fileExists:s(S=>e.fileExists(S),"fileExists")}).channel==="guard";t.push(y?b?{check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${_}): ${J} was declined at install, and the maind plugin keeps it off too.`}:{check:"session-start",level:"info",message:`no session-start briefing \u2014 ${J} was declined at install, and the maind plugin keeps it off too, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`}:{check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start from the maind plugin (${J}).`});let v=e.plugin?.file?` (${e.plugin.file})`:"",k=e.clientConfigs.find(S=>S.key==="claude-code-user");k!==void 0&&yf(k.raw).length>0&&t.push({check:"claude-plugin",level:"warn",message:`the maind plugin is enabled${v} and brings its own MCP server, and ${k.path} still registers a \`maind\` server \u2014 Claude Code starts both, so every maind tool is listed twice.`,fix:`${n} doctor --remove-duplicate-mcp (lists it; --yes removes exactly that entry \u2014 with Claude Code closed)`});let E=e.claudeSettings===null?[]:Oe(e.claudeSettings,{fileExists:s(S=>e.fileExists(S),"fileExists")}).filter(S=>S.status!=="missing"&&S.status!=="broken");E.length>0&&t.push({check:"claude-plugin",level:"info",message:`the maind plugin is enabled${v}, and ~/.claude/settings.json still wires the bridge's own hooks (${E.map(S=>S.subcommand).join(", ")}) \u2014 nothing runs twice (the plugin's copy stands down for them), but these run from settings.json, pinned to that install, instead of updating with the plugin.`,fix:`${n} doctor --remove-duplicate-hooks (lists them; --yes removes exactly those entries from settings.json)`})}if(e.claudeSettings!==null&&!p){let y=e.guardMode??"off",_=Mi(e.claudeSettings,{guardMode:y,fileExists:s(E=>e.fileExists(E),"fileExists")}),v=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${wn}`)} install --hooks-only`,k=(e.declinedHooks??[]).includes(J);_.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${J} hook).`}):_.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${J} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):_.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${y}); without the core ${J} hook it stops when the guard is switched off.`,fix:v}):k?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${J} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:v}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${J}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:v})}if(e.claudeSettings!==null){let y=Oe(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")},[bH])[0];if(y.status==="superseded"){let _=e.foreignHookHosts??[],b=_.includes("cursor"),v=(e.declinedHooks??[]).includes($t),k=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${wn}`),E=y.remedy==="run-install"?`${k} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${k} ${$t}`,S=b?`Cursor, installed here, imports it from ~/.claude/settings.json and takes only JSON at session start \u2014 it gets plain text it cannot parse${_.includes("devin")?"; Devin Local gets text whose handling it does not document":""}`:_.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:b&&!v?"warn":"info",message:`the SessionStart reminder hook still runs \`${y.command}\` \u2014 ${S}. ${$t} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:E})}}let f=e.repoBlocks??null,h=f?.plans.find(y=>y.keeps.some(_=>_.startsWith("team conventions block")))??null;f!==null&&yr(f.plans)&&t.push({check:"repo-blocks",level:"info",message:`${f.root} still carries the maind blocks an earlier install wrote into the repository \u2014 ${Dc(f.plans)}. The bridge no longer writes them (ADR-364): hooks and user-level rule files carry the same content. They stay until you remove them.`,fix:`${n} doctor --migrate-repo-blocks (lists them and changes nothing; --yes removes exactly the listed blocks)`}),h!==null&&t.push({check:"repo-blocks",level:"ok",message:`${h.rel} carries the team conventions block (install --team); the bridge keeps it current.`}),f!==null&&f.inRepo&&h===null&&(e.foreignHookHosts??[]).includes("cursor")&&t.push({check:"team-option",level:"info",message:`Cursor is installed here, and its sessionStart hook can drop the briefing in a race Cursor confirms. For teams that work mostly in Cursor, the team option puts the conventions into ${f.root}'s AGENTS.md, which Cursor reads reliably.`,fix:`${n} install --team (writes the AGENTS.md conventions block and the project .mcp.json)`});for(let y of e.channels??[])y.state==="ok"?t.push({check:"channels",level:"ok",message:`${y.label}: ${y.path}`}):y.state==="foreign"?t.push({check:"channels",level:"info",message:`${y.label}: ${y.path} is not the bridge's (no maind marker) \u2014 left as it is, so ${y.client} gets no conventions from MAIND there.`}):t.push({check:"channels",level:"info",message:`${y.label} is not set up \u2014 ${y.client} sessions get the project conventions only from the MCP instructions${f!==null&&yr(f.plans)?" and the repository's old maind blocks":""}.`,fix:`${n} install --hooks-only (asks consent per hook and file)`});let g=e.context??null;if(g!==null&&e.claudeSettings!==null){let y=Oe(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")}).filter(_=>(_.subcommand==="on-prompt-context"||_.subcommand==="on-read-context")&&_.status!=="missing").map(_=>_.subcommand);if(y.length>0){let _=t.length;g.sqlite.ok?g.repoRoot!==null&&!g.indexPresent&&t.push({check:"context",level:"info",message:`${g.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:`${y.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${g.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"}),y.includes("on-prompt-context")&&g.repoRoot!==null&&!g.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${g.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===_&&t.push({check:"context",level:"ok",message:`${y.join(" and ")}: code index and cached conventions present${g.repoRoot?` for ${g.repoRoot}`:""}.`})}}return t}function LS(e){let t=e.filter(o=>o.level==="error"&&vf.includes(o.check)).sort((o,i)=>vf.indexOf(o.check)-vf.indexOf(i.check)),n=t[0];if(n===void 0)return vH(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 vH(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?kH(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 kH(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?xH(e):`[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 xH(e){let t=e.find(n=>n.check==="claude-plugin"&&n.level==="warn");return t===void 0?null:`[maind] setup note \u2014 ${t.message}`+(t.fix?` To fix, run in a terminal: ${t.fix}`:"")}function FS(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}`]:[]]),o=e.filter(a=>a.level==="error").length,i=e.filter(a=>a.level==="warn").length;return r.push("",o+i===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${o} error(s), ${i} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
902
+ `}),n=r+1}return t}function yH(e){let t=bf(e),n=[],r=null;for(let o=0;o<t.length;o++){if(!t[o].text.startsWith(er))continue;let i=hH.find(a=>o+a.lines<=t.length&&MS(t.slice(o,o+a.lines).map(c=>c.text).join(`
903
+ `))===a.sha256);if(i===void 0){r=`a "${er}" section (line ${o+1}) that is not a block the installer wrote \u2014 edited by hand, or an unknown variant`;continue}n.push({kind:"preamble",from:o,to:o+i.lines-1}),o+=i.lines-1}for(let o=0;o<t.length;o++){if(t[o].text.trim()!==va)continue;let i=t.findIndex((c,l)=>l>o&&c.text.trim()===ka);if(i<0){r=`a conventions block without its end marker (line ${o+1})`;break}let a=t.slice(o+1,i).some(c=>c.text.trim().startsWith(hi));n.push({kind:a?"team-conventions":"conventions",from:o,to:i}),o=i}return n.sort((o,i)=>o.from-i.from),{blocks:n,manual:r}}function _H(e,t){let n=bf(e),r=new Array(n.length).fill(!1);for(let a of t)if(a.kind!=="team-conventions"){for(let c=a.from;c<=a.to;c++)r[c]=!0;for(let c=a.from-1;c>=0&&!r[c]&&Dc(n[c]);c--)r[c]=!0}let o=0;for(;o<n.length&&r[o];)o++;if(o>0)for(;o<n.length&&Dc(n[o]);o++)r[o]=!0;let i=n.filter((a,c)=>!r[c]);return i.every(Dc)?null:i.map(a=>a.text+a.eol).join("")}function $S(e,t,n){let r=yH(n);if(r.blocks.length===0&&r.manual===null)return null;let o=s(p=>`${bH[p.kind]} (lines ${p.from+1}\u2013${p.to+1})`,"describe"),i=r.blocks.filter(p=>p.kind!=="team-conventions"),a=r.blocks.filter(p=>p.kind==="team-conventions");if(r.manual!==null)return{rel:e,path:t,raw:n,action:"manual",next:null,removes:[],keeps:[r.manual]};if(i.length===0)return{rel:e,path:t,raw:n,action:"keep",next:null,removes:[],keeps:a.map(o)};let c=_H(n,r.blocks),l=i.map(o);if(c===null)return{rel:e,path:t,raw:n,action:"delete",next:null,removes:l,keeps:[]};let d=bf(c).filter(p=>!Dc(p)).length-a.reduce((p,f)=>p+(f.to-f.from+1),0),u=[...a.map(o),...d>0?[`${d} line${d===1?"":"s"} of yours`]:[]];return{rel:e,path:t,raw:n,action:"edit",next:c,removes:l,keeps:u}}function yr(e){return e.some(t=>t.action==="edit"||t.action==="delete"||t.action==="manual")}function Pc(e){return e.filter(t=>t.action!=="keep").map(t=>{if(t.action==="manual")return`${t.rel} (by hand)`;let n=[...new Set(t.removes.map(r=>r.replace(/ \(lines.*$/,"")))];return`${t.rel} (${n.join(" + ")})`}).join(", ")}var PS,MS,mH,hH,Dc,bH,Ki=w(()=>{"use strict";wa();Zr();PS=["CLAUDE.md","AGENTS.md",".github/copilot-instructions.md",".cursorrules",".windsurfrules"],MS=s(e=>fH("sha256").update(e).digest("hex"),"sha256"),mH={lines:70,sha256:"2c7687dc2fd58b7c96d7f31c7b530c06c3fffe8710c6404a7e421ca7c8bf7714"},hH=gH([{lines:bt.split(`
904
+ `).length,sha256:MS(bt)},mH,{lines:57,sha256:"72f5d6423e98eb01b2854b44dff290f2d8be1af1c8995f059dba5118530aafce"},{lines:56,sha256:"bf77aeeed9e96b8d0bfcba1feee0592256e2d49d64b53977bbd8f5b8323e5387"},{lines:21,sha256:"afdaf4a151cfd6fc9258392d86593e0604dae7518ffa8918cfc92bab9d5fd41b"}]);s(gH,"dedupe");s(bf,"splitLines");Dc=s(e=>e.text.trim()==="","isBlank");s(yH,"scanRepoFile");s(_H,"cutBlocks");bH={preamble:"maind preamble",conventions:"conventions block","team-conventions":"team conventions block (install --team)"};s($S,"planRepoFile");s(yr,"hasMigratableBlocks");s(Pc,"summarizeRepoBlocks")});import{parse as wH}from"jsonc-parser";function wf(e,t){let n=e.split(/[.+-]/).slice(0,3).map(o=>Number.parseInt(o,10)||0),r=t.split(/[.+-]/).slice(0,3).map(o=>Number.parseInt(o,10)||0);for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function kf(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=wH(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,o=r.servers?.maind??r.mcpServers?.maind,i=o?.transport??o;return!i||typeof i.command!="string"?null:{command:i.command,args:Array.isArray(i.args)?i.args.filter(a=>typeof a=="string"):[]}}function bo(e,t){let n=`npm i -g ${wn}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Mc(e){let t=[],n=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${wn}`),r=[e.runningVersion,...e.nodeTrees.map(y=>y.bridgeVersion).filter(y=>y!==null)],o=e.latestVersion??r.sort(wf).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(y=>y.bridgeVersion!==null);if(e.nodeTrees.length>0){let y=e.pathWinner?.node??null,_=e.nodeTrees.find(v=>v.node===y);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)."}):_&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${_.node} tree (${_.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let v=e.nodeTrees.find(k=>k.node===e.nvmDefault);v&&v.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${v.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:bo(o,v.node)})}if(new Set(i.map(v=>v.bridgeVersion)).size>1)for(let v of i.filter(k=>wf(k.bridgeVersion,o)<0))t.push({check:"node-trees",level:"warn",message:`${v.node} carries bridge ${v.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:bo(o,v.node)})}let a=!1,c=new Map,l=s((y,_)=>{let b=c.get(y)??{version:e.installVersionOf(y),clients:[]};b.clients.push(_),c.set(y,b)},"noteInstall");for(let y of e.clientConfigs){let _=kf(y);if(_===null)continue;if(y.present===!1){t.push({check:"client-config",level:"warn",message:`${y.label}: ${y.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(a=!0,/(^|\/)npx(\.cmd)?$/.test(_.command)&&_.args.some(k=>k.includes(wn))){t.push({check:"client-config",level:"warn",message:`${y.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${bo(o)}, then set "command": "maind-mcp-bridge" (no args) in ${y.path}`});continue}let v=/(^|[\\/])node(\.exe)?$/.test(_.command);if(v&&_.args.length>0){let k=_.args[0];if(!e.fileExists(k)){t.push({check:"client-config",level:"error",message:`${y.label} runs ${k}, which does not exist.`,fix:`re-run \`npx -y ${wn}@${o} install\` to rewrite the entry`});continue}l(k,y.label)}else if(_.command.includes("/")||_.command.includes("\\")){if(!e.fileExists(_.command)){t.push({check:"client-config",level:"error",message:`${y.label} points at ${_.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${y.path} (after ${bo(o)})`});continue}}else if(_.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${y.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:bo(o,e.nvmDefault)});continue}v||(_.command.includes("/")||_.command.includes("\\")?l(_.command,y.label):_.command==="maind-mcp-bridge"&&e.pathWinner&&l(e.pathWinner.path,y.label)),t.push({check:"client-config",level:"ok",message:`${y.label}: ${[_.command,..._.args].join(" ")}`})}if(!a&&e.plugin?.enabled!==!0&&t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${wn} install`}),e.latestVersion!==null)for(let[y,_]of c){let b=_.clients.join(", ");if(_.version===null)t.push({check:"version",level:"info",message:`${b}: cannot tell which bridge version ${y} is.`});else if(wf(_.version,e.latestVersion)<0){let v=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(y)?.[1]??null;t.push({check:"version",level:"warn",message:`${b} run bridge ${_.version} (${y}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:v?bo(e.latestVersion,v):`npx -y ${wn}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${b} run bridge ${_.version} (published: ${e.latestVersion}).`})}for(let{dir:y,maind:_}of e.npxStaleDirs)t.push({check:"npx-cache",level:_?"error":"info",message:_?`a half-built better-sqlite3 was left in ${y} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${y} (another tool's npx entry, not maind's).`,fix:`rm -rf '${y.replace(/'/g,"'\\''")}'`});let d=e.envApiKey??e.apiKey;(e.deviceId===null||!LS.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"}),d===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):kH.test(d)?t.push({check:"credentials",level:e.deviceId!==null&&LS.test(e.deviceId)?"ok":"info",message:`key ${d.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 u=e.connection;if(u===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):u.outcome==="ok"||u.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${u.outcome==="ok"?"succeeded":"was paired"} at ${u.at} (bridge ${u.bridge_version}).`}):t.push({check:"connection",level:"error",message:u.outcome==="auth_failed"?`the server rejected the last connection (${u.at}${u.detail?`: ${u.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${u.at}${u.detail?`: ${u.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 y=Oe(e.claudeSettings,{fileExists:s(b=>e.fileExists(b),"fileExists")}),_=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let b of y){if(b.status==="missing"||b.status==="superseded")continue;if(b.status!=="ok"){t.push({check:"hooks",level:b.status==="broken"?"error":"warn",message:b.detail});continue}let v=b.command?/(\S+\/build\/index\.js)/.exec(b.command)?.[1]??null:null,k=v?e.installVersionOf(v):null;k!==null&&_!==null&&k!==_&&t.push({check:"hooks",level:"warn",message:`${b.event}/${b.subcommand} runs bridge ${k}, the MCP server runs ${_} \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"} ${b.subcommand}`})}t.some(b=>b.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}let p=e.plugin?.enabled===!0;if(p){let y=(e.declinedHooks??[]).includes(J),_=e.guardMode??"off",b=y&&e.claudeSettings!==null&&Mi(e.claudeSettings,{guardMode:_,fileExists:s(S=>e.fileExists(S),"fileExists")}).channel==="guard";t.push(y?b?{check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${_}): ${J} was declined at install, and the maind plugin keeps it off too.`}:{check:"session-start",level:"info",message:`no session-start briefing \u2014 ${J} was declined at install, and the maind plugin keeps it off too, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`}:{check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start from the maind plugin (${J}).`});let v=e.plugin?.file?` (${e.plugin.file})`:"",k=e.clientConfigs.find(S=>S.key==="claude-code-user");k!==void 0&&yf(k.raw).length>0&&t.push({check:"claude-plugin",level:"warn",message:`the maind plugin is enabled${v} and brings its own MCP server, and ${k.path} still registers a \`maind\` server \u2014 Claude Code starts both, so every maind tool is listed twice.`,fix:`${n} doctor --remove-duplicate-mcp (lists it; --yes removes exactly that entry \u2014 with Claude Code closed)`});let E=e.claudeSettings===null?[]:Oe(e.claudeSettings,{fileExists:s(S=>e.fileExists(S),"fileExists")}).filter(S=>S.status!=="missing"&&S.status!=="broken");E.length>0&&t.push({check:"claude-plugin",level:"info",message:`the maind plugin is enabled${v}, and ~/.claude/settings.json still wires the bridge's own hooks (${E.map(S=>S.subcommand).join(", ")}) \u2014 nothing runs twice (the plugin's copy stands down for them), but these run from settings.json, pinned to that install, instead of updating with the plugin.`,fix:`${n} doctor --remove-duplicate-hooks (lists them; --yes removes exactly those entries from settings.json)`})}if(e.claudeSettings!==null&&!p){let y=e.guardMode??"off",_=Mi(e.claudeSettings,{guardMode:y,fileExists:s(E=>e.fileExists(E),"fileExists")}),v=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${wn}`)} install --hooks-only`,k=(e.declinedHooks??[]).includes(J);_.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${J} hook).`}):_.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${J} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):_.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${y}); without the core ${J} hook it stops when the guard is switched off.`,fix:v}):k?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${J} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:v}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${J}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:v})}if(e.claudeSettings!==null){let y=Oe(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")},[vH])[0];if(y.status==="superseded"){let _=e.foreignHookHosts??[],b=_.includes("cursor"),v=(e.declinedHooks??[]).includes(Lt),k=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${wn}`),E=y.remedy==="run-install"?`${k} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${k} ${Lt}`,S=b?`Cursor, installed here, imports it from ~/.claude/settings.json and takes only JSON at session start \u2014 it gets plain text it cannot parse${_.includes("devin")?"; Devin Local gets text whose handling it does not document":""}`:_.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:b&&!v?"warn":"info",message:`the SessionStart reminder hook still runs \`${y.command}\` \u2014 ${S}. ${Lt} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:E})}}let f=e.repoBlocks??null,h=f?.plans.find(y=>y.keeps.some(_=>_.startsWith("team conventions block")))??null;f!==null&&yr(f.plans)&&t.push({check:"repo-blocks",level:"info",message:`${f.root} still carries the maind blocks an earlier install wrote into the repository \u2014 ${Pc(f.plans)}. The bridge no longer writes them (ADR-364): hooks and user-level rule files carry the same content. They stay until you remove them.`,fix:`${n} doctor --migrate-repo-blocks (lists them and changes nothing; --yes removes exactly the listed blocks)`}),h!==null&&t.push({check:"repo-blocks",level:"ok",message:`${h.rel} carries the team conventions block (install --team); the bridge keeps it current.`}),f!==null&&f.inRepo&&h===null&&(e.foreignHookHosts??[]).includes("cursor")&&t.push({check:"team-option",level:"info",message:`Cursor is installed here, and its sessionStart hook can drop the briefing in a race Cursor confirms. For teams that work mostly in Cursor, the team option puts the conventions into ${f.root}'s AGENTS.md, which Cursor reads reliably.`,fix:`${n} install --team (writes the AGENTS.md conventions block and the project .mcp.json)`});for(let y of e.channels??[])y.state==="ok"?t.push({check:"channels",level:"ok",message:`${y.label}: ${y.path}`}):y.state==="foreign"?t.push({check:"channels",level:"info",message:`${y.label}: ${y.path} is not the bridge's (no maind marker) \u2014 left as it is, so ${y.client} gets no conventions from MAIND there.`}):t.push({check:"channels",level:"info",message:`${y.label} is not set up \u2014 ${y.client} sessions get the project conventions only from the MCP instructions${f!==null&&yr(f.plans)?" and the repository's old maind blocks":""}.`,fix:`${n} install --hooks-only (asks consent per hook and file)`});let g=e.context??null;if(g!==null&&e.claudeSettings!==null){let y=Oe(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")}).filter(_=>(_.subcommand==="on-prompt-context"||_.subcommand==="on-read-context")&&_.status!=="missing").map(_=>_.subcommand);if(y.length>0){let _=t.length;g.sqlite.ok?g.repoRoot!==null&&!g.indexPresent&&t.push({check:"context",level:"info",message:`${g.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:`${y.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${g.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"}),y.includes("on-prompt-context")&&g.repoRoot!==null&&!g.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${g.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===_&&t.push({check:"context",level:"ok",message:`${y.join(" and ")}: code index and cached conventions present${g.repoRoot?` for ${g.repoRoot}`:""}.`})}}return t}function FS(e){let t=e.filter(o=>o.level==="error"&&vf.includes(o.check)).sort((o,i)=>vf.indexOf(o.check)-vf.indexOf(i.check)),n=t[0];if(n===void 0)return xH(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 xH(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?SH(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 SH(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?EH(e):`[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 EH(e){let t=e.find(n=>n.check==="claude-plugin"&&n.level==="warn");return t===void 0?null:`[maind] setup note \u2014 ${t.message}`+(t.fix?` To fix, run in a terminal: ${t.fix}`:"")}function jS(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}`]:[]]),o=e.filter(a=>a.level==="error").length,i=e.filter(a=>a.level==="warn").length;return r.push("",o+i===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${o} error(s), ${i} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
902
905
  `)+`
903
- `}var wn,bH,wH,$S,vf,Mc=w(()=>{"use strict";dc();_f();Ki();ve();wn="@maind-dev/mcp-bridge",bH=je.find(e=>e.subcommand===$t),wH=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,$S=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(wf,"compareVersions");s(kf,"maindEntry");s(bo,"installFix");s(Pc,"diagnose");vf=["connection","client-config","npx-cache","hooks"];s(LS,"sessionStartLine");s(vH,"briefingGapLine");s(kH,"hookHostsGapLine");s(xH,"pluginDuplicateLine");s(FS,"renderFindings")});import{parse as US}from"smol-toml";function BS(e){let t;try{t=US(e)}catch{return null}if(!Ht(t)||!Ht(t.mcp_servers)||!Ht(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"),o=[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[]],i=CH(e);if(i===null)return{action:"manual",next:null,stays:o};let a=SH(i),l=i.some(u=>u.comment&&!a.some(([p,f])=>u.start>=p&&u.end<=f))?[...o,"comments"]:o;if(l.length===0)return{action:"delete",next:null,stays:l};if(a.length===0)return{action:"manual",next:null,stays:l};let d=EH(e,a);return RH(t,d)?{action:"edit",next:d,stays:l}:{action:"manual",next:null,stays:l}}function SH(e){let t=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.kind!=="header"||o.path?.[0]!=="mcp_servers"||o.path[1]!=="maind")continue;let i=r;for(let c=r+1;c<e.length&&e[c].kind!=="header";c++)(e[c].kind==="keyval"||e[c].kind==="continuation")&&(i=c);let a=r;for(;a>0&&e[a-1].kind==="blank";)a--;t.push([e[a].start,e[i].end])}let n=[];for(let[r,o]of t){let i=n.at(-1);i!==void 0&&r<=i[1]?i[1]=Math.max(i[1],o):n.push([r,o])}return n}function EH(e,t){let n=e;for(let[r,o]of[...t].reverse())n=n.slice(0,r)+n.slice(o);return t[0]?.[0]===0&&(n=n.replace(/^(?:[ \t]*\r?\n)+/,"")),n}function RH(e,t){let n;try{n=US(t)}catch{return!1}if(!Ht(n))return!1;let r={...e.mcp_servers};delete r.maind;let o={...e,mcp_servers:r};return xf(jS(o),jS(n))}function jS(e){if(!Ht(e.mcp_servers)||Object.keys(e.mcp_servers).length>0)return e;let t={...e};return delete t.mcp_servers,t}function xf(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)=>xf(n,t[r]));if(Ht(e)||Ht(t)){if(!Ht(e)||!Ht(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>r in t&&xf(e[r],t[r]))}return Object.is(e,t)}function Ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function CH(e){let t=[],n=null,r=0;for(let o=0;o<e.length;){let i=e.indexOf(`
904
- `,o),a=i===-1?e.length:i+1,c=e.slice(o,i===-1?e.length:i).replace(/\r$/,"");if(n!==null||r>0){let l=HS(c,0,n,r);if(l===null)return null;({open:n,depth:r}=l),t.push({start:o,end:a,kind:"continuation",comment:l.comment})}else{let l=c.search(/[^ \t]/);if(l===-1)t.push({start:o,end:a,kind:"blank",comment:!1});else if(c[l]==="#")t.push({start:o,end:a,kind:"comment",comment:!0});else if(c[l]==="["){let d=TH(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:o,end:a,kind:"header",comment:u.length>0,path:d.path})}else{let d=HS(c,l,null,0);if(d===null)return null;({open:n,depth:r}=d),t.push({start:o,end:a,kind:"keyval",comment:d.comment})}}o=a}return n===null&&r===0?t:null}function HS(e,t,n,r){let o=t;for(;o<e.length;){if(n!==null){let a=Sf(e,o,n);if(a===-1)return{open:n,depth:r,comment:!1};n=null,o=a;continue}let i=e[o];if(i==="#")return{open:n,depth:r,comment:!0};if(i==='"'||i==="'"){if(e.startsWith(i.repeat(3),o)){n=i==='"'?'"""':"'''",o+=3;continue}let a=Sf(e,o+1,i);if(a===-1)return null;o=a;continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r<0))return null;o++}return{open:n,depth:r,comment:!1}}function Sf(e,t,n){if(n==="'"||n==="'''"){let r=e.indexOf(n,t);if(r===-1)return-1;let o=r+n.length;if(n==="'''")for(;o<r+5&&e[o]==="'";)o++;return o}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 o=r+3;for(;o<r+5&&e[o]==='"';)o++;return o}r++}return-1}function TH(e,t){let n=e[t+1]==="[",r=n?"]]":"]",o=t+(n?2:1),i=[];for(;;){for(;e[o]===" "||e[o]===" ";)o++;let a=AH(e,o);if(a===null)return null;for(i.push(a.value),o=a.end;e[o]===" "||e[o]===" ";)o++;if(e[o]==="."){o++;continue}return e.startsWith(r,o)?{path:i,end:o+r.length}:null}}function AH(e,t){if(e[t]==='"'){let r=Sf(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 KS=w(()=>{"use strict";s(BS,"planTomlPhantomRemoval");s(SH,"maindTableRanges");s(EH,"applyCut");s(RH,"sameWithoutMaind");s(jS,"dropEmptyServers");s(xf,"sameValue");s(Ht,"isTable");s(CH,"scanLines");s(HS,"scanValue");s(Sf,"closeOf");s(TH,"parseHeader");s(AH,"readKey")});import{findNodeAtLocation as IH,parse as GS,parseTree as NH,stripComments as OH}from"jsonc-parser";function WS(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||kf(n)===null)continue;if(n.kind==="toml"){let f=DH(n,n.raw);f!==null&&t.push(f);continue}let r=[],o=GS(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!Ef(o))continue;let i=Ef(o.servers)&&"maind"in o.servers?"servers":"mcpServers",a=o[i];if(!Ef(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(o).filter(f=>f!==i),d=OH(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=PH(n.raw,[i,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${i}.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 ${i}.maind; stays: ${u}`})}return t}function DH(e,t){let n=BS(t);if(n===null)return null;let r={label:e.label,path:e.path,raw:t},o=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]${o}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove [mcp_servers.maind] by hand \u2014 it cannot be cut out cleanly${o}`}}}function PH(e,t){let n=NH(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:IH(n,[...t])?.parent,o=r?.parent?.children;if(r===void 0||r.type!=="property"||o===void 0)return null;let i=o.indexOf(r),a=r.offset,c=r.offset+r.length;if(i+1<o.length)c=o[i+1].offset;else if(i>0){let u=o[i-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 GS(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function VS(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
906
+ `}var wn,vH,kH,LS,vf,$c=w(()=>{"use strict";uc();_f();Ki();ve();wn="@maind-dev/mcp-bridge",vH=je.find(e=>e.subcommand===Lt),kH=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,LS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(wf,"compareVersions");s(kf,"maindEntry");s(bo,"installFix");s(Mc,"diagnose");vf=["connection","client-config","npx-cache","hooks"];s(FS,"sessionStartLine");s(xH,"briefingGapLine");s(SH,"hookHostsGapLine");s(EH,"pluginDuplicateLine");s(jS,"renderFindings")});import{parse as BS}from"smol-toml";function KS(e){let t;try{t=BS(e)}catch{return null}if(!Ut(t)||!Ut(t.mcp_servers)||!Ut(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"),o=[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[]],i=AH(e);if(i===null)return{action:"manual",next:null,stays:o};let a=RH(i),l=i.some(u=>u.comment&&!a.some(([p,f])=>u.start>=p&&u.end<=f))?[...o,"comments"]:o;if(l.length===0)return{action:"delete",next:null,stays:l};if(a.length===0)return{action:"manual",next:null,stays:l};let d=CH(e,a);return TH(t,d)?{action:"edit",next:d,stays:l}:{action:"manual",next:null,stays:l}}function RH(e){let t=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.kind!=="header"||o.path?.[0]!=="mcp_servers"||o.path[1]!=="maind")continue;let i=r;for(let c=r+1;c<e.length&&e[c].kind!=="header";c++)(e[c].kind==="keyval"||e[c].kind==="continuation")&&(i=c);let a=r;for(;a>0&&e[a-1].kind==="blank";)a--;t.push([e[a].start,e[i].end])}let n=[];for(let[r,o]of t){let i=n.at(-1);i!==void 0&&r<=i[1]?i[1]=Math.max(i[1],o):n.push([r,o])}return n}function CH(e,t){let n=e;for(let[r,o]of[...t].reverse())n=n.slice(0,r)+n.slice(o);return t[0]?.[0]===0&&(n=n.replace(/^(?:[ \t]*\r?\n)+/,"")),n}function TH(e,t){let n;try{n=BS(t)}catch{return!1}if(!Ut(n))return!1;let r={...e.mcp_servers};delete r.maind;let o={...e,mcp_servers:r};return xf(HS(o),HS(n))}function HS(e){if(!Ut(e.mcp_servers)||Object.keys(e.mcp_servers).length>0)return e;let t={...e};return delete t.mcp_servers,t}function xf(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)=>xf(n,t[r]));if(Ut(e)||Ut(t)){if(!Ut(e)||!Ut(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>r in t&&xf(e[r],t[r]))}return Object.is(e,t)}function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function AH(e){let t=[],n=null,r=0;for(let o=0;o<e.length;){let i=e.indexOf(`
907
+ `,o),a=i===-1?e.length:i+1,c=e.slice(o,i===-1?e.length:i).replace(/\r$/,"");if(n!==null||r>0){let l=US(c,0,n,r);if(l===null)return null;({open:n,depth:r}=l),t.push({start:o,end:a,kind:"continuation",comment:l.comment})}else{let l=c.search(/[^ \t]/);if(l===-1)t.push({start:o,end:a,kind:"blank",comment:!1});else if(c[l]==="#")t.push({start:o,end:a,kind:"comment",comment:!0});else if(c[l]==="["){let d=IH(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:o,end:a,kind:"header",comment:u.length>0,path:d.path})}else{let d=US(c,l,null,0);if(d===null)return null;({open:n,depth:r}=d),t.push({start:o,end:a,kind:"keyval",comment:d.comment})}}o=a}return n===null&&r===0?t:null}function US(e,t,n,r){let o=t;for(;o<e.length;){if(n!==null){let a=Sf(e,o,n);if(a===-1)return{open:n,depth:r,comment:!1};n=null,o=a;continue}let i=e[o];if(i==="#")return{open:n,depth:r,comment:!0};if(i==='"'||i==="'"){if(e.startsWith(i.repeat(3),o)){n=i==='"'?'"""':"'''",o+=3;continue}let a=Sf(e,o+1,i);if(a===-1)return null;o=a;continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r<0))return null;o++}return{open:n,depth:r,comment:!1}}function Sf(e,t,n){if(n==="'"||n==="'''"){let r=e.indexOf(n,t);if(r===-1)return-1;let o=r+n.length;if(n==="'''")for(;o<r+5&&e[o]==="'";)o++;return o}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 o=r+3;for(;o<r+5&&e[o]==='"';)o++;return o}r++}return-1}function IH(e,t){let n=e[t+1]==="[",r=n?"]]":"]",o=t+(n?2:1),i=[];for(;;){for(;e[o]===" "||e[o]===" ";)o++;let a=NH(e,o);if(a===null)return null;for(i.push(a.value),o=a.end;e[o]===" "||e[o]===" ";)o++;if(e[o]==="."){o++;continue}return e.startsWith(r,o)?{path:i,end:o+r.length}:null}}function NH(e,t){if(e[t]==='"'){let r=Sf(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 GS=w(()=>{"use strict";s(KS,"planTomlPhantomRemoval");s(RH,"maindTableRanges");s(CH,"applyCut");s(TH,"sameWithoutMaind");s(HS,"dropEmptyServers");s(xf,"sameValue");s(Ut,"isTable");s(AH,"scanLines");s(US,"scanValue");s(Sf,"closeOf");s(IH,"parseHeader");s(NH,"readKey")});import{findNodeAtLocation as OH,parse as WS,parseTree as DH,stripComments as PH}from"jsonc-parser";function VS(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||kf(n)===null)continue;if(n.kind==="toml"){let f=MH(n,n.raw);f!==null&&t.push(f);continue}let r=[],o=WS(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!Ef(o))continue;let i=Ef(o.servers)&&"maind"in o.servers?"servers":"mcpServers",a=o[i];if(!Ef(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(o).filter(f=>f!==i),d=PH(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=$H(n.raw,[i,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${i}.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 ${i}.maind; stays: ${u}`})}return t}function MH(e,t){let n=KS(t);if(n===null)return null;let r={label:e.label,path:e.path,raw:t},o=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]${o}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove [mcp_servers.maind] by hand \u2014 it cannot be cut out cleanly${o}`}}}function $H(e,t){let n=DH(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:OH(n,[...t])?.parent,o=r?.parent?.children;if(r===void 0||r.type!=="property"||o===void 0)return null;let i=o.indexOf(r),a=r.offset,c=r.offset+r.length;if(i+1<o.length)c=o[i+1].offset;else if(i>0){let u=o[i-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 WS(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function qS(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
905
908
  `;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(`
906
909
  `)+`
907
- `}function Ef(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qS=w(()=>{"use strict";Mc();KS();s(WS,"planPhantomRemovals");s(DH,"tomlRemoval");s(PH,"withoutProperty");s(VS,"renderPhantomPlan");s(Ef,"isObject")});import{execFileSync as MH}from"node:child_process";import{existsSync as $H,readFileSync as LH,realpathSync as FH}from"node:fs";import{dirname as jH,join as HH,relative as zS,resolve as UH}from"node:path";function Rf(e){try{return $H(e)?LH(e,"utf8"):null}catch{return null}}function BH(e){try{let t=MH("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 JS(e){try{return FH(e)}catch{return UH(e)}}function wo(e,t={}){let n=JS(e),r=(t.toplevel??BH)(n),o=r===null?null:JS(r),i=t.read??Rf,a=o??n,c=[];if(o===null)c.push(n);else{let d=n;for(let u=0;u<64;u++){c.push(d);let p=zS(o,d);if(p===""||p.startsWith(".."))break;let f=jH(d);if(f===d)break;d=f}c.includes(o)||c.push(o)}let l=[];for(let d of c)for(let u of DS){let p=HH(d,u),f=i(p);if(f===null)continue;let h=MS(zS(a,p).split("\\").join("/")||u,p,f);h!==null&&l.push(h)}return{root:a,inRepo:o!==null,plans:l}}var $c=w(()=>{"use strict";Ki();s(Rf,"readOrNull");s(BH,"gitToplevelSync");s(JS,"realOrResolve");s(wo,"scanRepoBlocks")});function Lc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function KH(e){for(let t of je)if(new RegExp(`(^|[\\s/"'])${t.subcommand}(\\s|$|["'])`).test(e)||t.supersedes!==void 0&&t.supersedes.replaceable.test(e))return t.subcommand;return null}function YS(e,t){if(e===null||e.trim().length===0)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!Lc(n)||!Lc(n.hooks))return null;let r=[],o={};for(let[a,c]of Object.entries(n.hooks)){if(!Array.isArray(c)){o[a]=c;continue}let l=[];for(let d of c){if(!Lc(d)||!Array.isArray(d.hooks)){l.push(d);continue}let u=d.hooks.filter(p=>{if(!Lc(p)||typeof p.command!="string")return!0;let f=KH(p.command);return f===null?!0:(r.push({event:a,subcommand:f,command:p.command}),!1)});u.length===d.hooks.length?l.push(d):u.length>0&&l.push({...d,hooks:u})}(l.length>0||c.length===0)&&(o[a]=l)}if(r.length===0)return null;let i={...n};return Object.keys(o).length>0?i.hooks=o:delete i.hooks,{file:t,raw:e,next:JSON.stringify(i,null,2)+`
908
- `,removed:r}}function XS(e,t,n){return n?e===null?`No bridge hooks in settings.json next to the maind plugin \u2014 the plugin runs them.
910
+ `}function Ef(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zS=w(()=>{"use strict";$c();GS();s(VS,"planPhantomRemovals");s(MH,"tomlRemoval");s($H,"withoutProperty");s(qS,"renderPhantomPlan");s(Ef,"isObject")});import{execFileSync as LH}from"node:child_process";import{existsSync as FH,readFileSync as jH,realpathSync as HH}from"node:fs";import{dirname as UH,join as BH,relative as JS,resolve as KH}from"node:path";function Rf(e){try{return FH(e)?jH(e,"utf8"):null}catch{return null}}function GH(e){try{let t=LH("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 YS(e){try{return HH(e)}catch{return KH(e)}}function wo(e,t={}){let n=YS(e),r=(t.toplevel??GH)(n),o=r===null?null:YS(r),i=t.read??Rf,a=o??n,c=[];if(o===null)c.push(n);else{let d=n;for(let u=0;u<64;u++){c.push(d);let p=JS(o,d);if(p===""||p.startsWith(".."))break;let f=UH(d);if(f===d)break;d=f}c.includes(o)||c.push(o)}let l=[];for(let d of c)for(let u of PS){let p=BH(d,u),f=i(p);if(f===null)continue;let h=$S(JS(a,p).split("\\").join("/")||u,p,f);h!==null&&l.push(h)}return{root:a,inRepo:o!==null,plans:l}}var Lc=w(()=>{"use strict";Ki();s(Rf,"readOrNull");s(GH,"gitToplevelSync");s(YS,"realOrResolve");s(wo,"scanRepoBlocks")});function Fc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function WH(e){for(let t of je)if(new RegExp(`(^|[\\s/"'])${t.subcommand}(\\s|$|["'])`).test(e)||t.supersedes!==void 0&&t.supersedes.replaceable.test(e))return t.subcommand;return null}function XS(e,t){if(e===null||e.trim().length===0)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!Fc(n)||!Fc(n.hooks))return null;let r=[],o={};for(let[a,c]of Object.entries(n.hooks)){if(!Array.isArray(c)){o[a]=c;continue}let l=[];for(let d of c){if(!Fc(d)||!Array.isArray(d.hooks)){l.push(d);continue}let u=d.hooks.filter(p=>{if(!Fc(p)||typeof p.command!="string")return!0;let f=WH(p.command);return f===null?!0:(r.push({event:a,subcommand:f,command:p.command}),!1)});u.length===d.hooks.length?l.push(d):u.length>0&&l.push({...d,hooks:u})}(l.length>0||c.length===0)&&(o[a]=l)}if(r.length===0)return null;let i={...n};return Object.keys(o).length>0?i.hooks=o:delete i.hooks,{file:t,raw:e,next:JSON.stringify(i,null,2)+`
911
+ `,removed:r}}function ZS(e,t,n){return n?e===null?`No bridge hooks in settings.json next to the maind plugin \u2014 the plugin runs them.
909
912
  `:[`The maind plugin is enabled, and ${e.file} still wires the bridge's own hooks \u2014 the plugin's copies stand down for them, so these run instead:`,"",...e.removed.map(o=>` remove ${o.event.padEnd(18)} ${o.subcommand}`),"",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-duplicate-hooks --yes"].join(`
910
913
  `)+`
911
914
  `:`The maind plugin is not enabled \u2014 the hooks in settings.json are the ones Claude Code runs; nothing to remove.
912
- `}var ZS=w(()=>{"use strict";ve();s(Lc,"isObject");s(KH,"ourSubcommand");s(YS,"planDuplicateHookRemoval");s(XS,"renderDuplicateHooksPlan")});var tE={};Z(tE,{renderMigrationPlan:()=>eE,runMigrateRepoBlocks:()=>zH});import{unlinkSync as GH}from"node:fs";import{homedir as WH,platform as QS}from"node:os";function eE(e,t,n){let r=[],o=e.plans.filter(i=>i.action!=="keep");r.push(`maind blocks an earlier install wrote into ${e.root} (ADR-364):`,"");for(let i of o)r.push(` ${i.action.padEnd(6)} ${i.rel}`),i.action==="manual"?r.push(` ${i.keeps.join("; ")} \u2014 remove it by hand`):i.action==="delete"?r.push(` holds nothing but ${i.removes.join(" and ")} \u2014 the file goes`):r.push(` remove ${i.removes.join(" and ")}${i.keeps.length>0?`; stays: ${i.keeps.join(", ")}`:""}`);for(let i of e.plans.filter(a=>a.action==="keep"))r.push(` keep ${i.rel}`,` ${i.keeps.join(", ")} \u2014 the team option stays`);r.push("","Set up first, so nothing is lost (user level, for the clients installed here):","");for(let i of t)r.push(` ${qH(i).padEnd(6)} ${i.target}${i.detail?` \u2014 ${i.detail}`:""}`);return r.push(""),r.push(n?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --migrate-repo-blocks --yes"),r.join(`
915
+ `}var QS=w(()=>{"use strict";ve();s(Fc,"isObject");s(WH,"ourSubcommand");s(XS,"planDuplicateHookRemoval");s(ZS,"renderDuplicateHooksPlan")});var nE={};Z(nE,{renderMigrationPlan:()=>tE,runMigrateRepoBlocks:()=>YH});import{unlinkSync as VH}from"node:fs";import{homedir as qH,platform as eE}from"node:os";function tE(e,t,n){let r=[],o=e.plans.filter(i=>i.action!=="keep");r.push(`maind blocks an earlier install wrote into ${e.root} (ADR-364):`,"");for(let i of o)r.push(` ${i.action.padEnd(6)} ${i.rel}`),i.action==="manual"?r.push(` ${i.keeps.join("; ")} \u2014 remove it by hand`):i.action==="delete"?r.push(` holds nothing but ${i.removes.join(" and ")} \u2014 the file goes`):r.push(` remove ${i.removes.join(" and ")}${i.keeps.length>0?`; stays: ${i.keeps.join(", ")}`:""}`);for(let i of e.plans.filter(a=>a.action==="keep"))r.push(` keep ${i.rel}`,` ${i.keeps.join(", ")} \u2014 the team option stays`);r.push("","Set up first, so nothing is lost (user level, for the clients installed here):","");for(let i of t)r.push(` ${JH(i).padEnd(6)} ${i.target}${i.detail?` \u2014 ${i.detail}`:""}`);return r.push(""),r.push(n?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --migrate-repo-blocks --yes"),r.join(`
913
916
  `)+`
914
- `}function qH(e){switch(e.status){case"would-create":case"created":return"add";case"would-merge":case"merged":return"update";case"failed":return"failed";default:return e.detail!==void 0&&/already|up to date/.test(e.detail)?"ok":"skip"}}async function zH(e,t={}){let n=t.out??process.stdout,r=t.cwd??process.cwd(),o=(t.scan??wo)(r);if(o===null||o.plans.length===0)return n.write(`No maind blocks in ${o?.root??r} \u2014 nothing to migrate.
917
+ `}function JH(e){switch(e.status){case"would-create":case"created":return"add";case"would-merge":case"merged":return"update";case"failed":return"failed";default:return e.detail!==void 0&&/already|up to date/.test(e.detail)?"ok":"skip"}}async function YH(e,t={}){let n=t.out??process.stdout,r=t.cwd??process.cwd(),o=(t.scan??wo)(r);if(o===null||o.plans.length===0)return n.write(`No maind blocks in ${o?.root??r} \u2014 nothing to migrate.
915
918
  `),0;if(!yr(o.plans))return n.write(`Only the team conventions block (install --team) in ${o.root} \u2014 it stays; nothing to migrate.
916
- `),0;let i=t.setUpChannels??(d=>JH(d,t.homeDir??WH(),r,n));if(n.write(eE(o,await i(!0),e)),!e)return 0;let a=await i(!1),c=a.filter(d=>d.status==="failed");for(let d of a.filter(u=>u.status==="created"||u.status==="merged"))n.write(` set up ${d.target}
919
+ `),0;let i=t.setUpChannels??(d=>XH(d,t.homeDir??qH(),r,n));if(n.write(tE(o,await i(!0),e)),!e)return 0;let a=await i(!1),c=a.filter(d=>d.status==="failed");for(let d of a.filter(u=>u.status==="created"||u.status==="merged"))n.write(` set up ${d.target}
917
920
  `);if(c.length>0){for(let d of c)n.write(` failed ${d.target}: ${d.detail??"unknown error"}
918
921
  `);return n.write(`Nothing was removed \u2014 a channel could not be set up, and removing the blocks first would lose them.
919
922
  `),1}let l=0;for(let d of o.plans)if(d.action!=="keep"){if(d.action==="manual"){n.write(` left ${d.rel} \u2014 remove the maind section by hand
920
923
  `);continue}if(Rf(d.path)!==d.raw){n.write(` skipped ${d.rel} \u2014 changed since it was read
921
- `),l++;continue}try{d.action==="delete"?GH(d.path):await U(d.path,d.next??d.raw),n.write(` ${d.action==="delete"?"deleted":"edited "} ${d.rel}
924
+ `),l++;continue}try{d.action==="delete"?VH(d.path):await U(d.path,d.next??d.raw),n.write(` ${d.action==="delete"?"deleted":"edited "} ${d.rel}
922
925
  `)}catch(u){n.write(` failed ${d.rel}: ${u instanceof Error?u.message:String(u)}
923
926
  `),l++}}return n.write(`Commit the changed files when you are ready; your user-level channels carry the same content from now on.
924
- `),l>0?1:0}async function JH(e,t,n,r){let o={homeDir:t,isInteractive:!1,full:!0,skip:!1,dryRun:e,out:r},i=[],a=De(Pe(t,process.env,QS()));if(a.enabled)i.push({target:Zp,action:"skip",status:"skipped",detail:Ba(a)});else for(let c of VH)i.push(await _i(o,c));return i.push(...await Qp(o,{ctx:Mt({projectRoot:n,homeDir:t,platform:QS(),env:process.env,bridgeEntry:oe()}),probe:ce,noRules:!1,cwd:n})),i}var VH,nE=w(()=>{"use strict";ie();_t();Je();Ca();ve();ef();oo();Ki();$c();VH=je.filter(e=>e.subcommand===$t||e.subcommand===J);s(eE,"renderMigrationPlan");s(qH,"channelVerb");s(zH,"runMigrateRepoBlocks");s(JH,"defaultChannelSetup")});var cE={};Z(cE,{channelProbe:()=>aE,contextProbe:()=>sE,realProbe:()=>Wi,resolveNvmAlias:()=>iE,runDoctor:()=>mU});import{execFileSync as YH}from"node:child_process";import{existsSync as Gi,readFileSync as XH,readdirSync as Cf,realpathSync as ZH,statSync as QH,unlinkSync as eU}from"node:fs";import{homedir as kt,platform as _r}from"node:os";import{delimiter as tU,dirname as rE,join as se}from"node:path";import{parse as nU}from"smol-toml";function Se(e){try{return Gi(e)?XH(e,"utf8"):null}catch{return null}}function rU(){try{let e=YH(_r()==="win32"?"npm.cmd":"npm",["view",oE,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function Tf(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:se(kt(),".nvm")}function oU(){let e=se(Tf(),"versions","node"),t=[];try{t=Cf(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Se(se(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),o=null;try{o=r?JSON.parse(r).version??null:null}catch{o=null}return{node:n,bridgeVersion:o}})}function iE(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 o=[...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 o.at(-1)??null;let i=r.startsWith("v")?r:`v${r}`;if(t.includes(i))return i;let a=i.endsWith(".")?i:`${i}.`;return o.filter(c=>c.startsWith(a)).at(-1)??null}function iU(e){let t=Se(se(Tf(),"alias","default"));return t===null?null:iE(t,e.map(n=>n.node),n=>{let r=Se(se(Tf(),"alias",n));return r===null?null:r})}function sU(){let e=_r()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(tU))if(t)for(let n of e){let r=se(t,n);if(Gi(r)){let o=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:o?o[1]:null,path:r}}}return null}function aU(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:_r()==="win32"?se(process.env.LOCALAPPDATA??se(kt(),"AppData","Local"),"npm-cache"):se(kt(),".npm"),t=se(e,"_npx"),n=[],r=[];try{r=Cf(t)}catch{return[]}for(let o of r)try{let i=Cf(se(t,o,"node_modules"));i.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:se(t,o),maind:i.includes("@maind-dev")})}catch{}return n}function cU(e){let t;try{t=rE(ZH(e))}catch{return null}for(let n=0;n<6;n++){let r=Se(se(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===oE)return i.version??null}catch{}let o=rE(t);if(o===t)break;t=o}return null}function sE(e){let t=ln(e),n=!1;try{let o=Se(mo);n=o!==null&&typeof JSON.parse(o).conventions=="string"}catch{n=!1}let r=sc();return{repoRoot:t,indexPresent:t!==null&&Gi(se(t,cn)),conventionsCached:n||t!==null&&Gi(se(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function Wi(e=process.cwd(),t={}){let n=oU(),r=Se(se(it(),"device-id")),o=Mt({projectRoot:e,homeDir:kt(),platform:_r(),env:process.env,bridgeEntry:oe()}),i=null;try{i=z()}catch{i=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=Q(),l=we({entryPath:oe(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:H,latestVersion:t.offline===!0?null:rU(),nodeTrees:n,nvmDefault:iU(n),pathWinner:sU(),clientConfigs:fi(o).map(d=>({key:d.key,label:d.label,path:d.path,kind:d.kind,raw:Se(d.path),present:d.presence===void 0?null:Ne(d.presence,ce)})),npxStaleDirs:aU(),connection:Zb(),claudeSettings:Se(se(kt(),".claude","settings.json")),fileExists:s(d=>Gi(d),"fileExists"),installVersionOf:cU,deviceId:r===null?null:r.trim(),apiKey:i,envApiKey:a.length>0?a:null,guardMode:he(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?ze(l):null,context:t.offline===!0?null:sE(e),foreignHookHosts:dU(o),repoBlocks:t.offline===!0?null:lU(e),channels:t.offline===!0?[]:aE(o),plugin:De(Pe(kt(),process.env,_r()))}}function lU(e){try{return wo(e)}catch{return null}}function aE(e){let t=[];try{if(Ne(Yr(e),ce)){let n=pi(e),r=null;try{let o=Se(n);r=o===null?null:Ei(nU(o),J)}catch{r=null}if(r===null)try{let o=Se(se(Jr(e),"hooks.json"));r=o===null?null:Ei(JSON.parse(o),J)}catch{r=null}t.push({client:"codex",label:"Codex SessionStart hook",path:n,state:r===null?"missing":"ok"})}for(let n of ir(e,ce)){if(!Ne(n.presence,ce))continue;let r=Se(n.path);t.push({client:n.id,label:n.label,path:n.path,state:r===null?"missing":so(r)?"ok":"foreign"})}}catch{}return t}function dU(e){let t=[];try{Ne(Pt(e),ce)&&t.push("cursor"),Ne(pa(e),ce)&&t.push("devin")}catch{}return t}async function uU(e){let t=WS(Wi(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(VS(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
927
+ `),l>0?1:0}async function XH(e,t,n,r){let o={homeDir:t,isInteractive:!1,full:!0,skip:!1,dryRun:e,out:r},i=[],a=De(Pe(t,process.env,eE()));if(a.enabled)i.push({target:Zp,action:"skip",status:"skipped",detail:Ka(a)});else for(let c of zH)i.push(await _i(o,c));return i.push(...await Qp(o,{ctx:$t({projectRoot:n,homeDir:t,platform:eE(),env:process.env,bridgeEntry:oe()}),probe:ce,noRules:!1,cwd:n})),i}var zH,rE=w(()=>{"use strict";ie();_t();Je();Ta();ve();ef();oo();Ki();Lc();zH=je.filter(e=>e.subcommand===Lt||e.subcommand===J);s(tE,"renderMigrationPlan");s(JH,"channelVerb");s(YH,"runMigrateRepoBlocks");s(XH,"defaultChannelSetup")});var lE={};Z(lE,{channelProbe:()=>cE,contextProbe:()=>aE,realProbe:()=>Wi,resolveNvmAlias:()=>sE,runDoctor:()=>gU});import{execFileSync as ZH}from"node:child_process";import{existsSync as Gi,readFileSync as QH,readdirSync as Cf,realpathSync as eU,statSync as tU,unlinkSync as nU}from"node:fs";import{homedir as kt,platform as _r}from"node:os";import{delimiter as rU,dirname as oE,join as se}from"node:path";import{parse as oU}from"smol-toml";function Se(e){try{return Gi(e)?QH(e,"utf8"):null}catch{return null}}function iU(){try{let e=ZH(_r()==="win32"?"npm.cmd":"npm",["view",iE,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function Tf(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:se(kt(),".nvm")}function sU(){let e=se(Tf(),"versions","node"),t=[];try{t=Cf(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Se(se(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),o=null;try{o=r?JSON.parse(r).version??null:null}catch{o=null}return{node:n,bridgeVersion:o}})}function sE(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 o=[...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 o.at(-1)??null;let i=r.startsWith("v")?r:`v${r}`;if(t.includes(i))return i;let a=i.endsWith(".")?i:`${i}.`;return o.filter(c=>c.startsWith(a)).at(-1)??null}function aU(e){let t=Se(se(Tf(),"alias","default"));return t===null?null:sE(t,e.map(n=>n.node),n=>{let r=Se(se(Tf(),"alias",n));return r===null?null:r})}function cU(){let e=_r()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(rU))if(t)for(let n of e){let r=se(t,n);if(Gi(r)){let o=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:o?o[1]:null,path:r}}}return null}function lU(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:_r()==="win32"?se(process.env.LOCALAPPDATA??se(kt(),"AppData","Local"),"npm-cache"):se(kt(),".npm"),t=se(e,"_npx"),n=[],r=[];try{r=Cf(t)}catch{return[]}for(let o of r)try{let i=Cf(se(t,o,"node_modules"));i.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:se(t,o),maind:i.includes("@maind-dev")})}catch{}return n}function dU(e){let t;try{t=oE(eU(e))}catch{return null}for(let n=0;n<6;n++){let r=Se(se(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===iE)return i.version??null}catch{}let o=oE(t);if(o===t)break;t=o}return null}function aE(e){let t=ln(e),n=!1;try{let o=Se(mo);n=o!==null&&typeof JSON.parse(o).conventions=="string"}catch{n=!1}let r=ac();return{repoRoot:t,indexPresent:t!==null&&Gi(se(t,cn)),conventionsCached:n||t!==null&&Gi(se(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function Wi(e=process.cwd(),t={}){let n=sU(),r=Se(se(it(),"device-id")),o=$t({projectRoot:e,homeDir:kt(),platform:_r(),env:process.env,bridgeEntry:oe()}),i=null;try{i=z()}catch{i=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=Q(),l=we({entryPath:oe(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:H,latestVersion:t.offline===!0?null:iU(),nodeTrees:n,nvmDefault:aU(n),pathWinner:cU(),clientConfigs:fi(o).map(d=>({key:d.key,label:d.label,path:d.path,kind:d.kind,raw:Se(d.path),present:d.presence===void 0?null:Ne(d.presence,ce)})),npxStaleDirs:lU(),connection:Qb(),claudeSettings:Se(se(kt(),".claude","settings.json")),fileExists:s(d=>Gi(d),"fileExists"),installVersionOf:dU,deviceId:r===null?null:r.trim(),apiKey:i,envApiKey:a.length>0?a:null,guardMode:he(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?ze(l):null,context:t.offline===!0?null:aE(e),foreignHookHosts:pU(o),repoBlocks:t.offline===!0?null:uU(e),channels:t.offline===!0?[]:cE(o),plugin:De(Pe(kt(),process.env,_r()))}}function uU(e){try{return wo(e)}catch{return null}}function cE(e){let t=[];try{if(Ne(Yr(e),ce)){let n=pi(e),r=null;try{let o=Se(n);r=o===null?null:Ei(oU(o),J)}catch{r=null}if(r===null)try{let o=Se(se(Jr(e),"hooks.json"));r=o===null?null:Ei(JSON.parse(o),J)}catch{r=null}t.push({client:"codex",label:"Codex SessionStart hook",path:n,state:r===null?"missing":"ok"})}for(let n of ir(e,ce)){if(!Ne(n.presence,ce))continue;let r=Se(n.path);t.push({client:n.id,label:n.label,path:n.path,state:r===null?"missing":so(r)?"ok":"foreign"})}}catch{}return t}function pU(e){let t=[];try{Ne(Mt(e),ce)&&t.push("cursor"),Ne(fa(e),ce)&&t.push("devin")}catch{}return t}async function fU(e){let t=VS(Wi(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(qS(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
925
928
  `);continue}if(Se(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
926
- `),n++;continue}try{r.action==="delete"?eU(r.path):await U(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
929
+ `),n++;continue}try{r.action==="delete"?nU(r.path):await U(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
927
930
  `)}catch(o){process.stdout.write(` failed ${r.path}: ${o instanceof Error?o.message:String(o)}
928
- `),n++}}return n>0?1:0}async function pU(e){let t=se(kt(),".claude","settings.json"),n=De(Pe(kt(),process.env,_r())),r=Se(t),o=n.enabled?YS(r,t):null;if(process.stdout.write(XS(o,e,n.enabled)),!e||o===null)return 0;if(Se(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
931
+ `),n++}}return n>0?1:0}async function mU(e){let t=se(kt(),".claude","settings.json"),n=De(Pe(kt(),process.env,_r())),r=Se(t),o=n.enabled?XS(r,t):null;if(process.stdout.write(ZS(o,e,n.enabled)),!e||o===null)return 0;if(Se(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
929
932
  `),1;try{return await U(t,o.next,384),process.stdout.write(` edited ${t} \u2014 ${o.removed.length} hook entr${o.removed.length===1?"y":"ies"} removed
930
933
  `),0}catch(i){return process.stdout.write(` failed ${t}: ${i instanceof Error?i.message:String(i)}
931
- `),1}}async function fU(e){let t=se(kt(),".claude.json"),n=De(Pe(kt(),process.env,_r())),r=Se(t),o=n.enabled?NS(r,t):null;if(process.stdout.write(OS(o,e,n.enabled)),!e||o===null)return 0;if(Se(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
932
- `),1;try{let i;try{i=QH(t).mode&511}catch{i=384}return await U(t,o.next,i),process.stdout.write(` edited ${t} \u2014 removed ${o.removed.map(a=>a.join(".")).join(", ")}
934
+ `),1}}async function hU(e){let t=se(kt(),".claude.json"),n=De(Pe(kt(),process.env,_r())),r=Se(t),o=n.enabled?OS(r,t):null;if(process.stdout.write(DS(o,e,n.enabled)),!e||o===null)return 0;if(Se(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
935
+ `),1;try{let i;try{i=tU(t).mode&511}catch{i=384}return await U(t,o.next,i),process.stdout.write(` edited ${t} \u2014 removed ${o.removed.map(a=>a.join(".")).join(", ")}
933
936
  `),0}catch(i){return process.stdout.write(` failed ${t}: ${i instanceof Error?i.message:String(i)}
934
- `),1}}async function mU(e){if(e.includes("--remove-phantoms"))return uU(e.includes("--yes"));if(e.includes("--remove-duplicate-hooks"))return pU(e.includes("--yes"));if(e.includes("--remove-duplicate-mcp"))return fU(e.includes("--yes"));if(e.includes("--migrate-repo-blocks")){let{runMigrateRepoBlocks:n}=await Promise.resolve().then(()=>(nE(),tE));return n(e.includes("--yes"))}let t=Pc(Wi());return e.includes("--json")?process.stdout.write(JSON.stringify({version:H,findings:t},null,2)+`
935
- `):process.stdout.write(FS(t)),t.some(n=>n.level==="error")?1:0}var oE,Af=w(()=>{"use strict";Ue();Iu();pr();Ua();hn();re();vt();_t();ie();Je();Xr();Cp();Ga();ve();Fe();Mc();qS();$c();ZS();_f();oo();oE="@maind-dev/mcp-bridge";s(Se,"readOrNull");s(rU,"latestVersion");s(Tf,"nvmDir");s(oU,"nodeTrees");s(iE,"resolveNvmAlias");s(iU,"nvmDefault");s(sU,"pathWinner");s(aU,"npxStaleDirs");s(cU,"installVersionOf");s(sE,"contextProbe");s(Wi,"realProbe");s(lU,"safeScan");s(aE,"channelProbe");s(dU,"foreignHookHosts");s(uU,"removePhantoms");s(pU,"removeDuplicateHooks");s(fU,"removeDuplicateMcp");s(mU,"runDoctor")});function lE(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function uE(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let o=r,i=Array.isArray(o.active_claims)?o.active_claims:[],a=[];for(let c of i){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 o.session_id_short=="string"?o.session_id_short:"?",is_own_user:o.is_own_user===!0,branch:typeof o.branch=="string"?o.branch:null,focus:typeof o.focus=="string"?o.focus:null,machine_label:typeof o.machine_label=="string"?o.machine_label:null,last_seen_seconds:typeof o.last_seen_seconds=="number"?o.last_seen_seconds:0,claims:a,working_paths:Array.isArray(o.working_paths)?o.working_paths.filter(c=>typeof c=="string"):[]})}return n}function br(e,t){if(t.hostPids.length>0){let r=e.find(o=>t.hostPids.includes(o.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 Vi(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function pE(e,t,n){let r=n.maxAgeMs??dE,o=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let i=o/1e3,a=uE(e,i),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)lE(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 ${Vi(l.last_seen_seconds+i)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Vi(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(lE(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Vi(l.last_seen_seconds+i)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Vi(i)} ago, advisory \u2014 never a lock):
937
+ `),1}}async function gU(e){if(e.includes("--remove-phantoms"))return fU(e.includes("--yes"));if(e.includes("--remove-duplicate-hooks"))return mU(e.includes("--yes"));if(e.includes("--remove-duplicate-mcp"))return hU(e.includes("--yes"));if(e.includes("--migrate-repo-blocks")){let{runMigrateRepoBlocks:n}=await Promise.resolve().then(()=>(rE(),nE));return n(e.includes("--yes"))}let t=Mc(Wi());return e.includes("--json")?process.stdout.write(JSON.stringify({version:H,findings:t},null,2)+`
938
+ `):process.stdout.write(jS(t)),t.some(n=>n.level==="error")?1:0}var iE,Af=w(()=>{"use strict";Ue();Iu();pr();Ba();hn();re();vt();_t();ie();Je();Xr();Cp();Wa();ve();Fe();$c();zS();Lc();QS();_f();oo();iE="@maind-dev/mcp-bridge";s(Se,"readOrNull");s(iU,"latestVersion");s(Tf,"nvmDir");s(sU,"nodeTrees");s(sE,"resolveNvmAlias");s(aU,"nvmDefault");s(cU,"pathWinner");s(lU,"npxStaleDirs");s(dU,"installVersionOf");s(aE,"contextProbe");s(Wi,"realProbe");s(uU,"safeScan");s(cE,"channelProbe");s(pU,"foreignHookHosts");s(fU,"removePhantoms");s(mU,"removeDuplicateHooks");s(hU,"removeDuplicateMcp");s(gU,"runDoctor")});function dE(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function pE(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let o=r,i=Array.isArray(o.active_claims)?o.active_claims:[],a=[];for(let c of i){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 o.session_id_short=="string"?o.session_id_short:"?",is_own_user:o.is_own_user===!0,branch:typeof o.branch=="string"?o.branch:null,focus:typeof o.focus=="string"?o.focus:null,machine_label:typeof o.machine_label=="string"?o.machine_label:null,last_seen_seconds:typeof o.last_seen_seconds=="number"?o.last_seen_seconds:0,claims:a,working_paths:Array.isArray(o.working_paths)?o.working_paths.filter(c=>typeof c=="string"):[]})}return n}function br(e,t){if(t.hostPids.length>0){let r=e.find(o=>t.hostPids.includes(o.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 Vi(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function fE(e,t,n){let r=n.maxAgeMs??uE,o=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let i=o/1e3,a=pE(e,i),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)dE(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 ${Vi(l.last_seen_seconds+i)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Vi(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(dE(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Vi(l.last_seen_seconds+i)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Vi(i)} ago, advisory \u2014 never a lock):
936
939
  `+c.map(l=>` \u2022 ${l}`).join(`
937
940
  `)+`
938
- 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 fE(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 mE(e,t,n,r=dE,o=null){if(!e)return null;let i=n-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let a=i/1e3,c=uE(e,a),l=o!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${o}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",f=u>0?`, ${u} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${Vi(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
939
- ${h}`:h}var dE,Fc=w(()=>{"use strict";s(lE,"prefixConflict");dE=10*6e4;s(uE,"parsePeers");s(br,"selectOwnSnapshot");s(Vi,"ageDisplay");s(pE,"adviseOnPath");s(fE,"claimedIdentity");s(mE,"sessionStartSummary")});function gE(e){let t=[];for(let n of yE(e)){let r=vU(n);r&&!t.includes(r)&&t.push(r)}return t}function yE(e){let t=[],n="",r=null,o=0,i=[],a=s(()=>{n.trim()&&t.push(n),n=""},"flush");for(;o<e.length;){let c=e[o];if(r){if(c==="\\"&&r==='"'){n+=c+(e[o+1]??""),o+=2;continue}c===r&&(r=null),n+=c,o+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,o+=1;continue}if(c==="<"&&e[o+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(o));if(l){i.push(l[1]??l[2]??l[3]),n+=l[0],o+=l[0].length;continue}}if(c===`
941
+ 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 mE(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 hE(e,t,n,r=uE,o=null){if(!e)return null;let i=n-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let a=i/1e3,c=pE(e,a),l=o!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${o}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",f=u>0?`, ${u} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${Vi(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
942
+ ${h}`:h}var uE,jc=w(()=>{"use strict";s(dE,"prefixConflict");uE=10*6e4;s(pE,"parsePeers");s(br,"selectOwnSnapshot");s(Vi,"ageDisplay");s(fE,"adviseOnPath");s(mE,"claimedIdentity");s(hE,"sessionStartSummary")});function yE(e){let t=[];for(let n of _E(e)){let r=xU(n);r&&!t.includes(r)&&t.push(r)}return t}function _E(e){let t=[],n="",r=null,o=0,i=[],a=s(()=>{n.trim()&&t.push(n),n=""},"flush");for(;o<e.length;){let c=e[o];if(r){if(c==="\\"&&r==='"'){n+=c+(e[o+1]??""),o+=2;continue}c===r&&(r=null),n+=c,o+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,o+=1;continue}if(c==="<"&&e[o+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(o));if(l){i.push(l[1]??l[2]??l[3]),n+=l[0],o+=l[0].length;continue}}if(c===`
940
943
  `){if(i.length>0){let d=e.slice(o+1).split(`
941
- `),u=0;for(;i.length>0&&u<d.length;)d[u].trim()===i[0]&&i.shift(),u+=1;o+=1+d.slice(0,u).reduce((p,f)=>p+f.length+1,0),i=[],a();continue}a(),o+=1;continue}if(c==="&"&&e[o+1]==="&"||c==="|"&&e[o+1]==="|"){a(),o+=2;continue}if(c===";"||c==="|"){a(),o+=1;continue}n+=c,o+=1}return a(),t}function vU(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(gU.test(a)){n+=1;continue}if(_U.has(a)){n+=1;continue}if(bU.has(a))return null;let c=a.split("/").pop()??a;if(yU.has(c)){n+=1;continue}break}let r=t[n],o=r.split("/").pop()??r;if(!hE.test(o))return null;if(!hU.test(o))return If;if(!wU.has(o))return o;let i=t[n+1];return i&&hE.test(i)?`${o} ${i}`:o}function Nf(e){let t=gE(e).filter(n=>n!==If&&!_E.has(n));return t.length>0?t[t.length-1]:null}var hE,hU,If,gU,yU,_U,bU,wU,_E,Of=w(()=>{"use strict";hE=/^[A-Za-z][A-Za-z0-9._-]*$/,hU=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,If="?",gU=/^[A-Za-z_][A-Za-z0-9_]*=/,yU=new Set(["sudo","env","time","nohup","nice","command","exec"]),_U=new Set(["do","then","else","elif","if","while","until","!","{","("]),bU=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),wU=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(gE,"shellPrograms");s(yE,"commandSegments");s(vU,"programOf");_E=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(Nf,"primaryVerb")});function bE(e){let t=e.length>Df?e.slice(-Df):e;return kU.some(n=>n.test(t))}function Pf(e){return e.includes("maind")?xU.some(t=>e.includes(t)):!1}function wE(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!SU.some(t=>e.startsWith(t))}function vE(e,t){if(!wE(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?Nf(n):null}function Mf(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=vE(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&bE(e.output)?"fail":"ok",verb:t}}var Df,kU,xU,SU,kE=w(()=>{"use strict";Of();Df=8192,kU=[/\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(bE,"outputShowsFailure");xU=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];s(Pf,"isConsultationTool");SU=["mcp__maind__","mcp__plugin_maind_maind__"];s(wE,"isCountedTool");s(vE,"verbOfCall");s(Mf,"observe")});function xE(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 $f(e,t=-1/0){let n=e.filter(i=>i.k==="fail"&&i.t>t).slice().sort((i,a)=>i.t-a.t),r=[],o=[];for(let i of n)o.length>0&&i.t-o[o.length-1].t>6e5&&(r.push(xE(o)),o=[]),o.push(i);return o.length>0&&r.push(xE(o)),r}function Lf(e,t,n){if(t===null)return null;let r=null;for(let o of e)o.k==="ok"&&o.v===t&&o.t>n&&(r===null||o.t<r)&&(r=o.t);return r}function SE(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function vo(e,t,n){let r=SE(e,t),o=$f(e,r),i=o.length>0?o[o.length-1]:null,a=i!==null&&n-i.end<=6e5?i:null;if(a===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=Lf(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 Ff(e){return e.open&&!e.nudged}function jf(e,t){let n=-1/0;for(let i of e)i.k==="prompt"&&i.t>n&&(n=i.t);let r=Math.max(t,n),o=$f(e,r);for(let i=o.length-1;i>=0;i--){let a=o[i];if(a.failures.length<5||a.end-a.start<3e5)continue;let c=Lf(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function qi(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 Hf=w(()=>{"use strict";s(xE,"chainOf");s($f,"failureChains");s(Lf,"succeededAfter");s(SE,"resetPoint");s(vo,"difficultyStatus");s(Ff,"shouldNudge");s(jf,"captureCandidate");s(qi,"verbSummary")});function RU(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,o=e.severity,i=typeof o=="string"&&EU.has(o)?o:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:i,enabled:a}}function Hc(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return Ji;let n=null,r=null;for(let o of t){if(o===null||typeof o!="object")continue;let i=RU(o);i!==null&&(i.id===zi?n=i:i.id===jc&&(r=i))}return{difficulty:n,capture:r}}function ko(e){return e!==null&&e.enabled}function Uf(e){return ko(e)&&e.severity==="required"}var zi,jc,Ji,EU,Bf=w(()=>{"use strict";zi="conv_consult_on_difficulty",jc="conv_learning_capture_offer",Ji={difficulty:null,capture:null},EU=new Set(["required","recommended","info"]);s(RU,"ruleOf");s(Hc,"extractTriggerPolicy");s(ko,"isActive");s(Uf,"isDenyCapable")});function CU(e){return Math.max(1,Math.round(e/6e4))}function Yi(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${qi(e)}) and no maind consultation since they started (${zi}). 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 Kf(e){return`difficulty episode (${e.failures.length} failed attempts: ${qi(e)}) without a maind consultation since it started (${zi}, required)`}function Gf(e,t="guard"){let n=CU(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${jc}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${qi(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 EE=w(()=>{"use strict";Hf();Bf();s(CU,"minutes");s(Yi,"nudgeText");s(Kf,"difficultyDenyHead");s(Gf,"captureText")});var xo=w(()=>{"use strict";Of();kE();Hf();Bf();EE()});import{existsSync as TU,mkdirSync as AU,readFileSync as IU,readdirSync as NU,renameSync as OU,statSync as DU,unlinkSync as PU,writeFileSync as MU}from"node:fs";import{join as TE}from"node:path";function FU(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function jU(e){try{let t=JSON.parse(IU(e,"utf8"));return{ids:Array.isArray(t.ids)?t.ids.filter(n=>typeof n=="string"):[],...typeof t.project_key=="string"?{project_key:t.project_key}:{},...typeof t.seen_written_at=="string"?{seen_written_at:t.seen_written_at}:{}}}catch{return{ids:[]}}}function CE(e,t,n){AU(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;MU(r,JSON.stringify({...n,ids:n.ids.slice(-200)}),{mode:384}),OU(r,t)}function HU(e,t,n){try{for(let r of NU(e)){let o=TE(e,r);o!==n&&t-DU(o).mtimeMs>LU&&PU(o)}}catch{}}function Xi(e,t,n={}){try{if(!e||e==="unknown")return null;let r=(n.now??Date.now)(),o=n.toldDir??Bm(),i=TE(o,`${FU(e)}.json`),a=TU(i)?jU(i):{ids:[]},c=a.project_key??(n.projectKey??ne)();if(c===null)return null;let l=(n.readSnapshots??gr)(c),u=br(l,{hostPids:n.hostPids??[],cwd:t})?.snap??null??l.find(h=>!h.announce_error&&r-Date.parse(h.written_at)<$U)??null;if(u===null)return a.project_key===void 0&&CE(o,i,{...a,project_key:c}),null;if(u.written_at===a.seen_written_at)return null;let f=(u.announce_error?[]:u.assigned_to_you??[]).filter(h=>!a.ids.includes(h.id));return CE(o,i,{ids:[...a.ids,...f.map(h=>h.id)],project_key:c,seen_written_at:u.written_at}),HU(o,r,i),dl(f)}catch{return null}}var $U,LU,Wf=w(()=>{"use strict";Oo();ji();pe();Fc();$U=5*6e4,LU=7*24*60*60*1e3;s(FU,"safeName");s(jU,"readTold");s(CE,"writeTold");s(HU,"pruneTold");s(Xi,"pendingAssignedNotice")});function UU(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":ae()}}async function AE(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:UU(t),body:JSON.stringify({metrics:n})});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:i.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 Uc,Vf=w(()=>{"use strict";re();qr();Uc=process.env.MAIND_ENDPOINT??Vr("mcp-client-metrics-ingest");s(UU,"ingestHeaders");s(AE,"postMetrics")});import{realpathSync as BU}from"node:fs";import{basename as IE,dirname as NE,join as KU}from"node:path";function wr(e){let t=NE(e),n=[IE(e)];for(;;)try{let r=BU(t);return KU(r,...n.reverse())}catch{let r=NE(t);if(r===t)return e;n.push(IE(t)),t=r}}var Bc=w(()=>{"use strict";s(wr,"realpathOfUnwritten")});import{createHash as GU}from"node:crypto";import{mkdirSync as WU,readFileSync as VU,renameSync as qU,writeFileSync as zU}from"node:fs";import{dirname as JU,join as YU}from"node:path";function ZU(e){try{let t=JSON.parse(VU(e,"utf8"));if(t&&typeof t.repos=="object"&&t.repos!==null){let n={};for(let[r,o]of Object.entries(t.repos))typeof o=="string"&&(n[r]=o);return{version:1,repos:n}}}catch{}return{version:1,repos:{}}}function QU(e,t){WU(JU(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;zU(n,JSON.stringify(t,null,2),{mode:384}),qU(n,e)}function eB(e){return`[maind] setup note \u2014 this repository still carries the maind blocks earlier installs wrote into it: ${Dc(e.plans)}. The bridge no longer writes into repositories (ADR-364); this session gets the same hint and conventions from its hooks and user-level files, and the blocks stay effective until you remove them. To list them (and, after a look, remove them with --yes), run in a terminal: maind-mcp-bridge doctor --migrate-repo-blocks (or npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks).`}function OE(e,t={}){try{let n=(t.scan??wo)(e);if(n===null||!n.inRepo||!yr(n.plans))return null;let r=t.stateFile??XU,o=ZU(r),i=GU("sha256").update(n.root).digest("hex");return o.repos[i]!==void 0?null:(o.repos[i]=new Date(t.nowMs??Date.now()).toISOString(),QU(r,o),eB(n))}catch{return null}}var XU,DE=w(()=>{"use strict";at();Ki();$c();XU=YU(Te,"repo-blocks-notice.json");s(ZU,"readNoticeState");s(QU,"writeNoticeState");s(eB,"repoBlocksNoticeText");s(OE,"repoBlocksNotice")});import{existsSync as tB,realpathSync as nB,statSync as rB}from"node:fs";import{dirname as PE,isAbsolute as oB,join as iB}from"node:path";function cB(e,t){let n=e.filter(o=>ME.includes(o.id));if(n.length===0)return null;let r=n.map(o=>{let i=o.hint?`
944
+ `),u=0;for(;i.length>0&&u<d.length;)d[u].trim()===i[0]&&i.shift(),u+=1;o+=1+d.slice(0,u).reduce((p,f)=>p+f.length+1,0),i=[],a();continue}a(),o+=1;continue}if(c==="&"&&e[o+1]==="&"||c==="|"&&e[o+1]==="|"){a(),o+=2;continue}if(c===";"||c==="|"){a(),o+=1;continue}n+=c,o+=1}return a(),t}function xU(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(_U.test(a)){n+=1;continue}if(wU.has(a)){n+=1;continue}if(vU.has(a))return null;let c=a.split("/").pop()??a;if(bU.has(c)){n+=1;continue}break}let r=t[n],o=r.split("/").pop()??r;if(!gE.test(o))return null;if(!yU.test(o))return If;if(!kU.has(o))return o;let i=t[n+1];return i&&gE.test(i)?`${o} ${i}`:o}function Nf(e){let t=yE(e).filter(n=>n!==If&&!bE.has(n));return t.length>0?t[t.length-1]:null}var gE,yU,If,_U,bU,wU,vU,kU,bE,Of=w(()=>{"use strict";gE=/^[A-Za-z][A-Za-z0-9._-]*$/,yU=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,If="?",_U=/^[A-Za-z_][A-Za-z0-9_]*=/,bU=new Set(["sudo","env","time","nohup","nice","command","exec"]),wU=new Set(["do","then","else","elif","if","while","until","!","{","("]),vU=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),kU=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(yE,"shellPrograms");s(_E,"commandSegments");s(xU,"programOf");bE=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(Nf,"primaryVerb")});function wE(e){let t=e.length>Df?e.slice(-Df):e;return SU.some(n=>n.test(t))}function Pf(e){return e.includes("maind")?EU.some(t=>e.includes(t)):!1}function vE(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!RU.some(t=>e.startsWith(t))}function kE(e,t){if(!vE(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?Nf(n):null}function Mf(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=kE(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&wE(e.output)?"fail":"ok",verb:t}}var Df,SU,EU,RU,xE=w(()=>{"use strict";Of();Df=8192,SU=[/\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(wE,"outputShowsFailure");EU=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];s(Pf,"isConsultationTool");RU=["mcp__maind__","mcp__plugin_maind_maind__"];s(vE,"isCountedTool");s(kE,"verbOfCall");s(Mf,"observe")});function SE(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 $f(e,t=-1/0){let n=e.filter(i=>i.k==="fail"&&i.t>t).slice().sort((i,a)=>i.t-a.t),r=[],o=[];for(let i of n)o.length>0&&i.t-o[o.length-1].t>6e5&&(r.push(SE(o)),o=[]),o.push(i);return o.length>0&&r.push(SE(o)),r}function Lf(e,t,n){if(t===null)return null;let r=null;for(let o of e)o.k==="ok"&&o.v===t&&o.t>n&&(r===null||o.t<r)&&(r=o.t);return r}function EE(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function vo(e,t,n){let r=EE(e,t),o=$f(e,r),i=o.length>0?o[o.length-1]:null,a=i!==null&&n-i.end<=6e5?i:null;if(a===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=Lf(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 Ff(e){return e.open&&!e.nudged}function jf(e,t){let n=-1/0;for(let i of e)i.k==="prompt"&&i.t>n&&(n=i.t);let r=Math.max(t,n),o=$f(e,r);for(let i=o.length-1;i>=0;i--){let a=o[i];if(a.failures.length<5||a.end-a.start<3e5)continue;let c=Lf(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function qi(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 Hf=w(()=>{"use strict";s(SE,"chainOf");s($f,"failureChains");s(Lf,"succeededAfter");s(EE,"resetPoint");s(vo,"difficultyStatus");s(Ff,"shouldNudge");s(jf,"captureCandidate");s(qi,"verbSummary")});function TU(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,o=e.severity,i=typeof o=="string"&&CU.has(o)?o:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:i,enabled:a}}function Uc(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return Ji;let n=null,r=null;for(let o of t){if(o===null||typeof o!="object")continue;let i=TU(o);i!==null&&(i.id===zi?n=i:i.id===Hc&&(r=i))}return{difficulty:n,capture:r}}function ko(e){return e!==null&&e.enabled}function Uf(e){return ko(e)&&e.severity==="required"}var zi,Hc,Ji,CU,Bf=w(()=>{"use strict";zi="conv_consult_on_difficulty",Hc="conv_learning_capture_offer",Ji={difficulty:null,capture:null},CU=new Set(["required","recommended","info"]);s(TU,"ruleOf");s(Uc,"extractTriggerPolicy");s(ko,"isActive");s(Uf,"isDenyCapable")});function AU(e){return Math.max(1,Math.round(e/6e4))}function Yi(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${qi(e)}) and no maind consultation since they started (${zi}). 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 Kf(e){return`difficulty episode (${e.failures.length} failed attempts: ${qi(e)}) without a maind consultation since it started (${zi}, required)`}function Gf(e,t="guard"){let n=AU(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${Hc}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${qi(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 RE=w(()=>{"use strict";Hf();Bf();s(AU,"minutes");s(Yi,"nudgeText");s(Kf,"difficultyDenyHead");s(Gf,"captureText")});var xo=w(()=>{"use strict";Of();xE();Hf();Bf();RE()});import{existsSync as IU,mkdirSync as NU,readFileSync as OU,readdirSync as DU,renameSync as PU,statSync as MU,unlinkSync as $U,writeFileSync as LU}from"node:fs";import{join as AE}from"node:path";function HU(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function UU(e){try{let t=JSON.parse(OU(e,"utf8"));return{ids:Array.isArray(t.ids)?t.ids.filter(n=>typeof n=="string"):[],...typeof t.project_key=="string"?{project_key:t.project_key}:{},...typeof t.seen_written_at=="string"?{seen_written_at:t.seen_written_at}:{}}}catch{return{ids:[]}}}function TE(e,t,n){NU(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;LU(r,JSON.stringify({...n,ids:n.ids.slice(-200)}),{mode:384}),PU(r,t)}function BU(e,t,n){try{for(let r of DU(e)){let o=AE(e,r);o!==n&&t-MU(o).mtimeMs>jU&&$U(o)}}catch{}}function Xi(e,t,n={}){try{if(!e||e==="unknown")return null;let r=(n.now??Date.now)(),o=n.toldDir??Bm(),i=AE(o,`${HU(e)}.json`),a=IU(i)?UU(i):{ids:[]},c=a.project_key??(n.projectKey??ne)();if(c===null)return null;let l=(n.readSnapshots??gr)(c),u=br(l,{hostPids:n.hostPids??[],cwd:t})?.snap??null??l.find(h=>!h.announce_error&&r-Date.parse(h.written_at)<FU)??null;if(u===null)return a.project_key===void 0&&TE(o,i,{...a,project_key:c}),null;if(u.written_at===a.seen_written_at)return null;let f=(u.announce_error?[]:u.assigned_to_you??[]).filter(h=>!a.ids.includes(h.id));return TE(o,i,{ids:[...a.ids,...f.map(h=>h.id)],project_key:c,seen_written_at:u.written_at}),BU(o,r,i),ul(f)}catch{return null}}var FU,jU,Wf=w(()=>{"use strict";Oo();ji();pe();jc();FU=5*6e4,jU=7*24*60*60*1e3;s(HU,"safeName");s(UU,"readTold");s(TE,"writeTold");s(BU,"pruneTold");s(Xi,"pendingAssignedNotice")});function KU(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":ae()}}async function IE(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:KU(t),body:JSON.stringify({metrics:n})});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:i.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 Bc,Vf=w(()=>{"use strict";re();qr();Bc=process.env.MAIND_ENDPOINT??Vr("mcp-client-metrics-ingest");s(KU,"ingestHeaders");s(IE,"postMetrics")});import{realpathSync as GU}from"node:fs";import{basename as NE,dirname as OE,join as WU}from"node:path";function wr(e){let t=OE(e),n=[NE(e)];for(;;)try{let r=GU(t);return WU(r,...n.reverse())}catch{let r=OE(t);if(r===t)return e;n.push(NE(t)),t=r}}var Kc=w(()=>{"use strict";s(wr,"realpathOfUnwritten")});import{createHash as VU}from"node:crypto";import{mkdirSync as qU,readFileSync as zU,renameSync as JU,writeFileSync as YU}from"node:fs";import{dirname as XU,join as ZU}from"node:path";function eB(e){try{let t=JSON.parse(zU(e,"utf8"));if(t&&typeof t.repos=="object"&&t.repos!==null){let n={};for(let[r,o]of Object.entries(t.repos))typeof o=="string"&&(n[r]=o);return{version:1,repos:n}}}catch{}return{version:1,repos:{}}}function tB(e,t){qU(XU(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;YU(n,JSON.stringify(t,null,2),{mode:384}),JU(n,e)}function nB(e){return`[maind] setup note \u2014 this repository still carries the maind blocks earlier installs wrote into it: ${Pc(e.plans)}. The bridge no longer writes into repositories (ADR-364); this session gets the same hint and conventions from its hooks and user-level files, and the blocks stay effective until you remove them. To list them (and, after a look, remove them with --yes), run in a terminal: maind-mcp-bridge doctor --migrate-repo-blocks (or npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks).`}function DE(e,t={}){try{let n=(t.scan??wo)(e);if(n===null||!n.inRepo||!yr(n.plans))return null;let r=t.stateFile??QU,o=eB(r),i=VU("sha256").update(n.root).digest("hex");return o.repos[i]!==void 0?null:(o.repos[i]=new Date(t.nowMs??Date.now()).toISOString(),tB(r,o),nB(n))}catch{return null}}var QU,PE=w(()=>{"use strict";at();Ki();Lc();QU=ZU(Te,"repo-blocks-notice.json");s(eB,"readNoticeState");s(tB,"writeNoticeState");s(nB,"repoBlocksNoticeText");s(DE,"repoBlocksNotice")});import{existsSync as rB,realpathSync as oB,statSync as iB}from"node:fs";import{dirname as ME,isAbsolute as sB,join as aB}from"node:path";function dB(e,t){let n=e.filter(o=>$E.includes(o.id));if(n.length===0)return null;let r=n.map(o=>{let i=o.hint?`
942
945
  \u2192 ${o.hint}`:"";return` \u2022 ${o.title}
943
946
  ${o.detail}${i}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
944
947
 
@@ -946,49 +949,49 @@ ${h}`:h}var dE,Fc=w(()=>{"use strict";s(lE,"prefixConflict");dE=10*6e4;s(uE,"par
946
949
 
947
950
  `)+`
948
951
 
949
- 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 lB(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function dB(e,t,n,r=Date.now()){let o=e.repo_health_seen??{},i=o[t]??{};i[n]=new Date(r).toISOString(),o[t]=i,e.repo_health_seen=o}function qf(e){let t=PE(e);for(;;){try{if(rB(t).isDirectory())return t}catch{}let n=PE(t);if(n===t)return t;t=n}}async function uB(e,t,n){let r=await n.load();if(lB(r,e,t))return null;dB(r,e,t,n.now?.()),await n.save(r);let o;try{o=await n.check(t)}catch{return null}let i=o.filter(c=>ME.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:sB,metric_value:1},{session_id:e,metric_key:aB,metric_value:i}),await n.save(a),cB(o,t)}async function $E(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=de(e);if(!xe(n,{kind:"context",event:"PreToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return 0;let o=Ze(e);if(!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=oB(o)?o:iB(i,o),c=tB(a)?nB(a):wr(a),l=ot(qf(c));try{ja()&&jv(l,{memoryPath:ro})}catch{}let d=await uB(r,l,{load:ee,save:wt,check:s(async u=>(await zo(u,{includeRelease:!1})).findings,"check")});if(d!==null){let u=me(n,{kind:"context",event:"PreToolUse",text:d});u!==null&&process.stdout.write(u)}return 0}catch{return 0}}var ME,sB,aB,zf=w(()=>{"use strict";tn();Dt();Ha();$e();ke();Bc();Be();ME=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],sB="repo_health_hook_runs",aB="repo_health_hook_findings";s(cB,"formatRepoHealth");s(lB,"alreadySeen");s(dB,"markSeen");s(qf,"nearestExistingDir");s(uB,"repoHealthForEdit");s($E,"runOnRepoHealth")});import{existsSync as pB,readFileSync as fB,realpathSync as mB}from"node:fs";import{isAbsolute as FE,join as jE,posix as hB,relative as gB,sep as yB}from"node:path";function LE(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function kB(e,t){return{contracts:t.filter(r=>LE(r.spec)===e||LE(r.impl)===e).map(r=>r.id),theme:wB.test(e),acl:vB.test(e)}}function xB(e){return e.contracts.length===0&&!e.theme&&!e.acl}function SB(e,t,n,r,o=Date.now()){let i=e.write_health_seen??{},a=i[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(o).toISOString(),keys:[...c]},i[t]=a,e.write_health_seen=i}return l}function EB(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:
952
+ 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 uB(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function pB(e,t,n,r=Date.now()){let o=e.repo_health_seen??{},i=o[t]??{};i[n]=new Date(r).toISOString(),o[t]=i,e.repo_health_seen=o}function qf(e){let t=ME(e);for(;;){try{if(iB(t).isDirectory())return t}catch{}let n=ME(t);if(n===t)return t;t=n}}async function fB(e,t,n){let r=await n.load();if(uB(r,e,t))return null;pB(r,e,t,n.now?.()),await n.save(r);let o;try{o=await n.check(t)}catch{return null}let i=o.filter(c=>$E.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:cB,metric_value:1},{session_id:e,metric_key:lB,metric_value:i}),await n.save(a),dB(o,t)}async function LE(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=de(e);if(!xe(n,{kind:"context",event:"PreToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return 0;let o=Ze(e);if(!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=sB(o)?o:aB(i,o),c=rB(a)?oB(a):wr(a),l=ot(qf(c));try{Ha()&&Hv(l,{memoryPath:ro})}catch{}let d=await fB(r,l,{load:ee,save:wt,check:s(async u=>(await zo(u,{includeRelease:!1})).findings,"check")});if(d!==null){let u=me(n,{kind:"context",event:"PreToolUse",text:d});u!==null&&process.stdout.write(u)}return 0}catch{return 0}}var $E,cB,lB,zf=w(()=>{"use strict";tn();Pt();Ua();$e();ke();Kc();Be();$E=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],cB="repo_health_hook_runs",lB="repo_health_hook_findings";s(dB,"formatRepoHealth");s(uB,"alreadySeen");s(pB,"markSeen");s(qf,"nearestExistingDir");s(fB,"repoHealthForEdit");s(LE,"runOnRepoHealth")});import{existsSync as mB,readFileSync as hB,realpathSync as gB}from"node:fs";import{isAbsolute as jE,join as HE,posix as yB,relative as _B,sep as bB}from"node:path";function FE(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function SB(e,t){return{contracts:t.filter(r=>FE(r.spec)===e||FE(r.impl)===e).map(r=>r.id),theme:kB.test(e),acl:xB.test(e)}}function EB(e){return e.contracts.length===0&&!e.theme&&!e.acl}function RB(e,t,n,r,o=Date.now()){let i=e.write_health_seen??{},a=i[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(o).toISOString(),keys:[...c]},i[t]=a,e.write_health_seen=i}return l}function CB(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:
950
953
 
951
954
  `+e.map(n=>` \u2022 ${n.line}`).join(`
952
955
  `)+`
953
956
 
954
- 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 RB(e,t){let n=gB(e,t);return!n||n.startsWith("..")||FE(n)?null:n.split(yB).join(hB.sep)}function CB(e){try{let t=fB(jE(e,Hs),"utf8"),{manifest:n}=Gs(t);return n?.contracts??[]}catch{return[]}}async function HE(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=de(e);if(!xe(n,{kind:"context",event:"PostToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"",o=Ze(e);if(!r||!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=FE(o)?o:jE(i,o),c=pB(a)?mB(a):wr(a),l=ot(qf(c)),d=RB(l,c);if(d===null)return 0;let u=kB(d,CB(l));if(xB(u))return 0;let p=[];if(u.contracts.length>0)try{let y=await Gn(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=Vn(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=Wn(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(),h=SB(f,r,l,p);f.pending_metrics.push({session_id:r,metric_key:_B,metric_value:1},{session_id:r,metric_key:bB,metric_value:h.length}),await wt(f);let g=EB(h,d);if(g!==null){let y=me(n,{kind:"context",event:"PostToolUse",text:g});y!==null&&process.stdout.write(y)}return 0}catch{return 0}}var _B,bB,wB,vB,UE=w(()=>{"use strict";tn();Dt();$e();ke();zf();Bc();Be();_B="write_health_hook_runs",bB="write_health_hook_findings",wB=/\.(tsx?|jsx?|css)$/,vB=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(LE,"declPath");s(kB,"routesForPath");s(xB,"routesAreEmpty");s(SB,"takeUnreported");s(EB,"formatWriteHealth");s(RB,"repoRelative");s(CB,"readContracts");s(HE,"runOnWriteHealth")});var QE={};Z(QE,{agentHostPidCandidates:()=>lt,closeSessionMetrics:()=>qc,closeTrackedSession:()=>zE,effectiveConfig:()=>vn,flushSessionMetrics:()=>zc,grandparentPid:()=>YE,isCaptureTool:()=>Jf,recordGuardSignals:()=>qE,runFlush:()=>WB,runHookStatus:()=>VB,runOnFileEdit:()=>UB,runOnFileWrite:()=>HB,runOnRepoHealth:()=>$E,runOnSessionStart:()=>PB,runOnToolUse:()=>FB,runOnWriteHealth:()=>HE,runSessionEndMetrics:()=>GB,runSyncConfig:()=>zB,writeIdentitySideChannel:()=>Yf});import{execFileSync as KE}from"node:child_process";import{existsSync as Wc,readFileSync as GE,realpathSync as TB}from"node:fs";import{writeFile as AB}from"node:fs/promises";import{homedir as Vc}from"node:os";import{isAbsolute as Gc,join as Zi,relative as WE}from"node:path";function qE(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let o=Pf(n),i=n.includes("review_changes")||n.includes("review_verdict"),a=Jf(n);if(!o&&!i&&!a)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();o&&(l.consulted_at=d),i&&(l.reviewed_at=d),a&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function Jf(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 zE(e,t,n=Date.now()){OB(e,n);let r=e.sessions[t];if(!r)return!1;let o=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,o)},{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 OB(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let o=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-o>Kc&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i)||0));t-o>Kc&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i.at)||0));t-o>Kc&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let o=Date.parse(r.started_at);!Number.isNaN(o)&&t-o>Kc&&delete e.sessions[n]}}function vn(e){if(e.config)return e.config;let t=z();return t===null?null:{api_key:t,endpoint:Uc}}function JE(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 DB(e){let t=xe(e,{kind:"text",event:"SessionStart"});if(!_n(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=me(e,{kind:"text",event:"SessionStart",text:n.join("")});r!==null&&await cc(r)},"flush")}}async function PB(){let e=await V(),t=de(e),n=DB(t);try{return await MB(e,t,n)}finally{await n.flush()}}async function MB(e,t,n){if(n.speaks)try{let i=LS(Pc(Wi(process.cwd(),{offline:!0})));if(i!==null)n.line(i+`
955
- `);else{let a=OE(process.cwd());a!==null&&n.line(a+`
956
- `)}}catch{}let r=await ee();if(vn(r)===null)return 0;let o=ZE(e);if(o===null)return 0;JE(r,o),await wt(r);try{Yf(e,o)}catch{}try{let i=n.speaks?ne():null;if(i!==null){let a=gr(i),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=br(a,{hostPids:lt(),cwd:c}),d=fE(l?.snap??null,Bi(fo(e)||null,o)),u=mE(l?.snap??a[0]??null,d.id,Date.now(),void 0,d.announceError);u!==null&&n.line(u+`
957
+ 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 TB(e,t){let n=_B(e,t);return!n||n.startsWith("..")||jE(n)?null:n.split(bB).join(yB.sep)}function AB(e){try{let t=hB(HE(e,Us),"utf8"),{manifest:n}=Ws(t);return n?.contracts??[]}catch{return[]}}async function UE(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=de(e);if(!xe(n,{kind:"context",event:"PostToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"",o=Ze(e);if(!r||!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=jE(o)?o:HE(i,o),c=mB(a)?gB(a):wr(a),l=ot(qf(c)),d=TB(l,c);if(d===null)return 0;let u=SB(d,AB(l));if(EB(u))return 0;let p=[];if(u.contracts.length>0)try{let y=await Gn(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=Vn(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=Wn(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(),h=RB(f,r,l,p);f.pending_metrics.push({session_id:r,metric_key:wB,metric_value:1},{session_id:r,metric_key:vB,metric_value:h.length}),await wt(f);let g=CB(h,d);if(g!==null){let y=me(n,{kind:"context",event:"PostToolUse",text:g});y!==null&&process.stdout.write(y)}return 0}catch{return 0}}var wB,vB,kB,xB,BE=w(()=>{"use strict";tn();Pt();$e();ke();zf();Kc();Be();wB="write_health_hook_runs",vB="write_health_hook_findings",kB=/\.(tsx?|jsx?|css)$/,xB=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(FE,"declPath");s(SB,"routesForPath");s(EB,"routesAreEmpty");s(RB,"takeUnreported");s(CB,"formatWriteHealth");s(TB,"repoRelative");s(AB,"readContracts");s(UE,"runOnWriteHealth")});var e0={};Z(e0,{agentHostPidCandidates:()=>lt,closeSessionMetrics:()=>zc,closeTrackedSession:()=>JE,effectiveConfig:()=>vn,flushSessionMetrics:()=>Jc,grandparentPid:()=>XE,isCaptureTool:()=>Jf,recordGuardSignals:()=>zE,runFlush:()=>qB,runHookStatus:()=>zB,runOnFileEdit:()=>KB,runOnFileWrite:()=>BB,runOnRepoHealth:()=>LE,runOnSessionStart:()=>$B,runOnToolUse:()=>HB,runOnWriteHealth:()=>UE,runSessionEndMetrics:()=>VB,runSyncConfig:()=>YB,writeIdentitySideChannel:()=>Yf});import{execFileSync as GE}from"node:child_process";import{existsSync as Vc,readFileSync as WE,realpathSync as IB}from"node:fs";import{writeFile as NB}from"node:fs/promises";import{homedir as qc}from"node:os";import{isAbsolute as Wc,join as Zi,relative as VE}from"node:path";function zE(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let o=Pf(n),i=n.includes("review_changes")||n.includes("review_verdict"),a=Jf(n);if(!o&&!i&&!a)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();o&&(l.consulted_at=d),i&&(l.reviewed_at=d),a&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function Jf(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 JE(e,t,n=Date.now()){PB(e,n);let r=e.sessions[t];if(!r)return!1;let o=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,o)},{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 PB(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let o=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-o>Gc&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i)||0));t-o>Gc&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i.at)||0));t-o>Gc&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let o=Date.parse(r.started_at);!Number.isNaN(o)&&t-o>Gc&&delete e.sessions[n]}}function vn(e){if(e.config)return e.config;let t=z();return t===null?null:{api_key:t,endpoint:Bc}}function YE(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 MB(e){let t=xe(e,{kind:"text",event:"SessionStart"});if(!_n(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=me(e,{kind:"text",event:"SessionStart",text:n.join("")});r!==null&&await lc(r)},"flush")}}async function $B(){let e=await V(),t=de(e),n=MB(t);try{return await LB(e,t,n)}finally{await n.flush()}}async function LB(e,t,n){if(n.speaks)try{let i=FS(Mc(Wi(process.cwd(),{offline:!0})));if(i!==null)n.line(i+`
958
+ `);else{let a=DE(process.cwd());a!==null&&n.line(a+`
959
+ `)}}catch{}let r=await ee();if(vn(r)===null)return 0;let o=QE(e);if(o===null)return 0;YE(r,o),await wt(r);try{Yf(e,o)}catch{}try{let i=n.speaks?ne():null;if(i!==null){let a=gr(i),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=br(a,{hostPids:lt(),cwd:c}),d=mE(l?.snap??null,Bi(fo(e)||null,o)),u=hE(l?.snap??a[0]??null,d.id,Date.now(),void 0,d.announceError);u!==null&&n.line(u+`
957
960
  `);let p=Xi(o,c,{projectKey:s(()=>i,"projectKey"),hostPids:lt()});p!==null&&n.line(`[maind] ${p}
958
- `)}}catch{}try{let i=De(Pe(Vc(),process.env,process.platform)),a=_n(t.host)||i.enabled?[]:Oe($B());if(Wu(a)&&Ea(a)){let c=s(p=>a.filter(f=>f.remedy==="run-install"&&f.status===p).map(f=>f.subcommand).join(", "),"pick"),l=c("missing"),d=c("superseded"),u=[l?`not yet wired: ${l}`:null,d?`old form to replace: ${d}`:null].filter(p=>p!==null).join("; ");process.stderr.write(`[maind] New bridge capability (${u}) \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\`).
959
- `)}}catch{}return 0}function $B(){try{let e=Zi(Vc(),".claude","settings.json");return Wc(e)?GE(e,"utf8"):null}catch{return null}}function Yf(e,t,n,r=_o()){let o=n??lt();if(o.length===0)return;let i=Bi(fo(e)||null,t);if(i===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=fo(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of o)xS({dir:r,agentPid:d,sessionId:t,transcriptStem:i,cwd:a,transcriptPath:c,model:l})}function YE(){try{if(process.platform==="win32")return null;let e=KE("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 lt(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=YE();return n!==null&&n>1&&n!==t&&e.push(n),e}async function FB(){let e=await ee();if(vn(e)===null)return 0;let t=await V(),n=ZE(t)??"unknown",r=JE(e,n);r.tool_call_count+=1;try{let c=lt().filter(l=>SS(_o(),l,LB));n!=="unknown"&&c.length>0&&Yf(t,n,c)}catch{}let o=(t.tool_name??"").toString();(o.includes("search_lessons")||o.includes("get_session_briefing")||o.includes("get_lesson"))&&(r.lessons_consulted+=1),qE(e,n,o),Jf(o)&&n!=="unknown"&&await te({event:"capture_taken",session_id:n,detail:o});let i=t.transcript_path;if(typeof i=="string"&&i&&!r.transcript_path&&(r.transcript_path=i),r.transcript_path){let c=await Zu(r.transcript_path);c&&(r.token_count=c.total_tokens,await KB(e,r))}await wt(e);let a=de(t);try{if(n!=="unknown"&&xe(a,{kind:"context",event:"PreToolUse"})){let c=Xi(n,typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),{hostPids:lt()}),l=c===null?null:me(a,{kind:"context",event:"PreToolUse",text:`[maind] ${c}`});l!==null&&process.stdout.write(l+`
960
- `)}}catch{}return 0}function jB(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
961
+ `)}}catch{}try{let i=De(Pe(qc(),process.env,process.platform)),a=_n(t.host)||i.enabled?[]:Oe(FB());if(Wu(a)&&Ra(a)){let c=s(p=>a.filter(f=>f.remedy==="run-install"&&f.status===p).map(f=>f.subcommand).join(", "),"pick"),l=c("missing"),d=c("superseded"),u=[l?`not yet wired: ${l}`:null,d?`old form to replace: ${d}`:null].filter(p=>p!==null).join("; ");process.stderr.write(`[maind] New bridge capability (${u}) \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\`).
962
+ `)}}catch{}return 0}function FB(){try{let e=Zi(qc(),".claude","settings.json");return Vc(e)?WE(e,"utf8"):null}catch{return null}}function Yf(e,t,n,r=_o()){let o=n??lt();if(o.length===0)return;let i=Bi(fo(e)||null,t);if(i===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=fo(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of o)SS({dir:r,agentPid:d,sessionId:t,transcriptStem:i,cwd:a,transcriptPath:c,model:l})}function XE(){try{if(process.platform==="win32")return null;let e=GE("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 lt(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=XE();return n!==null&&n>1&&n!==t&&e.push(n),e}async function HB(){let e=await ee();if(vn(e)===null)return 0;let t=await V(),n=QE(t)??"unknown",r=YE(e,n);r.tool_call_count+=1;try{let c=lt().filter(l=>ES(_o(),l,jB));n!=="unknown"&&c.length>0&&Yf(t,n,c)}catch{}let o=(t.tool_name??"").toString();(o.includes("search_lessons")||o.includes("get_session_briefing")||o.includes("get_lesson"))&&(r.lessons_consulted+=1),zE(e,n,o),Jf(o)&&n!=="unknown"&&await te({event:"capture_taken",session_id:n,detail:o});let i=t.transcript_path;if(typeof i=="string"&&i&&!r.transcript_path&&(r.transcript_path=i),r.transcript_path){let c=await Zu(r.transcript_path);c&&(r.token_count=c.total_tokens,await WB(e,r))}await wt(e);let a=de(t);try{if(n!=="unknown"&&xe(a,{kind:"context",event:"PreToolUse"})){let c=Xi(n,typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),{hostPids:lt()}),l=c===null?null:me(a,{kind:"context",event:"PreToolUse",text:`[maind] ${c}`});l!==null&&process.stdout.write(l+`
963
+ `)}}catch{}return 0}function UB(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
961
964
  `);return`${t.prefix}${e.number} is already taken:
962
965
  ${n}
963
966
 
964
967
  Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
965
968
 
966
- 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 HB(){try{let e=await V();if((e.tool_name??"")!=="Write")return 0;let t=de(e);if(!xe(t,{kind:"deny"}))return 0;let n=Ze(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Gc(n)?n:Zi(r,n);if(Wc(o))return 0;let i=ot(r),a=WE(i,wr(o));if(a.length===0||a.startsWith("..")||Gc(a))return 0;let c=await Kn(i,a);if(!c.taken||c.namespace===null)return 0;let l=me(t,{kind:"deny",reason:jB(c,c.namespace)});return l!==null&&process.stdout.write(l),0}catch{return 0}}async function UB(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=de(e);if(!xe(n,{kind:"context",event:"PreToolUse"}))return 0;let r=Ze(e);if(!r)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Gc(r)?r:Zi(o,r),a=ne();if(a===null)return 0;let c=gr(a);if(c.length===0)return 0;let l=br(c,{hostPids:lt(),cwd:o});if(l===null)return 0;let d=ot(o),u=Wc(i)?TB(i):wr(i),p=WE(d,u).replace(/\\/g,"/");if(p.length===0||p.startsWith("..")||Gc(p))return 0;let f=pE(l.snap,p,{via:l.via,currentBranch:l.via==="cwd"?BB(o):null,nowMs:Date.now()});if(f===null)return 0;let h=me(n,{kind:"context",event:"PreToolUse",text:f});return h!==null&&process.stdout.write(h),0}catch{return 0}}function BB(e){try{let n=KE("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 KB(e,t){let n=wp(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let o=r/n.model_token_limit,i="ok";if(o>=n.handoff_at_pct/100?i="handoff_recommended":o>=n.warn_at_pct/100&&(i="warn"),t.last_advisory_status===i||(t.last_advisory_status=i,i==="ok"))return;let a=Math.round(o*100),c={session_id:t.session_id,status:i,tokens:r,ratio:Number(o.toFixed(3)),pct:a,thresholds:n,suggested_next:i==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await AB(Zi(Re,`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)}
969
+ 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 BB(){try{let e=await V();if((e.tool_name??"")!=="Write")return 0;let t=de(e);if(!xe(t,{kind:"deny"}))return 0;let n=Ze(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Wc(n)?n:Zi(r,n);if(Vc(o))return 0;let i=ot(r),a=VE(i,wr(o));if(a.length===0||a.startsWith("..")||Wc(a))return 0;let c=await Kn(i,a);if(!c.taken||c.namespace===null)return 0;let l=me(t,{kind:"deny",reason:UB(c,c.namespace)});return l!==null&&process.stdout.write(l),0}catch{return 0}}async function KB(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=de(e);if(!xe(n,{kind:"context",event:"PreToolUse"}))return 0;let r=Ze(e);if(!r)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Wc(r)?r:Zi(o,r),a=ne();if(a===null)return 0;let c=gr(a);if(c.length===0)return 0;let l=br(c,{hostPids:lt(),cwd:o});if(l===null)return 0;let d=ot(o),u=Vc(i)?IB(i):wr(i),p=VE(d,u).replace(/\\/g,"/");if(p.length===0||p.startsWith("..")||Wc(p))return 0;let f=fE(l.snap,p,{via:l.via,currentBranch:l.via==="cwd"?GB(o):null,nowMs:Date.now()});if(f===null)return 0;let h=me(n,{kind:"context",event:"PreToolUse",text:f});return h!==null&&process.stdout.write(h),0}catch{return 0}}function GB(e){try{let n=GE("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 WB(e,t){let n=wp(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let o=r/n.model_token_limit,i="ok";if(o>=n.handoff_at_pct/100?i="handoff_recommended":o>=n.warn_at_pct/100&&(i="warn"),t.last_advisory_status===i||(t.last_advisory_status=i,i==="ok"))return;let a=Math.round(o*100),c={session_id:t.session_id,status:i,tokens:r,ratio:Number(o.toFixed(3)),pct:a,thresholds:n,suggested_next:i==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await NB(Zi(Re,`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)}
967
970
  `)}i==="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.
968
971
  `):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.
969
- `)}async function GB(e){await qc(e)&&await zc(VE)}async function qc(e){try{let t=await ee();if(vn(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(zE(t,r),await wt(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
970
- `),!1}}async function zc(e=VE){try{let t=await ee(),n=vn(t);return n===null?null:await XE(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function WB(){let e=await ee(),t=vn(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 XE(t,NB);return process.stdout.write(JSON.stringify(n,null,2)+`
971
- `),n.ok?0:1}async function XE(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),o=AE(e.endpoint,e.api_key,r),i=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([o,i]);if(a.ok){let c=await ee();return c.pending_metrics=c.pending_metrics.slice(r.length),await wt(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 VB(){let e=await ee(),t=vn(e),n=qB(),r=De(Pe(Vc(),process.env,process.platform)),o=!r.enabled&&Wu(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:wp(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!o,...r.enabled?{provided_by:`maind plugin (${Si}, ${r.source??"?"})`}:{},hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...!r.enabled&&Ea(n.findings)?{remedy:BE}:{}}},null,2)+`
972
+ `)}async function VB(e){await zc(e)&&await Jc(qE)}async function zc(e){try{let t=await ee();if(vn(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(JE(t,r),await wt(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
973
+ `),!1}}async function Jc(e=qE){try{let t=await ee(),n=vn(t);return n===null?null:await ZE(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function qB(){let e=await ee(),t=vn(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 ZE(t,DB);return process.stdout.write(JSON.stringify(n,null,2)+`
974
+ `),n.ok?0:1}async function ZE(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),o=IE(e.endpoint,e.api_key,r),i=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([o,i]);if(a.ok){let c=await ee();return c.pending_metrics=c.pending_metrics.slice(r.length),await wt(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 zB(){let e=await ee(),t=vn(e),n=JB(),r=De(Pe(qc(),process.env,process.platform)),o=!r.enabled&&Wu(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:wp(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!o,...r.enabled?{provided_by:`maind plugin (${Si}, ${r.source??"?"})`}:{},hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...!r.enabled&&Ra(n.findings)?{remedy:KE}:{}}},null,2)+`
972
975
  `),o){process.stderr.write(`
973
976
  [maind] Claude Code hook wiring is incomplete:
974
977
  `);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
975
- `);Ea(n.findings)&&process.stderr.write(` ${BE}
976
- `)}return 0}function qB(){let e=Zi(Vc(),".claude","settings.json"),t=null;try{Wc(e)&&(t=GE(e,"utf8"))}catch{}return{settingsPath:e,findings:Oe(t)}}async function zB(){let e=await ee(),t=vn(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??IB,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)}
978
+ `);Ra(n.findings)&&process.stderr.write(` ${KE}
979
+ `)}return 0}function JB(){let e=Zi(qc(),".claude","settings.json"),t=null;try{Vc(e)&&(t=WE(e,"utf8"))}catch{}return{settingsPath:e,findings:Oe(t)}}async function YB(){let e=await ee(),t=vn(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??OB,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)}
977
980
  `),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
978
981
  `);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
979
982
  `),1}let o;try{o=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
980
983
  `),1}let i=o;return typeof i.warn_at_pct!="number"||typeof i.handoff_at_pct!="number"||typeof i.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
981
984
  `),1):(e.thresholds={warn_at_pct:i.warn_at_pct,handoff_at_pct:i.handoff_at_pct,model_token_limit:i.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await wt(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
982
- `),0)}function ZE(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var IB,VE,NB,Kc,LB,BE,Qi=w(()=>{"use strict";rr();xo();tn();Dt();jt();re();ve();ji();Wf();pe();Vf();Fc();Ic();ke();$e();Bc();Be();qr();Mc();Af();oo();DE();zf();UE();IB=process.env.MAIND_THRESHOLDS_ENDPOINT??Vr("get-context-thresholds"),VE=1500,NB=1e4,Kc=7*24*60*60*1e3;s(qE,"recordGuardSignals");s(Jf,"isCaptureTool");s(zE,"closeTrackedSession");s(OB,"gcState");s(vn,"effectiveConfig");s(JE,"getOrCreateSession");s(DB,"sessionStartOut");s(PB,"runOnSessionStart");s(MB,"sessionStartBody");s($B,"readSettingsRaw");s(Yf,"writeIdentitySideChannel");LB=6e4;s(YE,"grandparentPid");s(lt,"agentHostPidCandidates");s(FB,"runOnToolUse");s(jB,"denyReason");s(HB,"runOnFileWrite");s(UB,"runOnFileEdit");s(BB,"currentGitBranch");s(KB,"maybeEmitAdvisory");s(GB,"runSessionEndMetrics");s(qc,"closeSessionMetrics");s(zc,"flushSessionMetrics");s(WB,"runFlush");s(XE,"flushPending");s(VB,"runHookStatus");BE="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(qB,"readHookWiring");s(zB,"runSyncConfig");s(ZE,"sessionIdOf")});function t0(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!e0.test(n))return null;let r=n.toLowerCase();return t!==null&&e0.test(t)&&r!==t.toLowerCase()?null:r}var e0,n0=w(()=>{"use strict";e0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(t0,"snapshotSessionId")});import{appendFileSync as JB,existsSync as Jc,mkdirSync as r0,readFileSync as YB,readdirSync as XB,renameSync as Xf,rmdirSync as o0,statSync as Zf,unlinkSync as i0,writeFileSync as ZB}from"node:fs";import{join as So}from"node:path";function Qf(e){return e&&a0.test(e)?e:"no-session"}function es(e,t){return So(e,`${t}.job.json`)}function em(e,t){return So(e,`${t}.running.json`)}function c0(e,t){return So(e,`${t}.lock`)}function tm(e){Jc(e)||r0(e,{recursive:!0,mode:448})}function l0(e,t){tm(e);let n=Qf(t.session_id),r=`${es(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;ZB(r,JSON.stringify(t),{mode:384}),Xf(r,es(e,n))}function nK(e){try{let t=JSON.parse(e);if(t&&t.v===1&&typeof t.transcript_path=="string"&&typeof t.cwd=="string")return{v:1,session_id:typeof t.session_id=="string"?t.session_id:null,transcript_path:t.transcript_path,cwd:t.cwd,coord_session_id:typeof t.coord_session_id=="string"?t.coord_session_id:null,project_key:typeof t.project_key=="string"?t.project_key:null,presence:{own_snapshot_age_ms:typeof t.presence?.own_snapshot_age_ms=="number"?t.presence.own_snapshot_age_ms:null,presence_usable:t.presence?.presence_usable===!0},queued_at:typeof t.queued_at=="string"?t.queued_at:new Date(0).toISOString()}}catch{}return null}function d0(e,t){return Jc(es(e,t))}function u0(e,t){let n=es(e,t),r=em(e,t);try{if(Jc(n)&&Xf(n,r),!Jc(r))return null;let o=nK(YB(r,"utf8"));return o===null?(i0(r),null):o}catch{return null}}function p0(e,t){try{i0(em(e,t))}catch{}}function nm(e,t,n=Date.now()){tm(e);let r=c0(e,t);try{if(n-Zf(r).mtimeMs<QB)return!1;o0(r)}catch{}try{return r0(r,{recursive:!1}),!0}catch{return!1}}function rm(e,t){try{o0(c0(e,t))}catch{}}function f0(e){try{let t=new Set;for(let n of XB(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&a0.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function m0(e,t){for(let n of[es(e,t),em(e,t)])try{return Zf(n).mtimeMs}catch{}return null}function Eo(e,t,n=eK){try{tm(e);let r=So(e,tK);try{Zf(r).size>n&&Xf(r,So(e,"runs.1.jsonl"))}catch{}JB(r,JSON.stringify(t)+`
983
- `,{mode:384})}catch{}}var Ut,QB,s0,eK,tK,a0,om=w(()=>{"use strict";Be();Ut=So(Re,"session-end"),QB=10*6e4,s0=7*24*60*6e4,eK=256*1024,tK="runs.jsonl",a0=/^[A-Za-z0-9_-]{1,80}$/;s(Qf,"jobKey");s(es,"jobPath");s(em,"runningPath");s(c0,"lockPath");s(tm,"ensureDir");s(l0,"writeJob");s(nK,"parseJob");s(d0,"hasJob");s(u0,"takeJob");s(p0,"finishJob");s(nm,"acquireLock");s(rm,"releaseLock");s(f0,"pendingKeys");s(m0,"pendingSince");s(Eo,"appendRunLog")});function h0(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var g0=w(()=>{"use strict";s(h0,"resolveConnection")});function y0(e,t,n,r=Date.now()){let o=t===null?null:vi(t),i=typeof n=="object"&&n!==null?n:{repoRoot:n},a=cp(e,o,{repoRoot:i.repoRoot,...i.relativize?{relativize:i.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:o!==null}}var _0=w(()=>{"use strict";rr();s(y0,"buildCostPayload")});function oK(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();rK.test(r)&&!t.includes(r)&&t.push(r)}return t}async function b0(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:o}=await wi(e.transcriptPath),i=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?up({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:iK(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,c=a?pp(r,a):null,l=c??e.projectKey,d=oK([e.coordSessionId,e.sessionId,...o]),u=performance.now(),[p,f,h]=await Promise.all([ep(e.transcriptPath,{turns:r}),gp(e.transcriptPath),e.fetchContext(l,d)]),g={collect_ms:i,parallel_ms:Math.round(performance.now()-u)};if(a&&e.rememberCheckouts)try{e.rememberCheckouts(a.seenLive())}catch{}if(e.sessionId&&(p.session_id=e.sessionId,f.session_id=e.sessionId),p.maind_connected=e.connection(p.maind_connected==="connected",t()),!p.session_id)return{posted:!1,contextOk:h!==null,sentSlices:!1,timings:g};let y=c&&a?fp(c,a):null,_=y0(r,h,{repoRoot:e.repoRoot,relativize:y},t()),b=h===null?null:vi(h)?.canonical_session_id??null,v=e.coordSessionId??b,k=rp(p,f,{client_session_id:v,client:"claude-code",coordination_session_ids:d},"live_bridge",_);return await e.post(k,_!==null),{posted:!0,contextOk:_?.context_ok??h!==null,sentSlices:_!==null,timings:g}}function iK(e,t){try{return e()}catch{return t}}var rK,w0=w(()=>{"use strict";rr();_0();rK=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(oK,"sessionIdsFor");s(b0,"ingestSessionEnd");s(iK,"safe")});var I0={};Z(I0,{FLUSH_LOCK_KEY:()=>cm,INLINE_BUDGET:()=>dm,SESSION_END_WORKER:()=>lm,SWEEP_MAX_KEYS:()=>S0,SWEEP_MIN_AGE_MS:()=>x0,WORKER_BUDGET:()=>k0,WORKER_DEADLINE_MS:()=>sm,drainSession:()=>um,fetchCostContext:()=>E0,flushUnderLock:()=>A0,gitResolvers:()=>C0,liveJobDeps:()=>Xc,postIngest:()=>R0,postIngestOnce:()=>am,processJob:()=>Yc,runSessionEndWorker:()=>cK,sweepPending:()=>T0});import{execFileSync as sK}from"node:child_process";import{existsSync as v0,statSync as aK}from"node:fs";async function E0(e,t,n,r,o){if(n===null)return null;let[i,...a]=r;try{return await Lt("get_session_cost_context",{project_key:n,...i?{session_id:i}:{},...a.length>0?{also_session_ids:a}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:H,timeoutMs:o})}catch{return null}}async function am(e,t,n,r,o,i=fetch){let a=new AbortController,c=setTimeout(()=>a.abort(),r);try{let l=await i(Uc,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":H},body:JSON.stringify(n),signal:a.signal}),d=await l.json().catch(()=>null);if(!l.ok)return{outcome:"post_failed",status:l.status};let u=np(tp(d),o);return{outcome:"posted",status:l.status,...u?{verdict:u}:{}}}catch(l){return{outcome:a.signal.aborted||l instanceof Error&&l.name==="AbortError"?"post_timeout":"post_error"}}finally{clearTimeout(c)}}async function R0(e,t,n,r,o,i={}){let a=i.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=await am(e,t,n,o.postMs,r,i.fetchImpl),l=1;return(c.outcome==="post_timeout"||c.outcome==="post_error"||c.outcome==="post_failed"&&(c.status??0)>=500)&&o.postRetryDelayMs>0&&(await a(o.postRetryDelayMs),c=await am(e,t,n,o.postMs,r,i.fetchImpl),l=2),{...c,attempts:l}}function im(e,t){try{let n=sK("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function C0(){let e=new Map,t=new Map;return{repoRootOf:s(n=>v0(n)?im(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let o=im(["-C",n,"rev-parse","--show-toplevel"]);return e.set(n,o),o},"gitRootOf"),projectKeyOfRoot:s(n=>{let r=t.get(n);if(r!==void 0)return r;let o=im(["-C",n,"config","--get","remote.origin.url"]),i=o?nn(o):null;return t.set(n,i),i},"projectKeyOfRoot"),isDir:s(n=>{try{return aK(n).isDirectory()}catch{return!1}},"isDir")}}async function Yc(e,t){let n=t.now??Date.now,r=n(),o=Date.parse(e.queued_at),i={queued:Number.isFinite(o)?Math.max(0,r-o):0},a={ts:new Date(r).toISOString(),bridge:H,session_id:e.session_id,outcome:"no_transcript",ms:i};try{if(e.transcript_path)if(!v0(e.transcript_path))a.outcome="transcript_gone";else{let l=C0(),d=t.memoryPath??ro,u=null,p=await b0({apiKey:t.apiKey,deviceId:t.deviceId,sessionId:e.session_id,transcriptPath:e.transcript_path,projectKey:e.project_key,coordSessionId:e.coord_session_id,repoRoot:l.repoRootOf(e.cwd),resolveRoot:l.gitRootOf,projectKeyOf:l.projectKeyOfRoot,isDir:l.isDir,...t.memoryAllowed?{knownCheckouts:s(()=>ki(d),"knownCheckouts"),rememberCheckouts:s(h=>xi(d,h),"rememberCheckouts")}:{},fetchContext:s(async(h,g)=>{let y=n();try{return await t.fetchContext(h,g)}finally{i.context=n()-y}},"fetchContext"),post:s(async(h,g)=>{let y=n();u=await t.post(h,g),i.post=n()-y},"post"),connection:s(h=>h0({ownSnapshotAgeMs:e.presence.own_snapshot_age_ms,sawMaindCall:h,presenceUsable:e.presence.presence_usable}),"connection"),now:n});a.context_ok=p.contextOk,a.sent_slices=p.sentSlices,p.timings&&(i.collect=p.timings.collect_ms,i.parallel=p.timings.parallel_ms);let f=u;!p.posted||f===null?a.outcome="not_posted":(a.outcome=f.outcome,a.attempts=f.attempts,f.status!==void 0&&(a.http_status=f.status),f.verdict&&(a.verdict=f.verdict))}}catch(l){a.outcome="error",a.error=(l instanceof Error?l.message:String(l)).slice(0,200)}let c=n();try{let l=await t.flush();a.flush=l===null?"unpaired":l.ok?`ok:${l.flushed}`:`failed:${l.error??"unknown"}`}catch(l){a.flush=`failed:${(l instanceof Error?l.message:String(l)).slice(0,80)}`}return i.flush=n()-c,i.total=n()-r,a}async function um(e,t,n,r={}){let o=r.now??Date.now,i=r.maxRounds??20,a=0;for(;a<i&&nm(e,t,o());){try{let c=u0(e,t);if(c===null)break;let l=Date.parse(c.queued_at),d=Number.isFinite(l)&&o()-l>s0?{ts:new Date(o()).toISOString(),bridge:H,session_id:c.session_id,outcome:"expired",ms:{queued:o()-l}}:await n(c);Eo(e,d),p0(e,t),a++}finally{rm(e,t)}if(!d0(e,t))break}return a}async function T0(e,t,n,r={}){let o=r.now??Date.now,i=0;for(let a of f0(e)){if(i>=S0)break;if(a===t)continue;let c=m0(e,a);c===null||o()-c<x0||await um(e,a,n,{...r,maxRounds:1})>0&&i++}return i}async function A0(e,t,n=Date.now){if(!nm(e,cm,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{rm(e,cm)}}function Xc(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,o)=>E0(e,t,r,o,n.contextMs),"fetchContext"),post:s((r,o)=>R0(e,t,r,o,n),"post"),flush:s(()=>A0(Ut,()=>zc(n.flushMs)),"flush"),memoryAllowed:ja()}}async function cK(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{Eo(Ut,{ts:new Date().toISOString(),bridge:H,session_id:t,outcome:"deadline",ms:{total:sm}}),process.exit(0)},sm);n.unref();try{let r=z();if(!r)return 0;let o=ae(),i=s(a=>Yc(a,Xc(r,o,k0)),"run");await um(Ut,t,i),await T0(Ut,t,i)}catch(r){Eo(Ut,{ts:new Date().toISOString(),bridge:H,session_id:t,outcome:"error",ms:{},error:(r instanceof Error?r.message:String(r)).slice(0,200)})}finally{clearTimeout(n)}return 0}var lm,k0,dm,sm,x0,S0,cm,pm=w(()=>{"use strict";rr();re();gn();Vf();Qi();pe();Fe();Ha();g0();w0();om();lm="session-end-run",k0={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},dm={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},sm=3*6e4,x0=2*6e4,S0=3;s(E0,"fetchCostContext");s(am,"postIngestOnce");s(R0,"postIngest");s(im,"git");s(C0,"gitResolvers");s(Yc,"processJob");s(um,"drainSession");s(T0,"sweepPending");cm="metrics-flush";s(A0,"flushUnderLock");s(Xc,"liveJobDeps");s(cK,"runSessionEndWorker")});var M0={};Z(M0,{buildJob:()=>D0,enqueueAndSpawn:()=>P0,presenceLookup:()=>N0,runOnSessionEnd:()=>hK,transcriptToIngest:()=>O0});import{spawn as lK}from"node:child_process";import{existsSync as dK,unlinkSync as uK}from"node:fs";import{join as pK}from"node:path";function N0(e,t,n,r){let o=null,i={own_snapshot_age_ms:null,presence_usable:!1};try{if(i.presence_usable=e!==null&&!lf(process.env,Q()),e!==null){let a=br(gr(e),{hostPids:r,cwd:process.cwd()});if(a){let c=Date.parse(a.snap.written_at);i={...i,own_snapshot_age_ms:Number.isFinite(c)?Math.max(0,n-c):null}}o=t0(a?.snap,t)}}catch{i={own_snapshot_age_ms:null,presence_usable:!1},o=null}if(o===null){let a=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(a)&&(o=a)}return{coordSessionId:o,evidence:i}}function O0(e,t=process.env){let n=fo(e);return n&&!_n(Pi(e,t))?n:""}function D0(e,t){let n=typeof e.session_id=="string"&&e.session_id?e.session_id:null,r={v:1,session_id:n,transcript_path:t.transcriptPath,cwd:t.cwd,coord_session_id:null,project_key:null,presence:{own_snapshot_age_ms:null,presence_usable:!1},queued_at:new Date(t.nowMs).toISOString()};if(!t.transcriptPath)return r;let o=t.projectKey(),i=t.presence(o,Bi(t.transcriptPath,n),t.nowMs);return{...r,project_key:o,coord_session_id:i.coordSessionId,presence:i.evidence}}function P0(e,t={}){let n=t.dir??Ut,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let o=Qf(e.session_id);try{l0(n,e)}catch{return!1}try{return(t.spawnWorker??fK)(r,o,e.cwd),!0}catch{try{uK(pK(n,`${o}.job.json`))}catch{}return!1}}function fK(e,t,n){lK(process.execPath,[e,lm,t],{detached:!0,stdio:"ignore",cwd:dK(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function mK(e,t){try{let n=await Yc(e,Xc(t,ae(),dm));Eo(Ut,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
984
- `)}}async function hK(){let e=[];try{e=lt()}catch{e=[]}try{for(let i of e)ES(_o(),i)}catch{}let t=z();if(!t)return 0;let n=await V(),r=typeof n.session_id=="string"&&n.session_id?n.session_id:null;await qc(r);let o;try{o=D0(n,{transcriptPath:O0(n),cwd:process.cwd(),nowMs:Date.now(),projectKey:ne,presence:s((i,a,c)=>N0(i,a,c,e),"presence")})}catch{return 0}return P0(o)||await mK(o,t),0}var $0=w(()=>{"use strict";Ue();re();Fc();ke();$e();Qi();df();ji();pe();Ic();n0();om();pm();s(N0,"presenceLookup");s(O0,"transcriptToIngest");s(D0,"buildJob");s(P0,"enqueueAndSpawn");s(fK,"spawnDetachedWorker");s(mK,"runInline");s(hK,"runOnSessionEnd")});var L0={};Z(L0,{runOnSessionBriefing:()=>gK});async function gK(e=process.argv.slice(2)){try{return await hc("core",await V(),{hostHint:ix(e)})}catch{return 0}}var F0=w(()=>{"use strict";pr();ke();$e();s(gK,"runOnSessionBriefing")});var H0={};Z(H0,{deliverSessionReminder:()=>j0,runOnSessionReminder:()=>wK});import{readFile as yK}from"node:fs/promises";import{homedir as _K}from"node:os";import{join as bK}from"node:path";async function j0(e,t={}){let n=t.target??de(e);if(!xe(n,{kind:"text",event:"SessionStart"}))return 0;let r;try{r=await yK(bK(t.homeDir??_K(),gi),"utf8")}catch{return 0}if(r.length===0)return 0;let o=me(n,{kind:"text",event:"SessionStart",text:r});return o!==null&&await(t.write??cc)(o),0}async function wK(){try{return await j0(await V())}catch{return 0}}var U0=w(()=>{"use strict";ve();ke();$e();s(j0,"deliverSessionReminder");s(wK,"runOnSessionReminder")});var J0={};Z(J0,{CURSOR_BRIEFING_MARKER:()=>fm,CURSOR_DELIVERY_LOG:()=>B0,CURSOR_UNAVAILABLE_TEXT:()=>G0,appendDelivery:()=>q0,cursorProjectDir:()=>K0,deliverCursorSessionStart:()=>V0,formatCursorBriefing:()=>W0,runOnCursorSessionStart:()=>IK});import{appendFile as vK,mkdir as kK,readFile as xK,stat as SK,writeFile as EK}from"node:fs/promises";import{dirname as RK,join as CK}from"node:path";function K0(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let o=r.find(i=>typeof i=="string"&&i.length>0);if(o)return o}return null}function W0(e,t,n){let o=`${fm}${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 fc(o,n,e)}async function V0(e,t={}){let n=t.write??z0,r=t.env??process.env,o=(t.apiKey??z)();if(o===null)return await n(`{}
985
- `),0;let i=K0(e,r),a=i===null?null:(t.projectKeyFor??yt)(i),c=await ho(a,o,{fetcher:s(p=>ar({...p,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=G0,d="none";else{let p=W0(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})+`
986
- `),await q0(t.logFile??B0,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Ro(e.conversation_id)??Ro(e.session_id),transcript_path:Ro(e.transcript_path)??Ro(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Ro(e.cursor_version)??Ro(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function IK(){try{return await V0(await V())}catch{try{await z0(`{}
987
- `)}catch{}return 0}}async function q0(e,t){try{if(await kK(RK(e),{recursive:!0,mode:448}),await vK(e,JSON.stringify(t)+`
988
- `,{mode:384}),(await SK(e)).size>TK){let n=(await xK(e,"utf8")).split(`
989
- `).filter(r=>r.trim().length>0);await EK(e,n.slice(-AK).join(`
985
+ `),0)}function QE(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var OB,qE,DB,Gc,jB,KE,Qi=w(()=>{"use strict";rr();xo();tn();Pt();Ht();re();ve();ji();Wf();pe();Vf();jc();Nc();ke();$e();Kc();Be();qr();$c();Af();oo();PE();zf();BE();OB=process.env.MAIND_THRESHOLDS_ENDPOINT??Vr("get-context-thresholds"),qE=1500,DB=1e4,Gc=7*24*60*60*1e3;s(zE,"recordGuardSignals");s(Jf,"isCaptureTool");s(JE,"closeTrackedSession");s(PB,"gcState");s(vn,"effectiveConfig");s(YE,"getOrCreateSession");s(MB,"sessionStartOut");s($B,"runOnSessionStart");s(LB,"sessionStartBody");s(FB,"readSettingsRaw");s(Yf,"writeIdentitySideChannel");jB=6e4;s(XE,"grandparentPid");s(lt,"agentHostPidCandidates");s(HB,"runOnToolUse");s(UB,"denyReason");s(BB,"runOnFileWrite");s(KB,"runOnFileEdit");s(GB,"currentGitBranch");s(WB,"maybeEmitAdvisory");s(VB,"runSessionEndMetrics");s(zc,"closeSessionMetrics");s(Jc,"flushSessionMetrics");s(qB,"runFlush");s(ZE,"flushPending");s(zB,"runHookStatus");KE="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(JB,"readHookWiring");s(YB,"runSyncConfig");s(QE,"sessionIdOf")});function n0(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!t0.test(n))return null;let r=n.toLowerCase();return t!==null&&t0.test(t)&&r!==t.toLowerCase()?null:r}var t0,r0=w(()=>{"use strict";t0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(n0,"snapshotSessionId")});import{appendFileSync as XB,existsSync as Yc,mkdirSync as o0,readFileSync as ZB,readdirSync as QB,renameSync as Xf,rmdirSync as i0,statSync as Zf,unlinkSync as s0,writeFileSync as eK}from"node:fs";import{join as So}from"node:path";function Qf(e){return e&&c0.test(e)?e:"no-session"}function es(e,t){return So(e,`${t}.job.json`)}function em(e,t){return So(e,`${t}.running.json`)}function l0(e,t){return So(e,`${t}.lock`)}function tm(e){Yc(e)||o0(e,{recursive:!0,mode:448})}function d0(e,t){tm(e);let n=Qf(t.session_id),r=`${es(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;eK(r,JSON.stringify(t),{mode:384}),Xf(r,es(e,n))}function oK(e){try{let t=JSON.parse(e);if(t&&t.v===1&&typeof t.transcript_path=="string"&&typeof t.cwd=="string")return{v:1,session_id:typeof t.session_id=="string"?t.session_id:null,transcript_path:t.transcript_path,cwd:t.cwd,coord_session_id:typeof t.coord_session_id=="string"?t.coord_session_id:null,project_key:typeof t.project_key=="string"?t.project_key:null,presence:{own_snapshot_age_ms:typeof t.presence?.own_snapshot_age_ms=="number"?t.presence.own_snapshot_age_ms:null,presence_usable:t.presence?.presence_usable===!0},queued_at:typeof t.queued_at=="string"?t.queued_at:new Date(0).toISOString()}}catch{}return null}function u0(e,t){return Yc(es(e,t))}function p0(e,t){let n=es(e,t),r=em(e,t);try{if(Yc(n)&&Xf(n,r),!Yc(r))return null;let o=oK(ZB(r,"utf8"));return o===null?(s0(r),null):o}catch{return null}}function f0(e,t){try{s0(em(e,t))}catch{}}function nm(e,t,n=Date.now()){tm(e);let r=l0(e,t);try{if(n-Zf(r).mtimeMs<tK)return!1;i0(r)}catch{}try{return o0(r,{recursive:!1}),!0}catch{return!1}}function rm(e,t){try{i0(l0(e,t))}catch{}}function m0(e){try{let t=new Set;for(let n of QB(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&c0.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function h0(e,t){for(let n of[es(e,t),em(e,t)])try{return Zf(n).mtimeMs}catch{}return null}function Eo(e,t,n=nK){try{tm(e);let r=So(e,rK);try{Zf(r).size>n&&Xf(r,So(e,"runs.1.jsonl"))}catch{}XB(r,JSON.stringify(t)+`
986
+ `,{mode:384})}catch{}}var Bt,tK,a0,nK,rK,c0,om=w(()=>{"use strict";Be();Bt=So(Re,"session-end"),tK=10*6e4,a0=7*24*60*6e4,nK=256*1024,rK="runs.jsonl",c0=/^[A-Za-z0-9_-]{1,80}$/;s(Qf,"jobKey");s(es,"jobPath");s(em,"runningPath");s(l0,"lockPath");s(tm,"ensureDir");s(d0,"writeJob");s(oK,"parseJob");s(u0,"hasJob");s(p0,"takeJob");s(f0,"finishJob");s(nm,"acquireLock");s(rm,"releaseLock");s(m0,"pendingKeys");s(h0,"pendingSince");s(Eo,"appendRunLog")});function g0(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var y0=w(()=>{"use strict";s(g0,"resolveConnection")});function _0(e,t,n,r=Date.now()){let o=t===null?null:vi(t),i=typeof n=="object"&&n!==null?n:{repoRoot:n},a=cp(e,o,{repoRoot:i.repoRoot,...i.relativize?{relativize:i.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:o!==null}}var b0=w(()=>{"use strict";rr();s(_0,"buildCostPayload")});function sK(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();iK.test(r)&&!t.includes(r)&&t.push(r)}return t}async function w0(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:o}=await wi(e.transcriptPath),i=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?up({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:aK(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,c=a?pp(r,a):null,l=c??e.projectKey,d=sK([e.coordSessionId,e.sessionId,...o]),u=performance.now(),[p,f,h]=await Promise.all([ep(e.transcriptPath,{turns:r}),gp(e.transcriptPath),e.fetchContext(l,d)]),g={collect_ms:i,parallel_ms:Math.round(performance.now()-u)};if(a&&e.rememberCheckouts)try{e.rememberCheckouts(a.seenLive())}catch{}if(e.sessionId&&(p.session_id=e.sessionId,f.session_id=e.sessionId),p.maind_connected=e.connection(p.maind_connected==="connected",t()),!p.session_id)return{posted:!1,contextOk:h!==null,sentSlices:!1,timings:g};let y=c&&a?fp(c,a):null,_=_0(r,h,{repoRoot:e.repoRoot,relativize:y},t()),b=h===null?null:vi(h)?.canonical_session_id??null,v=e.coordSessionId??b,k=rp(p,f,{client_session_id:v,client:"claude-code",coordination_session_ids:d},"live_bridge",_);return await e.post(k,_!==null),{posted:!0,contextOk:_?.context_ok??h!==null,sentSlices:_!==null,timings:g}}function aK(e,t){try{return e()}catch{return t}}var iK,v0=w(()=>{"use strict";rr();b0();iK=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(sK,"sessionIdsFor");s(w0,"ingestSessionEnd");s(aK,"safe")});var N0={};Z(N0,{FLUSH_LOCK_KEY:()=>cm,INLINE_BUDGET:()=>dm,SESSION_END_WORKER:()=>lm,SWEEP_MAX_KEYS:()=>E0,SWEEP_MIN_AGE_MS:()=>S0,WORKER_BUDGET:()=>x0,WORKER_DEADLINE_MS:()=>sm,drainSession:()=>um,fetchCostContext:()=>R0,flushUnderLock:()=>I0,gitResolvers:()=>T0,liveJobDeps:()=>Zc,postIngest:()=>C0,postIngestOnce:()=>am,processJob:()=>Xc,runSessionEndWorker:()=>dK,sweepPending:()=>A0});import{execFileSync as cK}from"node:child_process";import{existsSync as k0,statSync as lK}from"node:fs";async function R0(e,t,n,r,o){if(n===null)return null;let[i,...a]=r;try{return await Ft("get_session_cost_context",{project_key:n,...i?{session_id:i}:{},...a.length>0?{also_session_ids:a}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:H,timeoutMs:o})}catch{return null}}async function am(e,t,n,r,o,i=fetch){let a=new AbortController,c=setTimeout(()=>a.abort(),r);try{let l=await i(Bc,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":H},body:JSON.stringify(n),signal:a.signal}),d=await l.json().catch(()=>null);if(!l.ok)return{outcome:"post_failed",status:l.status};let u=np(tp(d),o);return{outcome:"posted",status:l.status,...u?{verdict:u}:{}}}catch(l){return{outcome:a.signal.aborted||l instanceof Error&&l.name==="AbortError"?"post_timeout":"post_error"}}finally{clearTimeout(c)}}async function C0(e,t,n,r,o,i={}){let a=i.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=await am(e,t,n,o.postMs,r,i.fetchImpl),l=1;return(c.outcome==="post_timeout"||c.outcome==="post_error"||c.outcome==="post_failed"&&(c.status??0)>=500)&&o.postRetryDelayMs>0&&(await a(o.postRetryDelayMs),c=await am(e,t,n,o.postMs,r,i.fetchImpl),l=2),{...c,attempts:l}}function im(e,t){try{let n=cK("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function T0(){let e=new Map,t=new Map;return{repoRootOf:s(n=>k0(n)?im(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let o=im(["-C",n,"rev-parse","--show-toplevel"]);return e.set(n,o),o},"gitRootOf"),projectKeyOfRoot:s(n=>{let r=t.get(n);if(r!==void 0)return r;let o=im(["-C",n,"config","--get","remote.origin.url"]),i=o?nn(o):null;return t.set(n,i),i},"projectKeyOfRoot"),isDir:s(n=>{try{return lK(n).isDirectory()}catch{return!1}},"isDir")}}async function Xc(e,t){let n=t.now??Date.now,r=n(),o=Date.parse(e.queued_at),i={queued:Number.isFinite(o)?Math.max(0,r-o):0},a={ts:new Date(r).toISOString(),bridge:H,session_id:e.session_id,outcome:"no_transcript",ms:i};try{if(e.transcript_path)if(!k0(e.transcript_path))a.outcome="transcript_gone";else{let l=T0(),d=t.memoryPath??ro,u=null,p=await w0({apiKey:t.apiKey,deviceId:t.deviceId,sessionId:e.session_id,transcriptPath:e.transcript_path,projectKey:e.project_key,coordSessionId:e.coord_session_id,repoRoot:l.repoRootOf(e.cwd),resolveRoot:l.gitRootOf,projectKeyOf:l.projectKeyOfRoot,isDir:l.isDir,...t.memoryAllowed?{knownCheckouts:s(()=>ki(d),"knownCheckouts"),rememberCheckouts:s(h=>xi(d,h),"rememberCheckouts")}:{},fetchContext:s(async(h,g)=>{let y=n();try{return await t.fetchContext(h,g)}finally{i.context=n()-y}},"fetchContext"),post:s(async(h,g)=>{let y=n();u=await t.post(h,g),i.post=n()-y},"post"),connection:s(h=>g0({ownSnapshotAgeMs:e.presence.own_snapshot_age_ms,sawMaindCall:h,presenceUsable:e.presence.presence_usable}),"connection"),now:n});a.context_ok=p.contextOk,a.sent_slices=p.sentSlices,p.timings&&(i.collect=p.timings.collect_ms,i.parallel=p.timings.parallel_ms);let f=u;!p.posted||f===null?a.outcome="not_posted":(a.outcome=f.outcome,a.attempts=f.attempts,f.status!==void 0&&(a.http_status=f.status),f.verdict&&(a.verdict=f.verdict))}}catch(l){a.outcome="error",a.error=(l instanceof Error?l.message:String(l)).slice(0,200)}let c=n();try{let l=await t.flush();a.flush=l===null?"unpaired":l.ok?`ok:${l.flushed}`:`failed:${l.error??"unknown"}`}catch(l){a.flush=`failed:${(l instanceof Error?l.message:String(l)).slice(0,80)}`}return i.flush=n()-c,i.total=n()-r,a}async function um(e,t,n,r={}){let o=r.now??Date.now,i=r.maxRounds??20,a=0;for(;a<i&&nm(e,t,o());){try{let c=p0(e,t);if(c===null)break;let l=Date.parse(c.queued_at),d=Number.isFinite(l)&&o()-l>a0?{ts:new Date(o()).toISOString(),bridge:H,session_id:c.session_id,outcome:"expired",ms:{queued:o()-l}}:await n(c);Eo(e,d),f0(e,t),a++}finally{rm(e,t)}if(!u0(e,t))break}return a}async function A0(e,t,n,r={}){let o=r.now??Date.now,i=0;for(let a of m0(e)){if(i>=E0)break;if(a===t)continue;let c=h0(e,a);c===null||o()-c<S0||await um(e,a,n,{...r,maxRounds:1})>0&&i++}return i}async function I0(e,t,n=Date.now){if(!nm(e,cm,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{rm(e,cm)}}function Zc(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,o)=>R0(e,t,r,o,n.contextMs),"fetchContext"),post:s((r,o)=>C0(e,t,r,o,n),"post"),flush:s(()=>I0(Bt,()=>Jc(n.flushMs)),"flush"),memoryAllowed:Ha()}}async function dK(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{Eo(Bt,{ts:new Date().toISOString(),bridge:H,session_id:t,outcome:"deadline",ms:{total:sm}}),process.exit(0)},sm);n.unref();try{let r=z();if(!r)return 0;let o=ae(),i=s(a=>Xc(a,Zc(r,o,x0)),"run");await um(Bt,t,i),await A0(Bt,t,i)}catch(r){Eo(Bt,{ts:new Date().toISOString(),bridge:H,session_id:t,outcome:"error",ms:{},error:(r instanceof Error?r.message:String(r)).slice(0,200)})}finally{clearTimeout(n)}return 0}var lm,x0,dm,sm,S0,E0,cm,pm=w(()=>{"use strict";rr();re();gn();Vf();Qi();pe();Fe();Ua();y0();v0();om();lm="session-end-run",x0={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},dm={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},sm=3*6e4,S0=2*6e4,E0=3;s(R0,"fetchCostContext");s(am,"postIngestOnce");s(C0,"postIngest");s(im,"git");s(T0,"gitResolvers");s(Xc,"processJob");s(um,"drainSession");s(A0,"sweepPending");cm="metrics-flush";s(I0,"flushUnderLock");s(Zc,"liveJobDeps");s(dK,"runSessionEndWorker")});var $0={};Z($0,{buildJob:()=>P0,enqueueAndSpawn:()=>M0,presenceLookup:()=>O0,runOnSessionEnd:()=>yK,transcriptToIngest:()=>D0});import{spawn as uK}from"node:child_process";import{existsSync as pK,unlinkSync as fK}from"node:fs";import{join as mK}from"node:path";function O0(e,t,n,r){let o=null,i={own_snapshot_age_ms:null,presence_usable:!1};try{if(i.presence_usable=e!==null&&!lf(process.env,Q()),e!==null){let a=br(gr(e),{hostPids:r,cwd:process.cwd()});if(a){let c=Date.parse(a.snap.written_at);i={...i,own_snapshot_age_ms:Number.isFinite(c)?Math.max(0,n-c):null}}o=n0(a?.snap,t)}}catch{i={own_snapshot_age_ms:null,presence_usable:!1},o=null}if(o===null){let a=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(a)&&(o=a)}return{coordSessionId:o,evidence:i}}function D0(e,t=process.env){let n=fo(e);return n&&!_n(Pi(e,t))?n:""}function P0(e,t){let n=typeof e.session_id=="string"&&e.session_id?e.session_id:null,r={v:1,session_id:n,transcript_path:t.transcriptPath,cwd:t.cwd,coord_session_id:null,project_key:null,presence:{own_snapshot_age_ms:null,presence_usable:!1},queued_at:new Date(t.nowMs).toISOString()};if(!t.transcriptPath)return r;let o=t.projectKey(),i=t.presence(o,Bi(t.transcriptPath,n),t.nowMs);return{...r,project_key:o,coord_session_id:i.coordSessionId,presence:i.evidence}}function M0(e,t={}){let n=t.dir??Bt,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let o=Qf(e.session_id);try{d0(n,e)}catch{return!1}try{return(t.spawnWorker??hK)(r,o,e.cwd),!0}catch{try{fK(mK(n,`${o}.job.json`))}catch{}return!1}}function hK(e,t,n){uK(process.execPath,[e,lm,t],{detached:!0,stdio:"ignore",cwd:pK(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function gK(e,t){try{let n=await Xc(e,Zc(t,ae(),dm));Eo(Bt,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
987
+ `)}}async function yK(){let e=[];try{e=lt()}catch{e=[]}try{for(let i of e)RS(_o(),i)}catch{}let t=z();if(!t)return 0;let n=await V(),r=typeof n.session_id=="string"&&n.session_id?n.session_id:null;await zc(r);let o;try{o=P0(n,{transcriptPath:D0(n),cwd:process.cwd(),nowMs:Date.now(),projectKey:ne,presence:s((i,a,c)=>O0(i,a,c,e),"presence")})}catch{return 0}return M0(o)||await gK(o,t),0}var L0=w(()=>{"use strict";Ue();re();jc();ke();$e();Qi();df();ji();pe();Nc();r0();om();pm();s(O0,"presenceLookup");s(D0,"transcriptToIngest");s(P0,"buildJob");s(M0,"enqueueAndSpawn");s(hK,"spawnDetachedWorker");s(gK,"runInline");s(yK,"runOnSessionEnd")});var F0={};Z(F0,{runOnSessionBriefing:()=>_K});async function _K(e=process.argv.slice(2)){try{return await gc("core",await V(),{hostHint:sx(e)})}catch{return 0}}var j0=w(()=>{"use strict";pr();ke();$e();s(_K,"runOnSessionBriefing")});var U0={};Z(U0,{deliverSessionReminder:()=>H0,runOnSessionReminder:()=>kK});import{readFile as bK}from"node:fs/promises";import{homedir as wK}from"node:os";import{join as vK}from"node:path";async function H0(e,t={}){let n=t.target??de(e);if(!xe(n,{kind:"text",event:"SessionStart"}))return 0;let r;try{r=await bK(vK(t.homeDir??wK(),gi),"utf8")}catch{return 0}if(r.length===0)return 0;let o=me(n,{kind:"text",event:"SessionStart",text:r});return o!==null&&await(t.write??lc)(o),0}async function kK(){try{return await H0(await V())}catch{return 0}}var B0=w(()=>{"use strict";ve();ke();$e();s(H0,"deliverSessionReminder");s(kK,"runOnSessionReminder")});var Y0={};Z(Y0,{CURSOR_BRIEFING_MARKER:()=>fm,CURSOR_DELIVERY_LOG:()=>K0,CURSOR_UNAVAILABLE_TEXT:()=>W0,appendDelivery:()=>z0,cursorProjectDir:()=>G0,deliverCursorSessionStart:()=>q0,formatCursorBriefing:()=>V0,runOnCursorSessionStart:()=>OK});import{appendFile as xK,mkdir as SK,readFile as EK,stat as RK,writeFile as CK}from"node:fs/promises";import{dirname as TK,join as AK}from"node:path";function G0(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let o=r.find(i=>typeof i=="string"&&i.length>0);if(o)return o}return null}function V0(e,t,n){let o=`${fm}${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 mc(o,n,e)}async function q0(e,t={}){let n=t.write??J0,r=t.env??process.env,o=(t.apiKey??z)();if(o===null)return await n(`{}
988
+ `),0;let i=G0(e,r),a=i===null?null:(t.projectKeyFor??yt)(i),c=await ho(a,o,{fetcher:s(p=>ar({...p,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=W0,d="none";else{let p=V0(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})+`
989
+ `),await z0(t.logFile??K0,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Ro(e.conversation_id)??Ro(e.session_id),transcript_path:Ro(e.transcript_path)??Ro(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Ro(e.cursor_version)??Ro(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function OK(){try{return await q0(await V())}catch{try{await J0(`{}
990
+ `)}catch{}return 0}}async function z0(e,t){try{if(await SK(TK(e),{recursive:!0,mode:448}),await xK(e,JSON.stringify(t)+`
991
+ `,{mode:384}),(await RK(e)).size>IK){let n=(await EK(e,"utf8")).split(`
992
+ `).filter(r=>r.trim().length>0);await CK(e,n.slice(-NK).join(`
990
993
  `)+`
991
- `,{mode:384})}}catch{}}function z0(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var fm,B0,TK,AK,Ro,G0,Y0=w(()=>{"use strict";re();pr();gn();mc();pe();ke();Be();fm="[maind] Cursor session briefing",B0=CK(Re,"cursor","deliveries.jsonl"),TK=512*1024,AK=2e3,Ro=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(K0,"cursorProjectDir");G0=`${fm} 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(W0,"formatCursorBriefing");s(V0,"deliverCursorSessionStart");s(IK,"runOnCursorSessionStart");s(q0,"appendDelivery");s(z0,"writeStdout")});function NK(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 o=e[++n];if(o!=="warn"&&o!=="block")return null;t.mode=o;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 X0(e,t,n=process.stdout){let r=NK(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
994
+ `,{mode:384})}}catch{}}function J0(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var fm,K0,IK,NK,Ro,W0,X0=w(()=>{"use strict";re();pr();gn();hc();pe();ke();Be();fm="[maind] Cursor session briefing",K0=AK(Re,"cursor","deliveries.jsonl"),IK=512*1024,NK=2e3,Ro=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(G0,"cursorProjectDir");W0=`${fm} 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(V0,"formatCursorBriefing");s(q0,"deliverCursorSessionStart");s(OK,"runOnCursorSessionStart");s(z0,"appendDelivery");s(J0,"writeStdout")});function DK(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 o=e[++n];if(o!=="warn"&&o!=="block")return null;t.mode=o;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 Z0(e,t,n=process.stdout){let r=DK(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
992
995
  `),1;let o={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},i=[];for(let l of Qr)i.push(await _i(o,l));for(let l of i)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
993
996
  `);let a=i.some(l=>l.detail==="user declined"),c=i.some(l=>l.status==="failed");return r.dryRun?(n.write(`
994
997
  [dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
@@ -999,9 +1002,9 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
999
1002
  check: maind-mcp-bridge guard status
1000
1003
  Takes effect for NEW Claude Code sessions (hooks are read at session start).
1001
1004
  `),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
1002
- `),c?1:0)}var Z0=w(()=>{"use strict";ve();Ca();vt();s(NK,"parseGuardInstallFlags");s(X0,"runGuardInstall")});import{existsSync as Q0}from"node:fs";import{appendFile as OK,mkdir as DK,readFile as PK}from"node:fs/promises";import{join as MK}from"node:path";function mm(e,t=Zc){return MK(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function Co(e,t=Zc){return Q0(mm(e,t))}async function kn(e,t,n=Zc){try{await DK(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await OK(mm(e,n),r+`
1003
- `,{mode:384})}catch{}}async function vr(e,t=Zc){try{let n=mm(e,t);if(!Q0(n))return[];let r=[];for(let o of(await PK(n,"utf8")).split(`
1004
- `))if(o.trim())try{let i=JSON.parse(o),a=i.t,c=i.k,l=i.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!$K.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var Zc,$K,ts=w(()=>{"use strict";at();Zc=Gp,$K=new Set(["fail","ok","nudge","skip","prompt"]);s(mm,"triggerLogPath");s(Co,"hasTriggerLog");s(kn,"appendTriggerEvent");s(vr,"loadTriggerEvents")});import{existsSync as LK}from"node:fs";import{mkdir as FK,readFile as jK,rename as HK,writeFile as UK}from"node:fs/promises";import{dirname as BK,join as KK}from"node:path";function ns(e=process.env){let t=z();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??Ni,keyFp:Gr(t)}}async function hm(e,t=Date.now(),n=Qc){try{if(!LK(n))return null;let r=JSON.parse(await jK(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let o=Date.parse(r.fetched_at);if(Number.isNaN(o))return null;let i=r.policy;return{policy:Hc([i?.difficulty,i?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-o<GK}}catch{return null}}async function VK(e,t,n,r){try{await FK(BK(r),{recursive:!0,mode:448});let o={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},i=`${r}.tmp`;await UK(i,JSON.stringify(o,null,2),{mode:384}),await HK(i,r)}catch{}}async function qK(){let e=z();if(e===null)return null;let t=null;try{t=ne()}catch{t=null}let n=await Lt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:zK(),projectKey:t,bridgeVersion:H,timeoutMs:WK});if(n===null)return null;try{return Hc(JSON.parse(n))}catch{return null}}async function To(e,t={}){let n=t.nowMs??Date.now(),r=t.file??Qc,o=t.identity===void 0?ns():t.identity;if(o===null)return Ji;let i=await hm(o,n,r);if(i?.fresh)return i.policy;if(e){let a=await(t.fetcher??qK)();if(a!==null)return await VK(o,a,n,r),a}return i?.policy??Ji}function zK(){try{return ae()}catch{return null}}var Qc,GK,WK,Ao=w(()=>{"use strict";xo();Dt();re();pe();Fe();gn();at();Qc=KK(Te,"trigger-policy.json"),GK=12*60*60*1e3,WK=3e3;s(ns,"currentIdentity");s(hm,"readCachedPolicy");s(VK,"writeCachedPolicy");s(qK,"fetchTriggerPolicy");s(To,"resolveTriggerPolicy");s(zK,"safeDeviceId")});var tR={};Z(tR,{runGuard:()=>QK});import{existsSync as JK,readFileSync as YK}from"node:fs";import{homedir as eR}from"node:os";import{join as XK}from"node:path";async function QK(e){let t=e[0],n=e.slice(1);switch(t){case"install":return X0(n,eR());case"status":return tG();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
1005
+ `),c?1:0)}var Q0=w(()=>{"use strict";ve();Ta();vt();s(DK,"parseGuardInstallFlags");s(Z0,"runGuardInstall")});import{existsSync as eR}from"node:fs";import{appendFile as PK,mkdir as MK,readFile as $K}from"node:fs/promises";import{join as LK}from"node:path";function mm(e,t=Qc){return LK(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function Co(e,t=Qc){return eR(mm(e,t))}async function kn(e,t,n=Qc){try{await MK(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await PK(mm(e,n),r+`
1006
+ `,{mode:384})}catch{}}async function vr(e,t=Qc){try{let n=mm(e,t);if(!eR(n))return[];let r=[];for(let o of(await $K(n,"utf8")).split(`
1007
+ `))if(o.trim())try{let i=JSON.parse(o),a=i.t,c=i.k,l=i.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!FK.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var Qc,FK,ts=w(()=>{"use strict";at();Qc=Gp,FK=new Set(["fail","ok","nudge","skip","prompt"]);s(mm,"triggerLogPath");s(Co,"hasTriggerLog");s(kn,"appendTriggerEvent");s(vr,"loadTriggerEvents")});import{existsSync as jK}from"node:fs";import{mkdir as HK,readFile as UK,rename as BK,writeFile as KK}from"node:fs/promises";import{dirname as GK,join as WK}from"node:path";function ns(e=process.env){let t=z();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??Ni,keyFp:Gr(t)}}async function hm(e,t=Date.now(),n=el){try{if(!jK(n))return null;let r=JSON.parse(await UK(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let o=Date.parse(r.fetched_at);if(Number.isNaN(o))return null;let i=r.policy;return{policy:Uc([i?.difficulty,i?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-o<VK}}catch{return null}}async function zK(e,t,n,r){try{await HK(GK(r),{recursive:!0,mode:448});let o={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},i=`${r}.tmp`;await KK(i,JSON.stringify(o,null,2),{mode:384}),await BK(i,r)}catch{}}async function JK(){let e=z();if(e===null)return null;let t=null;try{t=ne()}catch{t=null}let n=await Ft("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:YK(),projectKey:t,bridgeVersion:H,timeoutMs:qK});if(n===null)return null;try{return Uc(JSON.parse(n))}catch{return null}}async function To(e,t={}){let n=t.nowMs??Date.now(),r=t.file??el,o=t.identity===void 0?ns():t.identity;if(o===null)return Ji;let i=await hm(o,n,r);if(i?.fresh)return i.policy;if(e){let a=await(t.fetcher??JK)();if(a!==null)return await zK(o,a,n,r),a}return i?.policy??Ji}function YK(){try{return ae()}catch{return null}}var el,VK,qK,Ao=w(()=>{"use strict";xo();Pt();re();pe();Fe();gn();at();el=WK(Te,"trigger-policy.json"),VK=12*60*60*1e3,qK=3e3;s(ns,"currentIdentity");s(hm,"readCachedPolicy");s(zK,"writeCachedPolicy");s(JK,"fetchTriggerPolicy");s(To,"resolveTriggerPolicy");s(YK,"safeDeviceId")});var nR={};Z(nR,{runGuard:()=>tG});import{existsSync as XK,readFileSync as ZK}from"node:fs";import{homedir as tR}from"node:os";import{join as QK}from"node:path";async function tG(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Z0(n,tR());case"status":return rG();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
1005
1008
  `),1):(await dr({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
1006
1009
  `),0)}case"off":return await dr({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
1007
1010
  `),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>
@@ -1009,71 +1012,71 @@ Takes effect for NEW Claude Code sessions (hooks are read at session start).
1009
1012
  `),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>
1010
1013
  `),1):(await dr(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.
1011
1014
  `:`${t} trigger disabled on this machine (your convention prefs are unchanged).
1012
- `),0)}case"skip":return eG(n);default:return process.stdout.write(ZK),t===void 0||t==="--help"||t==="-h"?0:1}}async function eG(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]
1015
+ `),0)}case"skip":return nG(n);default:return process.stdout.write(eG),t===void 0||t==="--help"||t==="-h"?0:1}}async function nG(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]
1013
1016
  `),1;let o=n.trim().slice(0,500);if(r!=="consult")return await kn(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await te({event:"override",session_id:t,reason:o,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
1014
1017
  logged (auditable) in ${ur}
1015
- `),0;let i=await Ft(t);return await Le(t,{...i,override_reason:o}),await te({event:"override",session_id:t,reason:o,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
1018
+ `),0;let i=await jt(t);return await Le(t,{...i,override_reason:o}),await te({event:"override",session_id:t,reason:o,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
1016
1019
  logged (auditable) in ${ur}
1017
- `),0}async function tG(){let e=he(),t=XK(eR(),".claude","settings.json"),n=null;try{JK(t)&&(n=YK(t,"utf8"))}catch{}let r=Oe(n,{},Qr),o=await gx(),i=ns(),a=i?await hm(i):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:Mi(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:Qc},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:o,events_file:ur},null,2)+`
1020
+ `),0}async function rG(){let e=he(),t=QK(tR(),".claude","settings.json"),n=null;try{XK(t)&&(n=ZK(t,"utf8"))}catch{}let r=Oe(n,{},Qr),o=await yx(),i=ns(),a=i?await hm(i):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:Mi(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:el},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:o,events_file:ur},null,2)+`
1018
1021
  `);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(`
1019
1022
  [maind] guard hook wiring is incomplete:
1020
1023
  `);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
1021
- `);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 ZK,nR=w(()=>{"use strict";dc();ve();vt();Z0();jt();at();ts();Ao();ZK=["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(`
1022
- `);s(QK,"runGuard");s(eG,"runGuardSkip");s(tG,"runGuardStatus")});var iR={};Z(iR,{bashOutputOf:()=>rR,consultedAtOf:()=>el,outcomeFromHook:()=>oR,runGuardDifficulty:()=>rG});function rR(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(`
1023
- `):null,interrupted:t.interrupted===!0}}function oR(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",o=!r&&n==="Bash"?rR(e.tool_response):{output:null,interrupted:!1},i=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:o.output,isInterrupt:e.is_interrupt===!0||o.interrupted,isSubagent:typeof i=="string"&&i.length>0}}}function el(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 nG(e,t,n){if(!Co(e))return;let r=await vr(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let o=vo(r,null,n);await kn(e,{t:n,k:"ok",v:t});let i=o.chain;i!==null&&i.failures.length>=4&&!o.resolved&&i.lastVerb===t&&await te({event:"difficulty_resolved",session_id:e,detail:String(i.failures.length)})}async function rG(){try{let e=he();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await V();if(st(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=oR(t);if(r===null)return 0;let o=Mf(r.outcome);if(o===null)return 0;let i=Date.now();if(o.kind==="ok")return await nG(n,o.verb,i),0;await kn(n,{t:i,k:"fail",v:o.verb});let a=await vr(n),c=vo(a,el(await ee(),n),i);if(!Ff(c)||c.chain===null)return 0;let l=await To(!0);if(!e.difficulty||!ko(l.difficulty))return 0;await kn(n,{t:i,k:"nudge"});let d=Yi(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?ac(d):Oi(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await te({event:"difficulty_nudge",session_id:n,cwd:u,project_key:ne()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var gm=w(()=>{"use strict";xo();ke();$e();Di();Be();pe();vt();jt();ts();Ao();s(rR,"bashOutputOf");s(oR,"outcomeFromHook");s(el,"consultedAtOf");s(nG,"recordSuccess");s(rG,"runGuardDifficulty")});var lR={};Z(lR,{decideDifficultyGate:()=>cR,decideGate:()=>aR,runGuardGate:()=>sG});function aR(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:sR(n)}:(n.deny_count??0)>=tl?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. "+sR(n)}:{kind:"deny",reason:oG(e.sessionId,n)}}function sR(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 oG(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:
1024
+ `);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 eG,rR=w(()=>{"use strict";uc();ve();vt();Q0();Ht();at();ts();Ao();eG=["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(`
1025
+ `);s(tG,"runGuard");s(nG,"runGuardSkip");s(rG,"runGuardStatus")});var sR={};Z(sR,{bashOutputOf:()=>oR,consultedAtOf:()=>tl,outcomeFromHook:()=>iR,runGuardDifficulty:()=>iG});function oR(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(`
1026
+ `):null,interrupted:t.interrupted===!0}}function iR(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",o=!r&&n==="Bash"?oR(e.tool_response):{output:null,interrupted:!1},i=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:o.output,isInterrupt:e.is_interrupt===!0||o.interrupted,isSubagent:typeof i=="string"&&i.length>0}}}function tl(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 oG(e,t,n){if(!Co(e))return;let r=await vr(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let o=vo(r,null,n);await kn(e,{t:n,k:"ok",v:t});let i=o.chain;i!==null&&i.failures.length>=4&&!o.resolved&&i.lastVerb===t&&await te({event:"difficulty_resolved",session_id:e,detail:String(i.failures.length)})}async function iG(){try{let e=he();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await V();if(st(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=iR(t);if(r===null)return 0;let o=Mf(r.outcome);if(o===null)return 0;let i=Date.now();if(o.kind==="ok")return await oG(n,o.verb,i),0;await kn(n,{t:i,k:"fail",v:o.verb});let a=await vr(n),c=vo(a,tl(await ee(),n),i);if(!Ff(c)||c.chain===null)return 0;let l=await To(!0);if(!e.difficulty||!ko(l.difficulty))return 0;await kn(n,{t:i,k:"nudge"});let d=Yi(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?cc(d):Oi(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await te({event:"difficulty_nudge",session_id:n,cwd:u,project_key:ne()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var gm=w(()=>{"use strict";xo();ke();$e();Di();Be();pe();vt();Ht();ts();Ao();s(oR,"bashOutputOf");s(iR,"outcomeFromHook");s(tl,"consultedAtOf");s(oG,"recordSuccess");s(iG,"runGuardDifficulty")});var dR={};Z(dR,{decideDifficultyGate:()=>lR,decideGate:()=>cR,runGuardGate:()=>cG});function cR(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:aR(n)}:(n.deny_count??0)>=nl?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. "+aR(n)}:{kind:"deny",reason:sG(e.sessionId,n)}}function aR(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 sG(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:
1024
1027
  1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
1025
1028
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
1026
- After ${tl} denies this gate downgrades itself to warn.`}function cR(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)>=tl?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. "+Yi(n.chain)}:{kind:"deny",reason:iG(n,e.sessionId)}}function iG(e,t){return`[maind guard | block] Edit denied \u2014 ${Kf(e.chain)}. Two exits:
1029
+ After ${nl} denies this gate downgrades itself to warn.`}function lR(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)>=nl?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. "+Yi(n.chain)}:{kind:"deny",reason:aG(n,e.sessionId)}}function aG(e,t){return`[maind guard | block] Edit denied \u2014 ${Kf(e.chain)}. Two exits:
1027
1030
  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.
1028
1031
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
1029
- After ${tl} denies this gate downgrades itself to warn.`}async function sG(){try{let e=he();if(e.mode==="off")return 0;let t=await V();if(st(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 o=await Ft(r),i=el(await ee(),r),a=i!==null,c=aR({mode:e.mode,session:o,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=ne()??void 0;if(c.kind==="deny")return process.stdout.write(cr(c.reason)),await Le(r,{...o,deny_count:(o.deny_count??0)+1}),await te({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(lr(c.context)),await Le(r,{...o,warned:!0,edits_seen:(o.edits_seen??0)+1}),await te({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&Co(r)){let u=vo(await vr(r),i,Date.now()),p=u.open?cR({mode:e.mode,enabled:e.difficulty,denyCapable:Uf((await To(!1)).difficulty),status:u,session:o,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(cr(p.reason)),await Le(r,{...o,difficulty_deny_count:(o.difficulty_deny_count??0)+1}),await te({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(lr(p.context)),await Le(r,{...o,difficulty_breaker_warned:!0,edits_seen:(o.edits_seen??0)+1}),0}return await Le(r,{...o,edits_seen:(o.edits_seen??0)+1}),0}catch{return 0}}var tl,dR=w(()=>{"use strict";xo();ke();$e();Di();Be();pe();vt();gm();jt();at();ts();Ao();tl=3;s(aR,"decideGate");s(sR,"warnText");s(oG,"denyText");s(cR,"decideDifficultyGate");s(iG,"difficultyDenyText");s(sG,"runGuardGate")});var pR={};Z(pR,{decideStopGate:()=>uR,runGuardStop:()=>cG});function uR(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function cG(){try{let e=he();if(e.mode==="off"||!e.stopGate)return 0;let t=await V();if(st(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 Ft(n),o=(await ee()).guard_signals?.[n]?.reviewed_at!==void 0;return uR({enabled:!0,editsSeen:r.edits_seen??0,reviewed:o,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:aG})),await Le(n,{...r,stop_blocked:!0}),await te({event:"stop_block",session_id:n})),0}catch{return 0}}var aG,fR=w(()=>{"use strict";ke();$e();Be();vt();jt();at();s(uR,"decideStopGate");aG="[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(cG,"runGuardStop")});var gR={};Z(gR,{capturedAtOf:()=>mR,decideCapture:()=>hR,runGuardCapture:()=>lG});function mR(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 hR(e){if(e.stopHookActive||!ko(e.policy.capture))return null;let t=jf(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Gf(t)}}async function lG(){try{let e=he();if(e.mode==="off"||!e.capture)return 0;let t=await V();if(st(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!Co(n))return 0;let r=hR({events:await vr(n),capturedAtMs:mR(await ee(),n),policy:await To(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await kn(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await te({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var yR=w(()=>{"use strict";xo();ke();$e();Be();vt();jt();ts();Ao();s(mR,"capturedAtOf");s(hR,"decideCapture");s(lG,"runGuardCapture")});import{appendFile as dG,mkdir as uG,readFile as bR,rename as wR,writeFile as vR}from"node:fs/promises";import{homedir as kR}from"node:os";import{join as xR}from"node:path";function SR(e,t,n,r){if(t==="off"||e.length===0)return null;let o={},i=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=o[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=i.get(d.convention_id);(p===void 0||d.convention_version>p)&&i.set(d.convention_id,d.convention_version)}}let l=Object.entries(o).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:[...i.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function kr(){return xR(kR(),".maind","gateway","attest-spool.jsonl")}async function ym(e){let t=z();if(t===null)return!1;let n=await Lt("gateway_attest",{...e},{apiKey:t,deviceId:ae(),projectKey:e.project_key??null,bridgeVersion:H,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function ER(e){try{await uG(xR(kR(),".maind","gateway"),{recursive:!0}),await dG(kr(),JSON.stringify(e)+`
1030
- `,{mode:384}),await pG()}catch{}}async function pG(){try{let t=(await bR(kr(),"utf8")).split(`
1031
- `).filter(r=>r.trim());if(t.length<=_R)return;let n=`${kr()}.${process.pid}.tmp`;await vR(n,t.slice(-_R).join(`
1032
+ After ${nl} denies this gate downgrades itself to warn.`}async function cG(){try{let e=he();if(e.mode==="off")return 0;let t=await V();if(st(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 o=await jt(r),i=tl(await ee(),r),a=i!==null,c=cR({mode:e.mode,session:o,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=ne()??void 0;if(c.kind==="deny")return process.stdout.write(cr(c.reason)),await Le(r,{...o,deny_count:(o.deny_count??0)+1}),await te({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(lr(c.context)),await Le(r,{...o,warned:!0,edits_seen:(o.edits_seen??0)+1}),await te({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&Co(r)){let u=vo(await vr(r),i,Date.now()),p=u.open?lR({mode:e.mode,enabled:e.difficulty,denyCapable:Uf((await To(!1)).difficulty),status:u,session:o,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(cr(p.reason)),await Le(r,{...o,difficulty_deny_count:(o.difficulty_deny_count??0)+1}),await te({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(lr(p.context)),await Le(r,{...o,difficulty_breaker_warned:!0,edits_seen:(o.edits_seen??0)+1}),0}return await Le(r,{...o,edits_seen:(o.edits_seen??0)+1}),0}catch{return 0}}var nl,uR=w(()=>{"use strict";xo();ke();$e();Di();Be();pe();vt();gm();Ht();at();ts();Ao();nl=3;s(cR,"decideGate");s(aR,"warnText");s(sG,"denyText");s(lR,"decideDifficultyGate");s(aG,"difficultyDenyText");s(cG,"runGuardGate")});var fR={};Z(fR,{decideStopGate:()=>pR,runGuardStop:()=>dG});function pR(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function dG(){try{let e=he();if(e.mode==="off"||!e.stopGate)return 0;let t=await V();if(st(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 jt(n),o=(await ee()).guard_signals?.[n]?.reviewed_at!==void 0;return pR({enabled:!0,editsSeen:r.edits_seen??0,reviewed:o,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:lG})),await Le(n,{...r,stop_blocked:!0}),await te({event:"stop_block",session_id:n})),0}catch{return 0}}var lG,mR=w(()=>{"use strict";ke();$e();Be();vt();Ht();at();s(pR,"decideStopGate");lG="[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(dG,"runGuardStop")});var yR={};Z(yR,{capturedAtOf:()=>hR,decideCapture:()=>gR,runGuardCapture:()=>uG});function hR(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 gR(e){if(e.stopHookActive||!ko(e.policy.capture))return null;let t=jf(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Gf(t)}}async function uG(){try{let e=he();if(e.mode==="off"||!e.capture)return 0;let t=await V();if(st(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!Co(n))return 0;let r=gR({events:await vr(n),capturedAtMs:hR(await ee(),n),policy:await To(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await kn(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await te({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var _R=w(()=>{"use strict";xo();ke();$e();Be();vt();Ht();ts();Ao();s(hR,"capturedAtOf");s(gR,"decideCapture");s(uG,"runGuardCapture")});import{appendFile as pG,mkdir as fG,readFile as wR,rename as vR,writeFile as kR}from"node:fs/promises";import{homedir as xR}from"node:os";import{join as SR}from"node:path";function ER(e,t,n,r){if(t==="off"||e.length===0)return null;let o={},i=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=o[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=i.get(d.convention_id);(p===void 0||d.convention_version>p)&&i.set(d.convention_id,d.convention_version)}}let l=Object.entries(o).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:[...i.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function kr(){return SR(xR(),".maind","gateway","attest-spool.jsonl")}async function ym(e){let t=z();if(t===null)return!1;let n=await Ft("gateway_attest",{...e},{apiKey:t,deviceId:ae(),projectKey:e.project_key??null,bridgeVersion:H,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function RR(e){try{await fG(SR(xR(),".maind","gateway"),{recursive:!0}),await pG(kr(),JSON.stringify(e)+`
1033
+ `,{mode:384}),await mG()}catch{}}async function mG(){try{let t=(await wR(kr(),"utf8")).split(`
1034
+ `).filter(r=>r.trim());if(t.length<=bR)return;let n=`${kr()}.${process.pid}.tmp`;await kR(n,t.slice(-bR).join(`
1032
1035
  `)+`
1033
- `,{mode:384}),await wR(n,kr())}catch{}}async function RR(){let e;try{e=(await bR(kr(),"utf8")).split(`
1034
- `).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 o=null;try{o=JSON.parse(r)}catch{continue}await ym(o)||(n=!0,t.push(r))}try{let r=`${kr()}.${process.pid}.tmp`;await vR(r,t.length>0?t.join(`
1036
+ `,{mode:384}),await vR(n,kr())}catch{}}async function CR(){let e;try{e=(await wR(kr(),"utf8")).split(`
1037
+ `).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 o=null;try{o=JSON.parse(r)}catch{continue}await ym(o)||(n=!0,t.push(r))}try{let r=`${kr()}.${process.pid}.tmp`;await kR(r,t.length>0?t.join(`
1035
1038
  `)+`
1036
- `:"",{mode:384}),await wR(r,kr())}catch{}}var _R,CR=w(()=>{"use strict";re();gn();Fe();_R=256;s(SR,"aggregateWindow");s(kr,"attestSpoolPath");s(ym,"postAttestation");s(ER,"spoolAttestation");s(pG,"capSpool");s(RR,"flushAttestSpool")});function rs(e=process.env,t=Q()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function nl(e=process.env,t=Q()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function TR(e,t=He()){let n={};try{let o=await q(t);if(o!==null&&o.trim().length>0){let i=JSON.parse(o);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await U(t,JSON.stringify(r,null,2)+`
1037
- `,384)}async function AR(e,t=He()){await TR({gateway_mode:e},t)}async function IR(e,t=He()){await TR({gateway_attest:e},t)}function NR(e=process.env,t=Q()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var _m=w(()=>{"use strict";Ue();ie();s(rs,"resolveGatewayMode");s(nl,"resolveGatewayAttest");s(TR,"writeGatewayConfigPatch");s(AR,"writeGatewayMode");s(IR,"writeGatewayAttest");s(NR,"resolveShaProofMode")});function DR(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 o=r,i=o.gateway_gate;if(typeof i!="object"||i===null)continue;let a=i;if(a.enabled!==!0)continue;let c=typeof o.id=="string"&&o.id.length>0&&o.id.length<=64?o.id:null,l=typeof o.version=="number"&&Number.isInteger(o.version)&&o.version>=1?o.version:null;if(c===null||l===null)continue;let d=typeof o.severity=="string"&&fG.has(o.severity)?o.severity:"recommended",u=typeof o.summary=="string"?o.summary:"",p=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of f){if(n.length>=256)return n;n.push({tool:h,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function mG(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function PR(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)mG(i,e,t)&&(o===null||OR[i.severity]>OR[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function MR(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 fG,OR,bm=w(()=>{"use strict";fG=new Set(["required","recommended","info"]);s(DR,"extractGatewayRules");OR={required:2,recommended:1,info:0};s(mG,"ruleMatches");s(PR,"decideToolCall");s(MR,"policyDenyText")});import{mkdirSync as hG,readFileSync as gG,renameSync as yG,writeFileSync as _G}from"node:fs";import{homedir as bG}from"node:os";import{dirname as wG,join as vG}from"node:path";function $R(){return vG(bG(),".maind","gateway","policy-cache.json")}function rl(e,t,n=new Date().toISOString()){try{let r={version:wm,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=$R();hG(wG(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;_G(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),yG(i,o)}catch{}}function ol(e){try{let t=gG($R(),"utf8"),n=JSON.parse(t);return n.version!==wm||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:wm,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var wm,vm=w(()=>{"use strict";wm=1;s($R,"policyCachePath");s(rl,"writePolicyCache");s(ol,"readPolicyCache")});function os(e=process.env){let t=e.MAIND_MCP_URL??Ni,n=z();return{mcpUrl:t,keyFp:n?Gr(n):"anon"}}async function il(e=6e3){let t=z();if(t===null)return null;let n=null;try{n=ne()}catch{n=null}let r=await Lt("get_conventions",{},{apiKey:t,deviceId:ae(),projectKey:n,bridgeVersion:H,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return DR(o)}var km=w(()=>{"use strict";Dt();re();gn();pe();Fe();bm();s(os,"policyIdentity");s(il,"fetchGatewayRules")});function is(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 kG(e){if(is(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 xG(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:is(e)?{action:"skip",reason:"already-wrapped"}:kG(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function LR(e,t,n){let r=String(e.command),o=Array.isArray(e.args)?e.args.map(String):[],i=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=i||t.env?{...i??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...o]};return a&&(c.env=a),c}function FR(e){if(!is(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 jR(e){return Object.entries(e).map(([t,n])=>{let r=xG(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var HR=w(()=>{"use strict";s(is,"isGatewayWrapped");s(kG,"isMaindProxyEntry");s(xG,"classifyServer");s(LR,"wrapServerEntry");s(FR,"unwrapServerEntry");s(jR,"planRewrites")});var VR={};Z(VR,{runGatewayInstall:()=>AG,runGatewayUninstall:()=>IG});import{existsSync as SG,readFileSync as EG}from"node:fs";import{homedir as RG}from"node:os";import{join as UR}from"node:path";import{createInterface as CG}from"node:readline";function BR(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 KR(){return[{label:"Claude Code (project .mcp.json)",path:UR(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:UR(RG(),".claude.json")}]}async function GR(e){let t=CG({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 WR(e){let t=TG(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,o=r.mcpServers;return typeof o!="object"||o===null||Array.isArray(o)?null:{raw:r,servers:o}}catch{return null}}function TG(e){try{return SG(e)?EG(e,"utf8"):null}catch{return null}}async function AG(e){let t=BR(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1038
- `),2;let n=we({entryPath:oe(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let o of KR()){let i=WR(o.path);if(i===null){process.stderr.write(` skipped ${o.label} \u2014 no mcpServers object
1039
- `);continue}let a=jR(i.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${o.label} \xB7 ${c.key} \u2014 ${c.reason}
1040
- `);continue}if(!(t.yes||await GR(`Wrap MCP server '${c.key}' in ${o.label} with the maind gateway?
1039
+ `:"",{mode:384}),await vR(r,kr())}catch{}}var bR,TR=w(()=>{"use strict";re();gn();Fe();bR=256;s(ER,"aggregateWindow");s(kr,"attestSpoolPath");s(ym,"postAttestation");s(RR,"spoolAttestation");s(mG,"capSpool");s(CR,"flushAttestSpool")});function rs(e=process.env,t=Q()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function rl(e=process.env,t=Q()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function AR(e,t=He()){let n={};try{let o=await q(t);if(o!==null&&o.trim().length>0){let i=JSON.parse(o);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await U(t,JSON.stringify(r,null,2)+`
1040
+ `,384)}async function IR(e,t=He()){await AR({gateway_mode:e},t)}async function NR(e,t=He()){await AR({gateway_attest:e},t)}function OR(e=process.env,t=Q()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var _m=w(()=>{"use strict";Ue();ie();s(rs,"resolveGatewayMode");s(rl,"resolveGatewayAttest");s(AR,"writeGatewayConfigPatch");s(IR,"writeGatewayMode");s(NR,"writeGatewayAttest");s(OR,"resolveShaProofMode")});function PR(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 o=r,i=o.gateway_gate;if(typeof i!="object"||i===null)continue;let a=i;if(a.enabled!==!0)continue;let c=typeof o.id=="string"&&o.id.length>0&&o.id.length<=64?o.id:null,l=typeof o.version=="number"&&Number.isInteger(o.version)&&o.version>=1?o.version:null;if(c===null||l===null)continue;let d=typeof o.severity=="string"&&hG.has(o.severity)?o.severity:"recommended",u=typeof o.summary=="string"?o.summary:"",p=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of f){if(n.length>=256)return n;n.push({tool:h,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function gG(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function MR(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)gG(i,e,t)&&(o===null||DR[i.severity]>DR[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function $R(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 hG,DR,bm=w(()=>{"use strict";hG=new Set(["required","recommended","info"]);s(PR,"extractGatewayRules");DR={required:2,recommended:1,info:0};s(gG,"ruleMatches");s(MR,"decideToolCall");s($R,"policyDenyText")});import{mkdirSync as yG,readFileSync as _G,renameSync as bG,writeFileSync as wG}from"node:fs";import{homedir as vG}from"node:os";import{dirname as kG,join as xG}from"node:path";function LR(){return xG(vG(),".maind","gateway","policy-cache.json")}function ol(e,t,n=new Date().toISOString()){try{let r={version:wm,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=LR();yG(kG(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;wG(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),bG(i,o)}catch{}}function il(e){try{let t=_G(LR(),"utf8"),n=JSON.parse(t);return n.version!==wm||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:wm,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var wm,vm=w(()=>{"use strict";wm=1;s(LR,"policyCachePath");s(ol,"writePolicyCache");s(il,"readPolicyCache")});function os(e=process.env){let t=e.MAIND_MCP_URL??Ni,n=z();return{mcpUrl:t,keyFp:n?Gr(n):"anon"}}async function sl(e=6e3){let t=z();if(t===null)return null;let n=null;try{n=ne()}catch{n=null}let r=await Ft("get_conventions",{},{apiKey:t,deviceId:ae(),projectKey:n,bridgeVersion:H,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return PR(o)}var km=w(()=>{"use strict";Pt();re();gn();pe();Fe();bm();s(os,"policyIdentity");s(sl,"fetchGatewayRules")});function is(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 SG(e){if(is(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 EG(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:is(e)?{action:"skip",reason:"already-wrapped"}:SG(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function FR(e,t,n){let r=String(e.command),o=Array.isArray(e.args)?e.args.map(String):[],i=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=i||t.env?{...i??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...o]};return a&&(c.env=a),c}function jR(e){if(!is(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 HR(e){return Object.entries(e).map(([t,n])=>{let r=EG(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var UR=w(()=>{"use strict";s(is,"isGatewayWrapped");s(SG,"isMaindProxyEntry");s(EG,"classifyServer");s(FR,"wrapServerEntry");s(jR,"unwrapServerEntry");s(HR,"planRewrites")});var qR={};Z(qR,{runGatewayInstall:()=>NG,runGatewayUninstall:()=>OG});import{existsSync as RG,readFileSync as CG}from"node:fs";import{homedir as TG}from"node:os";import{join as BR}from"node:path";import{createInterface as AG}from"node:readline";function KR(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 GR(){return[{label:"Claude Code (project .mcp.json)",path:BR(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:BR(TG(),".claude.json")}]}async function WR(e){let t=AG({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 VR(e){let t=IG(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,o=r.mcpServers;return typeof o!="object"||o===null||Array.isArray(o)?null:{raw:r,servers:o}}catch{return null}}function IG(e){try{return RG(e)?CG(e,"utf8"):null}catch{return null}}async function NG(e){let t=KR(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1041
+ `),2;let n=we({entryPath:oe(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let o of GR()){let i=VR(o.path);if(i===null){process.stderr.write(` skipped ${o.label} \u2014 no mcpServers object
1042
+ `);continue}let a=HR(i.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${o.label} \xB7 ${c.key} \u2014 ${c.reason}
1043
+ `);continue}if(!(t.yes||await WR(`Wrap MCP server '${c.key}' in ${o.label} with the maind gateway?
1041
1044
  Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
1042
1045
  The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${o.label} \xB7 ${c.key}
1043
- `);continue}i.servers[c.key]=LR(i.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${o.label} \xB7 ${c.key}
1046
+ `);continue}i.servers[c.key]=FR(i.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${o.label} \xB7 ${c.key}
1044
1047
  `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await U(o.path,JSON.stringify(i.raw,null,2)+`
1045
1048
  `,384)}return process.stderr.write(r>0?`
1046
1049
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
1047
1050
  `:`
1048
1051
  Nothing to wrap.
1049
- `),0}async function IG(e){let t=BR(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1050
- `),2;let n=0;for(let r of KR()){let o=WR(r.path);if(o===null)continue;let i=!1;for(let[a,c]of Object.entries(o.servers)){if(!is(c)||!(t.yes||await GR(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=FR(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
1052
+ `),0}async function OG(e){let t=KR(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1053
+ `),2;let n=0;for(let r of GR()){let o=VR(r.path);if(o===null)continue;let i=!1;for(let[a,c]of Object.entries(o.servers)){if(!is(c)||!(t.yes||await WR(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=jR(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
1051
1054
  `);continue}o.servers[a]=d,i=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
1052
1055
  `)}!t.dryRun&&i&&await U(r.path,JSON.stringify(o.raw,null,2)+`
1053
1056
  `,384)}return process.stderr.write(n>0?`
1054
1057
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
1055
1058
  `:`
1056
1059
  Nothing wrapped \u2014 nothing to restore.
1057
- `),0}var qR=w(()=>{"use strict";ie();_t();HR();s(BR,"parseFlags");s(KR,"targets");s(GR,"confirm");s(WR,"loadConfig");s(TG,"readFileSafeSync");s(AG,"runGatewayInstall");s(IG,"runGatewayUninstall")});var zR={};Z(zR,{runGatewayAttest:()=>OG,runGatewayMode:()=>NG,runGatewayPolicy:()=>MG});async function NG(e){let t=e[0];if(t===void 0){let n=rs(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1060
+ `),0}var zR=w(()=>{"use strict";ie();_t();UR();s(KR,"parseFlags");s(GR,"targets");s(WR,"confirm");s(VR,"loadConfig");s(IG,"readFileSafeSync");s(NG,"runGatewayInstall");s(OG,"runGatewayUninstall")});var JR={};Z(JR,{runGatewayAttest:()=>PG,runGatewayMode:()=>DG,runGatewayPolicy:()=>LG});async function DG(e){let t=e[0];if(t===void 0){let n=rs(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1058
1061
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
1059
- `),2):(await AR(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
1062
+ `),2):(await IR(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
1060
1063
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
1061
1064
  `:`Convention policy is off; only explicit --deny-tool flags apply.
1062
- `)),0)}async function OG(e){let t=e[0];if(t===void 0){let n=nl(),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)":""}.
1065
+ `)),0)}async function PG(e){let t=e[0];if(t===void 0){let n=rl(),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)":""}.
1063
1066
  `+(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.
1064
1067
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
1065
- `),2):(await IR(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.
1068
+ `),2):(await NR(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.
1066
1069
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
1067
- `),0)}function DG(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1070
+ `),0)}function MG(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1068
1071
  `;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),o=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${o})
1069
- `}return t}function PG(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 o=Math.floor(r/60);return o<24?`${o} h ago`:`${Math.floor(o/24)} d ago`}async function MG(e){let t=e.includes("--refresh"),n=rs(),r=os();if(t){let i=await il();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1070
- `):(rl(r,i),process.stdout.write(`maind: policy refreshed (${i.length} rule(s)).
1071
- `))}let o=ol(r);return process.stdout.write(`maind: gateway mode '${n}'
1072
+ `}return t}function $G(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 o=Math.floor(r/60);return o<24?`${o} h ago`:`${Math.floor(o/24)} d ago`}async function LG(e){let t=e.includes("--refresh"),n=rs(),r=os();if(t){let i=await sl();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1073
+ `):(ol(r,i),process.stdout.write(`maind: policy refreshed (${i.length} rule(s)).
1074
+ `))}let o=il(r);return process.stdout.write(`maind: gateway mode '${n}'
1072
1075
  `),o===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
1073
- `),0):(process.stdout.write(`maind: policy from cache (${PG(o)}, ${r.mcpUrl}):
1074
- `),process.stdout.write(DG(o.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
1075
- `),0)}var JR=w(()=>{"use strict";_m();vm();km();s(NG,"runGatewayMode");s(OG,"runGatewayAttest");s(DG,"renderRules");s(PG,"cacheAge");s(MG,"runGatewayPolicy")});var eC={};Z(eC,{gatewayEventsFile:()=>ZR,parseGatewayArgs:()=>QR,runGateway:()=>KG});import{spawn as $G}from"node:child_process";import{appendFile as LG,mkdir as FG}from"node:fs/promises";import{homedir as YR}from"node:os";import{basename as jG,join as XR}from"node:path";import{createInterface as HG}from"node:readline";function ZR(){return XR(YR(),".maind","gateway","events.jsonl")}async function BG(e){try{let t=ZR();await FG(XR(YR(),".maind","gateway"),{recursive:!0}),await LG(t,JSON.stringify(e)+`
1076
- `,{mode:384})}catch{}}function QR(e){let t=new Set,n=null,r=0;for(;r<e.length;){let o=e[r];if(o==="--deny-tool"){let i=e[r+1];if(!i)return null;t.add(i),r+=2;continue}if(o==="--label"){let i=e[r+1];if(!i)return null;n=i,r+=2;continue}if(o==="--"){let i=e[r+1];return i?{denyTools:t,label:n,command:i,args:e.slice(r+2)}:null}return null}return null}async function KG(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:R}=await Promise.resolve().then(()=>(qR(),VR));return e[0]==="install"?S(e.slice(1)):R(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:S,runGatewayMode:R,runGatewayPolicy:P}=await Promise.resolve().then(()=>(JR(),zR));return e[0]==="mode"?R(e.slice(1)):e[0]==="attest"?S(e.slice(1)):P(e.slice(1))}let t=QR(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1076
+ `),0):(process.stdout.write(`maind: policy from cache (${$G(o)}, ${r.mcpUrl}):
1077
+ `),process.stdout.write(MG(o.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
1078
+ `),0)}var YR=w(()=>{"use strict";_m();vm();km();s(DG,"runGatewayMode");s(PG,"runGatewayAttest");s(MG,"renderRules");s($G,"cacheAge");s(LG,"runGatewayPolicy")});var tC={};Z(tC,{gatewayEventsFile:()=>QR,parseGatewayArgs:()=>eC,runGateway:()=>WG});import{spawn as FG}from"node:child_process";import{appendFile as jG,mkdir as HG}from"node:fs/promises";import{homedir as XR}from"node:os";import{basename as UG,join as ZR}from"node:path";import{createInterface as BG}from"node:readline";function QR(){return ZR(XR(),".maind","gateway","events.jsonl")}async function GG(e){try{let t=QR();await HG(ZR(XR(),".maind","gateway"),{recursive:!0}),await jG(t,JSON.stringify(e)+`
1079
+ `,{mode:384})}catch{}}function eC(e){let t=new Set,n=null,r=0;for(;r<e.length;){let o=e[r];if(o==="--deny-tool"){let i=e[r+1];if(!i)return null;t.add(i),r+=2;continue}if(o==="--label"){let i=e[r+1];if(!i)return null;n=i,r+=2;continue}if(o==="--"){let i=e[r+1];return i?{denyTools:t,label:n,command:i,args:e.slice(r+2)}:null}return null}return null}async function WG(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:R}=await Promise.resolve().then(()=>(zR(),qR));return e[0]==="install"?S(e.slice(1)):R(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:S,runGatewayMode:R,runGatewayPolicy:P}=await Promise.resolve().then(()=>(YR(),JR));return e[0]==="mode"?R(e.slice(1)):e[0]==="attest"?S(e.slice(1)):P(e.slice(1))}let t=eC(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1077
1080
  maind-mcp-bridge gateway install [--yes] [--dry-run]
1078
1081
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1079
1082
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -1083,50 +1086,50 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
1083
1086
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
1084
1087
  install/uninstall rewrite Claude Code MCP configs (consent per server).
1085
1088
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
1086
- `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??jG(o),c=rs(),l=NR(),d=l==="off"?null:fs(),u=c==="off"?[]:ol(os())?.rules??[];c!=="off"&&il().then(S=>{S!==null&&(u=S,rl(os(),S))}).catch(()=>{});let p=[],f=nl()&&z()!==null&&c!=="off",h=null;try{h=ne()}catch{h=null}let g=Promise.resolve(),y=s(S=>{g=g.then(()=>BG(S)),f&&p.push(S)},"record"),_=s(async()=>{if(!f)return;let S=SR(p.splice(0),c,a,h);S!==null&&(await ym(S)||await ER(S))},"attestAndReset");f&&RR().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let v=$G(o,i,{stdio:["pipe","pipe","inherit"]});v.stdout.pipe(process.stdout),v.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(S)}
1087
- `),process.exitCode=1});let k=HG({input:process.stdin,terminal:!1});k.on("line",S=>{let R=zm(S);if(R.kind==="request"&&R.method==="tools/call"&&R.toolName){if(n.has(R.toolName)&&R.id!==void 0){process.stdout.write(xr(R.id,R.toolName)+`
1088
- `),y(fl("deny",a,R.toolName,Date.now()));return}let P=PR(R.toolName,a,u,c);if(P.kind==="deny"&&R.id!==void 0){process.stdout.write(xr(R.id,R.toolName,MR(R.toolName,P.rule))+`
1089
- `),y(ml("policy_deny",a,R.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));return}(P.kind==="warn"||P.kind==="deny")&&y(ml("policy_warn",a,R.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));let K=ms(S,d);if(K.length>0){let x=K.find(F=>F.verdict==="fabricated");if(x!==void 0&&l==="enforce"&&c==="enforce"&&R.id!==void 0&&x!==void 0&&R.id!==void 0){process.stdout.write(xr(R.id,R.toolName,Sr(x,!0))+`
1090
- `),y(hl("sha_deny",a,R.toolName,Date.now()));return}let D=x??K[0];process.stderr.write(`[maind gateway] ${Sr(D,!1)}
1091
- `),y(hl("sha_warn",a,R.toolName,Date.now()))}y(fl("tool_call",a,R.toolName,Date.now()))}v.stdin.write(S+`
1092
- `)}),k.on("close",()=>{v.stdin.end()});let E=await new Promise(S=>{v.on("exit",(R,P)=>{S(R??(P?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(S=>setTimeout(S,UG).unref())]),await _(),E}var UG,tC=w(()=>{"use strict";gl();CR();_m();bm();yl();vm();km();re();pe();s(ZR,"gatewayEventsFile");UG=5e3;s(BG,"logEvent");s(QR,"parseGatewayArgs");s(KG,"runGateway")});var Am={};Z(Am,{MAX_ENTRIES:()=>xm,TTL_MS:()=>Rm,crossSessionDir:()=>Cm,decideCrossSession:()=>oC,parseSessionDb:()=>rC,pruneDb:()=>Tm,runGuardCrossCheck:()=>ZG,runGuardCrossObserve:()=>XG,staleReason:()=>Sm});import{mkdir as GG,readFile as WG,readdir as VG,stat as nC,unlink as qG,writeFile as zG}from"node:fs/promises";import{homedir as JG}from"node:os";import{join as Em}from"node:path";function Cm(){return Em(JG(),".maind","cross-session")}function rC(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[i,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[i]={m:c.m,t:c.t})}let o={};if(typeof n.warned=="object"&&n.warned!==null)for(let[i,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(o[i]=a);return{files:r,warned:o}}function Tm(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Rm);return n.length>xm&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-xm)),{files:Object.fromEntries(n),warned:e.warned}}function oC(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Sm(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 iC(e){let t=Cm();return await GG(t,{recursive:!0}),Em(t,`${e}.json`)}async function sC(e,t){try{let n=await WG(await iC(e),"utf8");return Tm(rC(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function aC(e,t){try{await zG(await iC(e),JSON.stringify(t),{mode:384})}catch{}}async function YG(e){try{let t=Cm();for(let n of await VG(t)){if(!n.endsWith(".json"))continue;let r=Em(t,n),o=await nC(r).catch(()=>null);o&&e-o.mtimeMs>Rm&&await qG(r).catch(()=>{})}}catch{}}async function cC(e){try{return(await nC(e)).mtimeMs}catch{return}}async function XG(e,t=Date.now()){try{if(he().mode==="off")return 0;let r=e??await V();if(st(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=Ze(r);if(!o||!i)return 0;let a=await cC(i);if(a===void 0)return 0;let c=await sC(o,t);return c.files[i]={m:a,t},delete c.warned[i],await aC(o,Tm(c,t)),await YG(t),0}catch{return 0}}async function ZG(e,t=Date.now()){try{let n=he();if(n.mode==="off")return 0;let r=e??await V();if(st(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=Ze(r);if(!o||!i)return 0;let a=await sC(o,t),c=oC(a.files[i]?.m,await cC(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(cr(Sm(i,c))+`
1089
+ `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??UG(o),c=rs(),l=OR(),d=l==="off"?null:fs(),u=c==="off"?[]:il(os())?.rules??[];c!=="off"&&sl().then(S=>{S!==null&&(u=S,ol(os(),S))}).catch(()=>{});let p=[],f=rl()&&z()!==null&&c!=="off",h=null;try{h=ne()}catch{h=null}let g=Promise.resolve(),y=s(S=>{g=g.then(()=>GG(S)),f&&p.push(S)},"record"),_=s(async()=>{if(!f)return;let S=ER(p.splice(0),c,a,h);S!==null&&(await ym(S)||await RR(S))},"attestAndReset");f&&CR().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let v=FG(o,i,{stdio:["pipe","pipe","inherit"]});v.stdout.pipe(process.stdout),v.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(S)}
1090
+ `),process.exitCode=1});let k=BG({input:process.stdin,terminal:!1});k.on("line",S=>{let R=zm(S);if(R.kind==="request"&&R.method==="tools/call"&&R.toolName){if(n.has(R.toolName)&&R.id!==void 0){process.stdout.write(xr(R.id,R.toolName)+`
1091
+ `),y(ml("deny",a,R.toolName,Date.now()));return}let P=MR(R.toolName,a,u,c);if(P.kind==="deny"&&R.id!==void 0){process.stdout.write(xr(R.id,R.toolName,$R(R.toolName,P.rule))+`
1092
+ `),y(hl("policy_deny",a,R.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));return}(P.kind==="warn"||P.kind==="deny")&&y(hl("policy_warn",a,R.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));let K=ms(S,d);if(K.length>0){let x=K.find(F=>F.verdict==="fabricated");if(x!==void 0&&l==="enforce"&&c==="enforce"&&R.id!==void 0&&x!==void 0&&R.id!==void 0){process.stdout.write(xr(R.id,R.toolName,Sr(x,!0))+`
1093
+ `),y(gl("sha_deny",a,R.toolName,Date.now()));return}let D=x??K[0];process.stderr.write(`[maind gateway] ${Sr(D,!1)}
1094
+ `),y(gl("sha_warn",a,R.toolName,Date.now()))}y(ml("tool_call",a,R.toolName,Date.now()))}v.stdin.write(S+`
1095
+ `)}),k.on("close",()=>{v.stdin.end()});let E=await new Promise(S=>{v.on("exit",(R,P)=>{S(R??(P?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(S=>setTimeout(S,KG).unref())]),await _(),E}var KG,nC=w(()=>{"use strict";yl();TR();_m();bm();_l();vm();km();re();pe();s(QR,"gatewayEventsFile");KG=5e3;s(GG,"logEvent");s(eC,"parseGatewayArgs");s(WG,"runGateway")});var Am={};Z(Am,{MAX_ENTRIES:()=>xm,TTL_MS:()=>Rm,crossSessionDir:()=>Cm,decideCrossSession:()=>iC,parseSessionDb:()=>oC,pruneDb:()=>Tm,runGuardCrossCheck:()=>eW,runGuardCrossObserve:()=>QG,staleReason:()=>Sm});import{mkdir as VG,readFile as qG,readdir as zG,stat as rC,unlink as JG,writeFile as YG}from"node:fs/promises";import{homedir as XG}from"node:os";import{join as Em}from"node:path";function Cm(){return Em(XG(),".maind","cross-session")}function oC(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[i,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[i]={m:c.m,t:c.t})}let o={};if(typeof n.warned=="object"&&n.warned!==null)for(let[i,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(o[i]=a);return{files:r,warned:o}}function Tm(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Rm);return n.length>xm&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-xm)),{files:Object.fromEntries(n),warned:e.warned}}function iC(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Sm(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 sC(e){let t=Cm();return await VG(t,{recursive:!0}),Em(t,`${e}.json`)}async function aC(e,t){try{let n=await qG(await sC(e),"utf8");return Tm(oC(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function cC(e,t){try{await YG(await sC(e),JSON.stringify(t),{mode:384})}catch{}}async function ZG(e){try{let t=Cm();for(let n of await zG(t)){if(!n.endsWith(".json"))continue;let r=Em(t,n),o=await rC(r).catch(()=>null);o&&e-o.mtimeMs>Rm&&await JG(r).catch(()=>{})}}catch{}}async function lC(e){try{return(await rC(e)).mtimeMs}catch{return}}async function QG(e,t=Date.now()){try{if(he().mode==="off")return 0;let r=e??await V();if(st(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=Ze(r);if(!o||!i)return 0;let a=await lC(i);if(a===void 0)return 0;let c=await aC(o,t);return c.files[i]={m:a,t},delete c.warned[i],await cC(o,Tm(c,t)),await ZG(t),0}catch{return 0}}async function eW(e,t=Date.now()){try{let n=he();if(n.mode==="off")return 0;let r=e??await V();if(st(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=Ze(r);if(!o||!i)return 0;let a=await aC(o,t),c=iC(a.files[i]?.m,await lC(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(cr(Sm(i,c))+`
1093
1096
  `),await te({event:"cross_session_deny",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i}),0):(a.warned[i]===c.current||(process.stdout.write(lr(Sm(i,c))+`
1094
- `),a.warned[i]=c.current,await aC(o,a),await te({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var Rm,xm,Im=w(()=>{"use strict";ke();$e();Di();vt();jt();Rm=48*3600*1e3,xm=500;s(Cm,"crossSessionDir");s(rC,"parseSessionDb");s(Tm,"pruneDb");s(oC,"decideCrossSession");s(Sm,"staleReason");s(iC,"dbPath");s(sC,"loadDb");s(aC,"saveDb");s(YG,"sweepStaleSessionFiles");s(cC,"fileMtime");s(XG,"runGuardCrossObserve");s(ZG,"runGuardCrossCheck")});var Nm={};Z(Nm,{INDEX_REFRESH_WORKER:()=>lC,acquireLock:()=>Sc,releaseLock:()=>Fi,runIndexRefreshWorker:()=>oW,runOnIndexRefresh:()=>rW});import{spawn as QG}from"node:child_process";import{existsSync as eW}from"node:fs";import{join as tW}from"node:path";function nW(e){return tW(e,".maind","code-index.sqlite")}async function rW(){try{let e=await V(),t=Me(typeof e.cwd=="string"?e.cwd:process.cwd());if(!eW(nW(t))||!Sc(t))return 0;let n=process.argv[1];if(n===void 0)return Fi(t),0;QG(process.execPath,[n,lC,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function oW(){let e=process.argv[3]??Me();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(oc(),jp)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Fi(e)}return 0}var lC,Om=w(()=>{"use strict";ke();hn();tf();lC="index-refresh-run";s(nW,"indexDbPath");s(rW,"runOnIndexRefresh");s(oW,"runIndexRefreshWorker")});function cl(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 sl(e){return e.length<3||/^\d+$/.test(e)||dC.has(e)||dC.has(cl(e))}function aW(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function cW(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function pC(e){let t=new Set,n=new Set,r=[];for(let o of e.matchAll(lW)){let i=o[0],a=i.toLowerCase();if(r.push(a),/[._-]/.test(i)){let c=cW(a);c.length>=4&&!uC.has(c)&&n.add(c)}for(let c of aW(i)){let l=c.toLowerCase();sl(l)||t.add(cl(l))}}for(let o=0;o+1<r.length;o++){if(/[._-]/.test(r[o])||/[._-]/.test(r[o+1]))continue;let i=`${r[o]}-${r[o+1]}`;uC.has(i)||n.add(i)}return{words:t,compounds:n}}function dW(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 fC(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function Pm(e){if(!e)return[];let t=[];for(let n of e.split(`
1095
- `)){let r=uW.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 pW(e){let t=e.shortId.split("-"),n=new Set;for(let i of t)sl(i)||n.add(cl(i));let r=new Set;for(let i=0;i+1<t.length;i++)!sl(t[i])&&!sl(t[i+1])&&r.add(`${t[i]}-${t[i+1]}`);let o=pC(e.summary);for(let i of o.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(i)&&r.add(i);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:o.words}}function mC(e,t,n=3,r=[]){if(t.length===0)return[];let o=new Set([...r].map(f=>cl(f.toLowerCase()))),i=t.map(pW),a=new Map,c=new Map;for(let f of i){let h=new Set([...f.keyWords,...f.keyCompounds]);for(let g of h)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...h,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=i.length,d=s(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=pC(dW(e));for(let f of o)u.words.delete(f);let p=[];for(let f of i){let h=new Set;for(let v of u.words)f.keyWords.has(v)&&h.add(v);for(let v of u.compounds)f.keyCompounds.has(v)&&h.add(v);let g=new Set;for(let v of u.words)!h.has(v)&&f.summaryWords.has(v)&&g.add(v);if(h.size===0&&g.size===0)continue;let y=0;for(let v of h)y+=2*d(v);for(let v of g)y+=d(v);let _=[...h].some(v=>(a.get(v)??0)!==1?!1:/[.-]/.test(v)?v.length>=5:v.length>=6),b=h.size>=1&&h.size+g.size>=2&&y>=fW;!_&&!b||p.push({convention:f.convention,score:y,matched:[...h,...g]})}return p.sort((f,h)=>h.score-f.score||f.convention.id.localeCompare(h.convention.id)).slice(0,n)}function gW(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function hC(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],o=new Set,i=s((c,l)=>{if(r.length>=t)return;let d=c.endsWith("()"),u=d?c.slice(0,-2):c;if(u.includes("/")||mW.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!gW(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||hW.has(f.toLowerCase())||o.has(f)||(o.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))i(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))i(c[1],!1);return r}function Dm(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function yC(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 o=new al(t-gC);if(!o.tryAdd(`${iW} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let i=[],a=[],c=!1;if(n.length>0&&o.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}): ${Dm(d.convention.summary,320)}`;if(!o.tryAdd(u)){c=!0;break}i.push(d.convention.id)}if(r.length>0&&!c){let d=e.repoRoot?` in ${e.repoRoot}`:"";if(o.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?` '${Dm(y.signature,70)}'`:""}`}).join("; "),h=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${h>0?` (+${h} more \u2014 codebase_search)`:""}`;if(!o.tryAdd(g)){c=!0;break}a.push(u.candidate.name)}}if(i.length===0&&a.length===0)return null;let l=o.toString();return c&&(l+=`
1096
- (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:i,symbolNames:a}}function _W(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>yW}function bW(e){if(e.length===0)return"";let t=e.map(o=>o.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(o=>o[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function wW(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function _C(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"),o=e.symbols.filter(g=>n.has(g.nodeKey)).sort((g,y)=>r(y.nodeKey)-r(g.nodeKey)||g.startLine-y.startLine),i=e.symbols.reduce((g,y)=>Math.max(g,y.endLine),0),a=e.symbols.filter(g=>!g.qualifiedName.includes(".")&&g.kind!=="module"),c=_W(e.range,i)&&a.length>0;if(o.length===0&&e.importers.length===0&&!c)return null;let l=bW([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new al(t-gC),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${sW} ${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 v=`${b.qualifiedName} L${b.startLine}`,k=g.length===0?v:`${g} \xB7 ${v}`;if(k.length>500)break;g=k,y++}let _=a.length-y;d.tryAdd(_>0?`${g} \xB7 +${_} more`:g)||(p=!0)}if(o.length>0&&!p&&d.tryAdd("Called from other files (import-resolved call graph):"))for(let g of o){let y=n.get(g.nodeKey)??[],_=y.slice(0,3).map(E=>`${wW(E.caller,l)}${E.kind==="calls"?"":` [${E.kind}]`}`),b=y.length-_.length,v=g.signature?` '${Dm(g.signature,80)}'`:"",k=`- ${g.qualifiedName} L${g.startLine}${v} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!d.tryAdd(k)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(v=>v.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 h=d.toString();return p&&(h+=`
1097
- (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),h}var iW,sW,dC,uC,lW,uW,fW,mW,hW,al,gC,yW,bC=w(()=>{"use strict";iW="[maind context \xB7 prompt]",sW="[maind context \xB7 read]",dC=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+/)),uC=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(cl,"stem");s(sl,"isNoise");s(aW,"splitParts");s(cW,"normalizeCompound");lW=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(pC,"termsOf");s(dW,"promptForMatching");s(fC,"repoNameWords");uW=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(Pm,"parseConventionLines");s(pW,"profileOf");fW=4.5;s(mC,"matchConventions");mW=/\.(?: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,hW=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(gW,"looksLikeCode");s(hC,"extractSymbolCandidates");s(Dm,"clip");al=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(`
1098
- `)}},gC=90;s(yC,"renderPromptContext");yW=2e3;s(_W,"isPartialRead");s(bW,"commonDir");s(wW,"callerLabel");s(_C,"renderReadContext")});import{createHash as vW}from"node:crypto";import{existsSync as wC,mkdirSync as kW,readdirSync as xW,rmSync as SW,statSync as EW,writeFileSync as RW}from"node:fs";import{join as ll}from"node:path";function Mm(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function AW(e,t,n=null,r=TW){try{for(let o of xW(e)){let i=ll(e,o);if(i!==n)try{t-EW(i).mtimeMs>r&&SW(i,{recursive:!0,force:!0})}catch{}}}catch{}}var CW,TW,ss,vC=w(()=>{"use strict";Be();CW=ll(Re,"context"),TW=7*24*60*60*1e3;s(Mm,"safe");ss=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=CW){let o=n?`${Mm(t)}__${Mm(n)}`:Mm(t);return new e(r,ll(r,o))}fileFor(t){return ll(this.dir,vW("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return wC(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{wC(this.dir)||(kW(this.dir,{recursive:!0,mode:448}),AW(this.root,n,this.dir));for(let r of t)try{RW(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(AW,"sweepStaleScopes")});var Fm={};Z(Fm,{INDEX_RELPATH:()=>cn,SOFT_BUDGET_MS:()=>SC,findRepoRoot:()=>ln,isMachinePrompt:()=>TC,loadCachedConventions:()=>RC,promptContextFor:()=>IC,promptTextOf:()=>CC,readContextFor:()=>NC,runOnPromptContext:()=>FW,runOnReadContext:()=>HW});import{existsSync as kC,readFileSync as IW,realpathSync as NW,statSync as OW}from"node:fs";import{dirname as DW,isAbsolute as xC,join as as,relative as PW,sep as MW}from"node:path";function $W(e,t){let n=PW(e,t);return!n||n.startsWith("..")||xC(n)?null:n.split(MW).join("/")}function Lm(e){try{let t=OW(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function EC(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(oc(),jp));return t(e)}function RC(e,t={}){try{let n=t.identity===void 0?ns():t.identity;if(e!==null&&n!==null){let r=ra(e,n),o=pc(r?.result.instructions??null),i=Pm(o);if(i.length>0)return i}}catch{}try{let n=JSON.parse(IW(t.briefingCacheFile??mo,"utf8"));if(typeof n.conventions=="string")return Pm(n.conventions)}catch{}return[]}function CC(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function TC(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 AC(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 LW(e,t,n,r){let o;try{o=await r(n)}catch{return[]}try{if(!o.meta().schemaCurrent)return[];let i=o.symbolsNamed(e.map(d=>d.name)),a=o.files([...i.values()].flat().map(d=>d.filePath).slice(0,$m)),c=new Set;for(let[d,u]of a){let p=Lm(as(t,d));p!==null&&ai(u,p)&&c.add(d)}let l=[];for(let d of e){let u=i.get(d.name)??[],p=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),f=p.length>0?p:u,h=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));h.length>0&&l.push({candidate:d,locations:h,total:f.length})}return l}catch{return[]}finally{try{o.close()}catch{}}}async function IC(e,t={}){let n=t.now??Date.now,r=n(),o=t.env??process.env,i=de(e,o,t.readConfig??Q);if(!xe(i,{kind:"context",event:"UserPromptSubmit"}))return null;let a=CC(e);if(a.trim().length===0||TC(e,a))return null;let c=AC(e);if(c===null)return null;let l=ss.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:lc(i,o)??process.cwd(),u=ln(d),p=c.agentId===null?(t.assignedNotice??((k,E)=>Xi(k,E,{hostPids:lt()})))(c.sessionId,d):null,f=p===null?null:`[maind] ${p}`,h=mC(a,(t.loadConventions??RC)(u),6,fC(u)).filter(k=>!l.has(`conv:${k.convention.id}@${k.convention.version}`)).slice(0,3),g=hC(a).filter(k=>!l.has(`sym:${u??""}:${k.name}`)),y=u===null?null:as(u,cn),_=g.length>0&&y!==null&&u!==null&&kC(y)&&n()-r<SC?await LW(g,u,y,t.openReader??EC):[],b=yC({repoRoot:u,conventions:h,symbols:_});if(b===null)return f;let v=new Map(h.map(k=>[k.convention.id,k.convention.version]));return l.mark([...b.conventionIds.map(k=>`conv:${k}@${v.get(k)??0}`),...b.symbolNames.map(k=>`sym:${u??""}:${k}`)],n()),f===null?b.text:`${f}
1097
+ `),a.warned[i]=c.current,await cC(o,a),await te({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var Rm,xm,Im=w(()=>{"use strict";ke();$e();Di();vt();Ht();Rm=48*3600*1e3,xm=500;s(Cm,"crossSessionDir");s(oC,"parseSessionDb");s(Tm,"pruneDb");s(iC,"decideCrossSession");s(Sm,"staleReason");s(sC,"dbPath");s(aC,"loadDb");s(cC,"saveDb");s(ZG,"sweepStaleSessionFiles");s(lC,"fileMtime");s(QG,"runGuardCrossObserve");s(eW,"runGuardCrossCheck")});var Nm={};Z(Nm,{INDEX_REFRESH_WORKER:()=>dC,acquireLock:()=>Ec,releaseLock:()=>Fi,runIndexRefreshWorker:()=>sW,runOnIndexRefresh:()=>iW});import{spawn as tW}from"node:child_process";import{existsSync as nW}from"node:fs";import{join as rW}from"node:path";function oW(e){return rW(e,".maind","code-index.sqlite")}async function iW(){try{let e=await V(),t=Me(typeof e.cwd=="string"?e.cwd:process.cwd());if(!nW(oW(t))||!Ec(t))return 0;let n=process.argv[1];if(n===void 0)return Fi(t),0;tW(process.execPath,[n,dC,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function sW(){let e=process.argv[3]??Me();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(ic(),jp)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Fi(e)}return 0}var dC,Om=w(()=>{"use strict";ke();hn();tf();dC="index-refresh-run";s(oW,"indexDbPath");s(iW,"runOnIndexRefresh");s(sW,"runIndexRefreshWorker")});function ll(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 al(e){return e.length<3||/^\d+$/.test(e)||uC.has(e)||uC.has(ll(e))}function lW(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function dW(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function fC(e){let t=new Set,n=new Set,r=[];for(let o of e.matchAll(uW)){let i=o[0],a=i.toLowerCase();if(r.push(a),/[._-]/.test(i)){let c=dW(a);c.length>=4&&!pC.has(c)&&n.add(c)}for(let c of lW(i)){let l=c.toLowerCase();al(l)||t.add(ll(l))}}for(let o=0;o+1<r.length;o++){if(/[._-]/.test(r[o])||/[._-]/.test(r[o+1]))continue;let i=`${r[o]}-${r[o+1]}`;pC.has(i)||n.add(i)}return{words:t,compounds:n}}function pW(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 mC(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function Pm(e){if(!e)return[];let t=[];for(let n of e.split(`
1098
+ `)){let r=fW.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 mW(e){let t=e.shortId.split("-"),n=new Set;for(let i of t)al(i)||n.add(ll(i));let r=new Set;for(let i=0;i+1<t.length;i++)!al(t[i])&&!al(t[i+1])&&r.add(`${t[i]}-${t[i+1]}`);let o=fC(e.summary);for(let i of o.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(i)&&r.add(i);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:o.words}}function hC(e,t,n=3,r=[]){if(t.length===0)return[];let o=new Set([...r].map(f=>ll(f.toLowerCase()))),i=t.map(mW),a=new Map,c=new Map;for(let f of i){let h=new Set([...f.keyWords,...f.keyCompounds]);for(let g of h)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...h,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=i.length,d=s(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=fC(pW(e));for(let f of o)u.words.delete(f);let p=[];for(let f of i){let h=new Set;for(let v of u.words)f.keyWords.has(v)&&h.add(v);for(let v of u.compounds)f.keyCompounds.has(v)&&h.add(v);let g=new Set;for(let v of u.words)!h.has(v)&&f.summaryWords.has(v)&&g.add(v);if(h.size===0&&g.size===0)continue;let y=0;for(let v of h)y+=2*d(v);for(let v of g)y+=d(v);let _=[...h].some(v=>(a.get(v)??0)!==1?!1:/[.-]/.test(v)?v.length>=5:v.length>=6),b=h.size>=1&&h.size+g.size>=2&&y>=hW;!_&&!b||p.push({convention:f.convention,score:y,matched:[...h,...g]})}return p.sort((f,h)=>h.score-f.score||f.convention.id.localeCompare(h.convention.id)).slice(0,n)}function _W(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function gC(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],o=new Set,i=s((c,l)=>{if(r.length>=t)return;let d=c.endsWith("()"),u=d?c.slice(0,-2):c;if(u.includes("/")||gW.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!_W(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||yW.has(f.toLowerCase())||o.has(f)||(o.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))i(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))i(c[1],!1);return r}function Dm(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function _C(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 o=new cl(t-yC);if(!o.tryAdd(`${aW} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let i=[],a=[],c=!1;if(n.length>0&&o.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}): ${Dm(d.convention.summary,320)}`;if(!o.tryAdd(u)){c=!0;break}i.push(d.convention.id)}if(r.length>0&&!c){let d=e.repoRoot?` in ${e.repoRoot}`:"";if(o.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?` '${Dm(y.signature,70)}'`:""}`}).join("; "),h=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${h>0?` (+${h} more \u2014 codebase_search)`:""}`;if(!o.tryAdd(g)){c=!0;break}a.push(u.candidate.name)}}if(i.length===0&&a.length===0)return null;let l=o.toString();return c&&(l+=`
1099
+ (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:i,symbolNames:a}}function wW(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>bW}function vW(e){if(e.length===0)return"";let t=e.map(o=>o.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(o=>o[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function kW(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function bC(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"),o=e.symbols.filter(g=>n.has(g.nodeKey)).sort((g,y)=>r(y.nodeKey)-r(g.nodeKey)||g.startLine-y.startLine),i=e.symbols.reduce((g,y)=>Math.max(g,y.endLine),0),a=e.symbols.filter(g=>!g.qualifiedName.includes(".")&&g.kind!=="module"),c=wW(e.range,i)&&a.length>0;if(o.length===0&&e.importers.length===0&&!c)return null;let l=vW([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new cl(t-yC),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${cW} ${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 v=`${b.qualifiedName} L${b.startLine}`,k=g.length===0?v:`${g} \xB7 ${v}`;if(k.length>500)break;g=k,y++}let _=a.length-y;d.tryAdd(_>0?`${g} \xB7 +${_} more`:g)||(p=!0)}if(o.length>0&&!p&&d.tryAdd("Called from other files (import-resolved call graph):"))for(let g of o){let y=n.get(g.nodeKey)??[],_=y.slice(0,3).map(E=>`${kW(E.caller,l)}${E.kind==="calls"?"":` [${E.kind}]`}`),b=y.length-_.length,v=g.signature?` '${Dm(g.signature,80)}'`:"",k=`- ${g.qualifiedName} L${g.startLine}${v} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!d.tryAdd(k)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(v=>v.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 h=d.toString();return p&&(h+=`
1100
+ (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),h}var aW,cW,uC,pC,uW,fW,hW,gW,yW,cl,yC,bW,wC=w(()=>{"use strict";aW="[maind context \xB7 prompt]",cW="[maind context \xB7 read]",uC=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+/)),pC=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(ll,"stem");s(al,"isNoise");s(lW,"splitParts");s(dW,"normalizeCompound");uW=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(fC,"termsOf");s(pW,"promptForMatching");s(mC,"repoNameWords");fW=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(Pm,"parseConventionLines");s(mW,"profileOf");hW=4.5;s(hC,"matchConventions");gW=/\.(?: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,yW=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(_W,"looksLikeCode");s(gC,"extractSymbolCandidates");s(Dm,"clip");cl=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(`
1101
+ `)}},yC=90;s(_C,"renderPromptContext");bW=2e3;s(wW,"isPartialRead");s(vW,"commonDir");s(kW,"callerLabel");s(bC,"renderReadContext")});import{createHash as xW}from"node:crypto";import{existsSync as vC,mkdirSync as SW,readdirSync as EW,rmSync as RW,statSync as CW,writeFileSync as TW}from"node:fs";import{join as dl}from"node:path";function Mm(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function NW(e,t,n=null,r=IW){try{for(let o of EW(e)){let i=dl(e,o);if(i!==n)try{t-CW(i).mtimeMs>r&&RW(i,{recursive:!0,force:!0})}catch{}}}catch{}}var AW,IW,ss,kC=w(()=>{"use strict";Be();AW=dl(Re,"context"),IW=7*24*60*60*1e3;s(Mm,"safe");ss=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=AW){let o=n?`${Mm(t)}__${Mm(n)}`:Mm(t);return new e(r,dl(r,o))}fileFor(t){return dl(this.dir,xW("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return vC(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{vC(this.dir)||(SW(this.dir,{recursive:!0,mode:448}),NW(this.root,n,this.dir));for(let r of t)try{TW(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(NW,"sweepStaleScopes")});var Fm={};Z(Fm,{INDEX_RELPATH:()=>cn,SOFT_BUDGET_MS:()=>EC,findRepoRoot:()=>ln,isMachinePrompt:()=>AC,loadCachedConventions:()=>CC,promptContextFor:()=>NC,promptTextOf:()=>TC,readContextFor:()=>OC,runOnPromptContext:()=>HW,runOnReadContext:()=>BW});import{existsSync as xC,readFileSync as OW,realpathSync as DW,statSync as PW}from"node:fs";import{dirname as MW,isAbsolute as SC,join as as,relative as $W,sep as LW}from"node:path";function FW(e,t){let n=$W(e,t);return!n||n.startsWith("..")||SC(n)?null:n.split(LW).join("/")}function Lm(e){try{let t=PW(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function RC(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(ic(),jp));return t(e)}function CC(e,t={}){try{let n=t.identity===void 0?ns():t.identity;if(e!==null&&n!==null){let r=oa(e,n),o=fc(r?.result.instructions??null),i=Pm(o);if(i.length>0)return i}}catch{}try{let n=JSON.parse(OW(t.briefingCacheFile??mo,"utf8"));if(typeof n.conventions=="string")return Pm(n.conventions)}catch{}return[]}function TC(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function AC(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 IC(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 jW(e,t,n,r){let o;try{o=await r(n)}catch{return[]}try{if(!o.meta().schemaCurrent)return[];let i=o.symbolsNamed(e.map(d=>d.name)),a=o.files([...i.values()].flat().map(d=>d.filePath).slice(0,$m)),c=new Set;for(let[d,u]of a){let p=Lm(as(t,d));p!==null&&ai(u,p)&&c.add(d)}let l=[];for(let d of e){let u=i.get(d.name)??[],p=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),f=p.length>0?p:u,h=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));h.length>0&&l.push({candidate:d,locations:h,total:f.length})}return l}catch{return[]}finally{try{o.close()}catch{}}}async function NC(e,t={}){let n=t.now??Date.now,r=n(),o=t.env??process.env,i=de(e,o,t.readConfig??Q);if(!xe(i,{kind:"context",event:"UserPromptSubmit"}))return null;let a=TC(e);if(a.trim().length===0||AC(e,a))return null;let c=IC(e);if(c===null)return null;let l=ss.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:dc(i,o)??process.cwd(),u=ln(d),p=c.agentId===null?(t.assignedNotice??((k,E)=>Xi(k,E,{hostPids:lt()})))(c.sessionId,d):null,f=p===null?null:`[maind] ${p}`,h=hC(a,(t.loadConventions??CC)(u),6,mC(u)).filter(k=>!l.has(`conv:${k.convention.id}@${k.convention.version}`)).slice(0,3),g=gC(a).filter(k=>!l.has(`sym:${u??""}:${k.name}`)),y=u===null?null:as(u,cn),_=g.length>0&&y!==null&&u!==null&&xC(y)&&n()-r<EC?await jW(g,u,y,t.openReader??RC):[],b=_C({repoRoot:u,conventions:h,symbols:_});if(b===null)return f;let v=new Map(h.map(k=>[k.convention.id,k.convention.version]));return l.mark([...b.conventionIds.map(k=>`conv:${k}@${v.get(k)??0}`),...b.symbolNames.map(k=>`sym:${u??""}:${k}`)],n()),f===null?b.text:`${f}
1099
1102
 
1100
- ${b.text}`}async function FW(){try{let e=await V(),t=await IC(e);if(t!==null){let n=me(de(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function jW(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,o=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0;return r===void 0&&o===void 0?null:{offset:r,limit:o}}async function NC(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=de(e,t.env??process.env,t.readConfig??Q);if(!xe(r,{kind:"context",event:"PreToolUse"}))return null;let o=Ze(e);if(!o||$r(o)===null||Ko(o))return null;let i=AC(e);if(i===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=xC(o)?o:as(a,o),l;try{l=NW(c)}catch{return null}let d=ln(DW(l));if(d===null)return null;let u=as(d,cn);if(!kC(u))return null;let p=$W(d,l);if(p===null)return null;let f=await(t.openReader??EC)(u);try{let h=f.meta();if(!h.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=Lm(l);if(y===null||!ai(g,y))return null;let _=ss.forScope(i.sessionId,i.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let v=f.symbolsInFile(p),k=h.edgesDirty?[]:f.callersOfFile(p),E=h.edgesDirty?[]:f.importersOf(p),S=[...new Set([...k.map(X=>X.caller.filePath),...E])],R=S.slice(0,$m),P=new Set(S.slice($m)),K=f.files(R),x=new Set;for(let X of R){let Qe=K.get(X),ls=Qe===void 0?null:Lm(as(d,X));Qe!==void 0&&ls!==null&&ai(Qe,ls)&&x.add(X)}let T=s(X=>k.filter(Qe=>X.has(Qe.caller.filePath)).length+E.filter(Qe=>X.has(Qe)).length,"countIn"),D=k.filter(X=>x.has(X.caller.filePath)).map(X=>({calleeKey:X.calleeKey,kind:X.kind,caller:{nodeKey:X.caller.nodeKey,kind:X.caller.kind,qualifiedName:X.caller.qualifiedName,filePath:X.caller.filePath,startLine:X.caller.startLine}})),F=E.filter(X=>x.has(X)),xt=T(P),cs=k.length-D.length+(E.length-F.length)-xt,Io=_C({relPath:p,symbols:v,callers:D,importers:F,hidden:cs,unchecked:xt,range:jW(e)});return Io===null?null:(_.mark([b],n()),Io)}finally{f.close()}}async function HW(){try{let e=await V(),t=await NC(e);if(t!==null){let n=me(de(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var SC,$m,jm=w(()=>{"use strict";tn();Ue();mc();pr();Ao();Dt();bC();vC();Wf();Qi();Ua();ke();$e();SC=200,$m=200;s($W,"repoRelative");s(Lm,"diskStat");s(EC,"openReader");s(RC,"loadCachedConventions");s(CC,"promptTextOf");s(TC,"isMachinePrompt");s(AC,"scopeOf");s(LW,"locateSymbols");s(IC,"promptContextFor");s(FW,"runOnPromptContext");s(jW,"readRangeOf");s(NC,"readContextFor");s(HW,"runOnReadContext")});import{randomUUID as UW}from"node:crypto";Oo();import{createInterface as dD}from"node:readline";var MC=[["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 $C(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of MC)if(t.includes(n))return r;return null}s($C,"mapClientInfoNameToFamily");function Wm(e){let t;try{t=JSON.parse(e)}catch{return null}if(!ul(t)||t.method!=="initialize")return null;let n=t.params;if(!ul(n))return null;let r=n.clientInfo;if(!ul(r))return null;let o=r.name,i=$C(typeof o=="string"?o:null);if(i===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:c}}s(Wm,"tryExtractInitializeClient");function ul(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ul,"isRecord");import{fileURLToPath as LC}from"node:url";var pl="maind-bridge-",FC=8,Vm=8e3;function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Bt,"isRecord");function jC(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}}s(jC,"clientDeclaresRoots");function HC(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(HC,"isInitializedNotification");function UC(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 o;try{o=LC(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=FC)break}return n}s(UC,"rootPathsFrom");var ps=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(pl)){let n;try{n=JSON.parse(t)}catch{n=null}if(Bt(n)&&typeof n.id=="string"&&n.id.startsWith(pl)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&HC(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=Vm){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 o=`${pl}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,i=new Promise(a=>{let c=s(d=>{clearTimeout(l),this.pending.delete(o),a(d)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(o,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:o,method:t})),i}};async function qm(e,t,n=Vm){return jC(e)?UC(await t.request("roots/list",n)):null}s(qm,"listClientRoots");gl();yl();function _l(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let i=JSON.parse(t);return Array.isArray(i)?i:[i]}catch{return[]}let n=[],r=[],o=s(()=>{if(r.length===0)return;let i=r.join(`
1103
+ ${b.text}`}async function HW(){try{let e=await V(),t=await NC(e);if(t!==null){let n=me(de(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function UW(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,o=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0;return r===void 0&&o===void 0?null:{offset:r,limit:o}}async function OC(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=de(e,t.env??process.env,t.readConfig??Q);if(!xe(r,{kind:"context",event:"PreToolUse"}))return null;let o=Ze(e);if(!o||$r(o)===null||Ko(o))return null;let i=IC(e);if(i===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=SC(o)?o:as(a,o),l;try{l=DW(c)}catch{return null}let d=ln(MW(l));if(d===null)return null;let u=as(d,cn);if(!xC(u))return null;let p=FW(d,l);if(p===null)return null;let f=await(t.openReader??RC)(u);try{let h=f.meta();if(!h.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=Lm(l);if(y===null||!ai(g,y))return null;let _=ss.forScope(i.sessionId,i.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let v=f.symbolsInFile(p),k=h.edgesDirty?[]:f.callersOfFile(p),E=h.edgesDirty?[]:f.importersOf(p),S=[...new Set([...k.map(X=>X.caller.filePath),...E])],R=S.slice(0,$m),P=new Set(S.slice($m)),K=f.files(R),x=new Set;for(let X of R){let Qe=K.get(X),ls=Qe===void 0?null:Lm(as(d,X));Qe!==void 0&&ls!==null&&ai(Qe,ls)&&x.add(X)}let T=s(X=>k.filter(Qe=>X.has(Qe.caller.filePath)).length+E.filter(Qe=>X.has(Qe)).length,"countIn"),D=k.filter(X=>x.has(X.caller.filePath)).map(X=>({calleeKey:X.calleeKey,kind:X.kind,caller:{nodeKey:X.caller.nodeKey,kind:X.caller.kind,qualifiedName:X.caller.qualifiedName,filePath:X.caller.filePath,startLine:X.caller.startLine}})),F=E.filter(X=>x.has(X)),xt=T(P),cs=k.length-D.length+(E.length-F.length)-xt,Io=bC({relPath:p,symbols:v,callers:D,importers:F,hidden:cs,unchecked:xt,range:UW(e)});return Io===null?null:(_.mark([b],n()),Io)}finally{f.close()}}async function BW(){try{let e=await V(),t=await OC(e);if(t!==null){let n=me(de(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var EC,$m,jm=w(()=>{"use strict";tn();Ue();hc();pr();Ao();Pt();wC();kC();Wf();Qi();Ba();ke();$e();EC=200,$m=200;s(FW,"repoRelative");s(Lm,"diskStat");s(RC,"openReader");s(CC,"loadCachedConventions");s(TC,"promptTextOf");s(AC,"isMachinePrompt");s(IC,"scopeOf");s(jW,"locateSymbols");s(NC,"promptContextFor");s(HW,"runOnPromptContext");s(UW,"readRangeOf");s(OC,"readContextFor");s(BW,"runOnReadContext")});import{randomUUID as KW}from"node:crypto";Oo();import{createInterface as pD}from"node:readline";var $C=[["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 LC(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of $C)if(t.includes(n))return r;return null}s(LC,"mapClientInfoNameToFamily");function Wm(e){let t;try{t=JSON.parse(e)}catch{return null}if(!pl(t)||t.method!=="initialize")return null;let n=t.params;if(!pl(n))return null;let r=n.clientInfo;if(!pl(r))return null;let o=r.name,i=LC(typeof o=="string"?o:null);if(i===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:c}}s(Wm,"tryExtractInitializeClient");function pl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(pl,"isRecord");import{fileURLToPath as FC}from"node:url";var fl="maind-bridge-",jC=8,Vm=8e3;function Kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Kt,"isRecord");function HC(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Kt(t)||t.method!=="initialize"||!Kt(t.params))return!1;let n=t.params.capabilities;return Kt(n)&&Kt(n.roots)}catch{return!1}}s(HC,"clientDeclaresRoots");function UC(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(UC,"isInitializedNotification");function BC(e){if(!Kt(e)||!Kt(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Kt(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=FC(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=jC)break}return n}s(BC,"rootPathsFrom");var ps=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(fl)){let n;try{n=JSON.parse(t)}catch{n=null}if(Kt(n)&&typeof n.id=="string"&&n.id.startsWith(fl)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&UC(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=Vm){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 o=`${fl}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,i=new Promise(a=>{let c=s(d=>{clearTimeout(l),this.pending.delete(o),a(d)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(o,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:o,method:t})),i}};async function qm(e,t,n=Vm){return HC(e)?BC(await t.request("roots/list",n)):null}s(qm,"listClientRoots");yl();_l();function bl(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let i=JSON.parse(t);return Array.isArray(i)?i:[i]}catch{return[]}let n=[],r=[],o=s(()=>{if(r.length===0)return;let i=r.join(`
1101
1104
  `).trim();if(r=[],i.length!==0)try{n.push(JSON.parse(i))}catch{}},"flush");for(let i of t.split(`
1102
- `)){let a=i.endsWith("\r")?i.slice(0,-1):i;if(a===""){o();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return o(),n}s(_l,"rpcMessagesOf");function eh(e,t){for(let n of _l(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 o=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(o.content)?o.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:o.isError===!0,text:a?.text??""}}return null}s(eh,"parseCloudToolResponse");Dt();var uD="https://mcp.maind.dev/mcp",ci=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},sa=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=Gr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=pD(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=fD(r),this.clientVersionLocked=this.clientVersion!==null;let o=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=o&&/^[a-f0-9]{64}$/.test(o)?o: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 i=t.carry??null;i!==null&&(this.initFrame=i.initFrame,this.clientFamily===null&&(this.clientFamily=i.clientFamily),this.clientVersion===null&&(this.clientVersion=i.clientVersion),this.replayFrame=i.pendingFrame),this.clientChannel=new ps(a=>process.stdout.write(a+`
1103
- `),i!==null&&i.initFrame!==null&&(i.pendingFrame===null||!Wr(i.pendingFrame))),this.shaRepoRoot=fs(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??uD}async run(t=Eu()){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 o=n.trim();o.length!==0&&await this.forwardFrame(o)}}listClientRoots(t){return qm(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=Wm(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Wr(t)&&(this.initFrame=t);let r=gD(t),o=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=ms(t,this.shaRepoRoot);if(u.length>0){let p=u.find(h=>h.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&Zm(p)&&r.id!==null){let h=Sr(p,!0);process.stderr.write(`[maind] ${h}
1105
+ `)){let a=i.endsWith("\r")?i.slice(0,-1):i;if(a===""){o();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return o(),n}s(bl,"rpcMessagesOf");function eh(e,t){for(let n of bl(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 o=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(o.content)?o.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:o.isError===!0,text:a?.text??""}}return null}s(eh,"parseCloudToolResponse");Pt();var fD="https://mcp.maind.dev/mcp",ci=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},aa=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=Gr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=mD(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=hD(r),this.clientVersionLocked=this.clientVersion!==null;let o=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=o&&/^[a-f0-9]{64}$/.test(o)?o: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 i=t.carry??null;i!==null&&(this.initFrame=i.initFrame,this.clientFamily===null&&(this.clientFamily=i.clientFamily),this.clientVersion===null&&(this.clientVersion=i.clientVersion),this.replayFrame=i.pendingFrame),this.clientChannel=new ps(a=>process.stdout.write(a+`
1106
+ `),i!==null&&i.initFrame!==null&&(i.pendingFrame===null||!Wr(i.pendingFrame))),this.shaRepoRoot=fs(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??fD}async run(t=Eu()){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 o=n.trim();o.length!==0&&await this.forwardFrame(o)}}listClientRoots(t){return qm(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=Wm(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Wr(t)&&(this.initFrame=t);let r=_D(t),o=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=ms(t,this.shaRepoRoot);if(u.length>0){let p=u.find(h=>h.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&Zm(p)&&r.id!==null){let h=Sr(p,!0);process.stderr.write(`[maind] ${h}
1104
1107
  `);let g=r.params?.name;process.stdout.write(xr(r.id,typeof g=="string"?g:"unknown",h)+`
1105
1108
  `);return}o=Sr(f,!1),process.stderr.write(`[maind] ${o}
1106
1109
  `)}if(this.assignedInbox&&!Gm(this.clientFamily)){let p=this.assignedInbox.takeNote();p!==null&&(o=o===null?p:`${o}
1107
1110
  [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+`
1108
- `);return}let i=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Wr(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=oa(t);if(this.serveInitializeFromCache(t,p))return;ia(p,-32603,`bridge network error: ${Wb(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&&!Wr(t)){let u=await c.text().catch(()=>"");if(Gb(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=oa(t);ia(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=oa(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;ia(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(i&&this.localRouter){let u=d.startsWith("text/event-stream")?await xu(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
1111
+ `);return}let i=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Wr(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=ia(t);if(this.serveInitializeFromCache(t,p))return;sa(p,-32603,`bridge network error: ${Vb(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&&!Wr(t)){let u=await c.text().catch(()=>"");if(Wb(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=ia(t);sa(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=ia(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;sa(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(i&&this.localRouter){let u=d.startsWith("text/event-stream")?await xu(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
1109
1112
  `);return}if(Wr(t)){let u=d.startsWith("text/event-stream")?await xu(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
1110
- `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(o!==null){let u=d.startsWith("text/event-stream")?await xu(c):await c.text(),p=hD(u,o);p.trim().length>0&&process.stdout.write(p+`
1111
- `);return}if(d.startsWith("text/event-stream"))await mD(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
1112
- `)}}}async handle401(t,n){let r=await t.text().catch(()=>""),o=r.toLowerCase();if(o.includes("device_mismatch")||o.includes("device_revoked")||o.includes("device_required")||o.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new ci(_D(o));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=oa(n);ia(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}}),o=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),i=await o.text().catch(()=>"");if(!o.ok)throw new Error(`presence: upstream HTTP ${o.status}`);return bD(i)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let o=r.timeoutMs??9e4,i=await this.postCloudToolCall(t,n,o);if(i.kind!=="session_lost")return i;if(!await this.recoverSession())return{kind:"http_error",status:404,body:i.body.slice(0,500)};let a=await this.postCloudToolCall(t,n,o);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 o=`maind-bridge-${this.cloudFrameId}`,i=JSON.stringify({jsonrpc:"2.0",id:o,method:"tools/call",params:{name:t,arguments:n}});try{let a=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:i,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&&Gb(l)?{kind:"session_lost",body:l}:a.ok?eh(l,o)??{kind:"transport_error",message:`the response carried no answer to ${o}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:a.status,body:l.slice(0,500)}}catch(a){return{kind:"transport_error",message:Wb(a),timedOut:yD(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=ot()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Bb(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Wr(t))return!1;let r=ra(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Kb(n,r)+`
1113
- `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${na(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Eu(){return dD({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}s(Eu,"stdinLines");function pD(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(pD,"normalizeClientFamily");function fD(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(fD,"normalizeClientVersion");async function mD(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i=s(()=>{if(o.length===0)return;let a=o.join(`
1113
+ `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(o!==null){let u=d.startsWith("text/event-stream")?await xu(c):await c.text(),p=yD(u,o);p.trim().length>0&&process.stdout.write(p+`
1114
+ `);return}if(d.startsWith("text/event-stream"))await gD(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
1115
+ `)}}}async handle401(t,n){let r=await t.text().catch(()=>""),o=r.toLowerCase();if(o.includes("device_mismatch")||o.includes("device_revoked")||o.includes("device_required")||o.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new ci(wD(o));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=ia(n);sa(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}}),o=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),i=await o.text().catch(()=>"");if(!o.ok)throw new Error(`presence: upstream HTTP ${o.status}`);return vD(i)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let o=r.timeoutMs??9e4,i=await this.postCloudToolCall(t,n,o);if(i.kind!=="session_lost")return i;if(!await this.recoverSession())return{kind:"http_error",status:404,body:i.body.slice(0,500)};let a=await this.postCloudToolCall(t,n,o);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 o=`maind-bridge-${this.cloudFrameId}`,i=JSON.stringify({jsonrpc:"2.0",id:o,method:"tools/call",params:{name:t,arguments:n}});try{let a=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:i,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&&Wb(l)?{kind:"session_lost",body:l}:a.ok?eh(l,o)??{kind:"transport_error",message:`the response carried no answer to ${o}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:a.status,body:l.slice(0,500)}}catch(a){return{kind:"transport_error",message:Vb(a),timedOut:bD(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=ot()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Kb(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Wr(t))return!1;let r=oa(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Gb(n,r)+`
1116
+ `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ra(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Eu(){return pD({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}s(Eu,"stdinLines");function mD(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(mD,"normalizeClientFamily");function hD(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(hD,"normalizeClientVersion");async function gD(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i=s(()=>{if(o.length===0)return;let a=o.join(`
1114
1117
  `).trim();o=[],a.length>0&&process.stdout.write(a+`
1115
1118
  `)},"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(`
1116
- `))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){i();continue}u.startsWith(":")||u.startsWith("data:")&&o.push(u.slice(5).replace(/^\s/,""))}}}finally{i()}}s(mD,"pipeSseToStdout");function hD(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(hD,"appendNoteToToolResult");function gD(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(gD,"parseRpc");async function xu(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i=[],a=s(()=>{if(i.length===0)return;let c=i.join(`
1119
+ `))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){i();continue}u.startsWith(":")||u.startsWith("data:")&&o.push(u.slice(5).replace(/^\s/,""))}}}finally{i()}}s(gD,"pipeSseToStdout");function yD(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(yD,"appendNoteToToolResult");function _D(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(_D,"parseRpc");async function xu(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i=[],a=s(()=>{if(i.length===0)return;let c=i.join(`
1117
1120
  `).trim();i=[],c.length>0&&o.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(`
1118
1121
  `))!==-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/,""))}}}finally{a()}return o.join(`
1119
- `)}s(xu,"collectSseText");function oa(e){try{return JSON.parse(e).id??null}catch{return null}}s(oa,"tryExtractId");function Wr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Wr,"isInitializeRequest");function Gb(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(Gb,"isSessionLossBody");function Wb(e){return e instanceof Error?e.message:String(e)}s(Wb,"stringifyErr");function yD(e){return e?.name==="TimeoutError"}s(yD,"isTimeoutError");function ia(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
1120
- `)}s(ia,"emitJsonRpcError");function _D(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(_D,"extractHint");function bD(e){try{let t=_l(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(bD,"parsePresenceToolResult");re();Au();Iu();Fe();pe();ef();hn();hn();import{readFileSync as Nj}from"node:fs";import{join as jx}from"node:path";function kc(e){return e?Math.ceil(e.length/4):0}s(kc,"estimateTokens");var Hx=1e6,xc=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 Ux(e){try{let t=Nj(e,"utf8");return t.length>Hx?t.slice(0,Hx):t}catch{return""}}s(Ux,"readFileCapped");function Oj(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(Oj,"distinctFilePaths");function Bx(e,t,n,r){try{let o=kc(n);if(e==="codebase_search"){let i=Oj(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=kc(Ux(jx(r,c)));return Math.max(0,a-o)}if(e==="codebase_snippet"){let i=t?.filePath;if(typeof i!="string"||i.length===0)return 0;let a=kc(Ux(jx(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(Bx,"measureLocalToolSaved");tn();hn();import{createHash as Qj}from"node:crypto";tn();import{execFileSync as $j}from"node:child_process";import{createHash as Lj}from"node:crypto";hn();tf();import{realpathSync as zx}from"node:fs";function Fj(e,t){try{return zx(e)===zx(t)}catch{return e===t}}s(Fj,"samePath");var nf=30,jj=10,Jx=20,Hj=new Map;function rf(e){return e instanceof Error?e.message:String(e)}s(rf,"msg");function Ec(e){let t=e.split(`
1121
- `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Ec,"firstLine");var Yx=s(e=>e?e.slice(0,12):"?","short");async function Uj(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await qx(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:rf(c)}}},n);return a.locked?a.value.ok?i?(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}:(i||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:i}):(i||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:i})}s(Uj,"refreshIndex");function Bj(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(Bj,"isEmptyRange");function Kj(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(Kj,"localOnly");function Gj(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(Gj,"localGradeBlockers");function Wj(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=_u(!1,e.projectKey,e.result);if(!t.persist)return t;let n=Gj(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(Wj,"bridgePersistDecision");function Xx(e,t){try{return $j("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(Xx,"git");function Vj(e,t){let n=Vo(e),r=n&&Xx(e,["merge-base",t,`origin/${n}`])||null,o=Xx(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(Vj,"gitPersistFacts");function qj(e,t){return Lj("sha256").update(`${e??""}
1122
- ${JSON.stringify(t)}`).digest("hex")}s(qj,"payloadKey");function ct(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(ct,"fail");var mr="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Zx(e){let t=wu(e);if(t!==null&&vu(t))return ct("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 ct("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 ct("cloud_unavailable",`review_verdict failed: ${Ec(t?.detail??e)||"no detail"}`,mr)}s(Zx,"fromProtocolText");function zj(e,t,n){switch(e.kind){case"no_session":return ct("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. ${mr}`);case"transport_error":return e.timedOut?ct("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."):ct("cloud_unavailable",`network error: ${e.message}`,mr);case"http_error":return e.status===401?ct("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Ec(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?ct("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."):ct("cloud_unavailable",`HTTP ${e.status}: ${Ec(e.body)}`,mr);case"rpc_error":return Zx(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Zx(e.text);let r;try{r=JSON.parse(e.text)}catch{return ct("cloud_unavailable",`review_verdict returned non-JSON text: ${Ec(e.text)}`,mr)}return typeof r!="object"||r===null?ct("cloud_unavailable","review_verdict returned no object",mr):{kind:"verdict",body:r}}}}s(zj,"interpretOutcome");var Jj="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).",Yj={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"},Qx=s(e=>e.map(t=>Yj[t]??t).join("; "),"adviceFor");function Xj(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: ${Qx(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,o]=t??[];return`the reviewed range starts at ${Yx(n)}, but this branch forks off ${o??"the default branch"} at ${Yx(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${o??"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(Xj,"skipText");function Zj(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=Qx(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let o=e.reason??"",i=Xj(o,e.detail),a=t===!0&&o!=="no_report"?" The run itself is attestation-grade.":"";return i!==null?`Not recorded: ${i}${a}`:`Not recorded (${o||"the server gave no reason"}).${a}`}s(Zj,"recordHint");async function eS(e,t,n){let r=n.repoRoot??Me(),o=r,i=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let le=po(c,r);if(le===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(!Fj(le.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."};o=le.repoRoot,i=n.engineFor(o),a=n.projectKeyFor?.(o)??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??Hj,h=[],g=await Uj(i,o,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 i.reviewChanges(gu(l,d)),_={repo_root:o,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(Bj(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:h};let b;try{b=await i.reviewDetectorScopes({baseRef:l})}catch(le){let Hm=Ve(Nt(`reviewDetectorScopes failed: ${rf(le)}`));b={commit:Hm,local:Hm},h.push(`repo-health detectors unavailable (${rf(le)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:v,dropped:k}=yu(y,b.commit);k>0&&h.push(`${k} symbol(s) exceed the server schema (name > ${ea} or qualified name > ${ta} chars) and were left out \u2014 this run is not attestation-grade.`);let E=qj(a,v),S=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",R=Wj({persistWanted:u,since:l,projectKey:a,result:y,payload:v,git:S?(n.persistFacts??Vj)(o,y.headSha):null,recordedRunId:f.get(E)??null}),P={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:v.changed_symbols.length,symbols_dropped:k,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,Jx),local_only:Kj(b).slice(0,Jx)}},K=await n.callCloudTool("review_verdict",{attest:v,persist:R.persist,...a?{project_key:a}:{}},{timeoutMs:p}),x=zj(K,p,R.persist);if(x.kind==="error")return{ok:!1,error:x.error,message:x.message,hint:x.hint,base:_,local:P,warnings:h};let T=x.body;if(T.ok!==!0){let le=T.error==="requires_team"||T.error==="requires_enterprise";return{ok:!1,error:T.error??"unknown_error",message:T.message??"review_verdict returned no message",hint:le?Jj:T.hint??mr,base:_,local:P,warnings:h}}if(T.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:P,warnings:h};let D=T.attest,F=T.run??null,xt=F&&typeof F.id=="string"?{persisted:!0,run_id:F.id,commit_sha:F.commit_sha??null,attestation_format:F.attestation_format??null}:{persisted:!1,reason:R.skipped??T.run_note??"not_persisted",...R.detail?{detail:R.detail}:{}};xt.persisted&&f.set(E,F.id);let cs=typeof D?.attestation_grade=="boolean"?D.attestation_grade:null,Io=Array.isArray(D?.grade_blockers)?D.grade_blockers:[],X=T.counts??{},Qe=Array.isArray(T.findings)?T.findings:[],ls=`Verdict ${T.verdict??"?"}: ${X.block??0} block, ${X.warn??0} warn, ${X.note??0} note`+(T.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:T.verdict??null,counts:X,record:xt,attest:D?{attestation_grade:cs,grade_blockers:Io,attestation_format:D.attestation_format??null,input_hash:D.input_hash??null,policy_hash:D.policy_hash??null,evaluated_convention_count:D.evaluated_convention_count??null,detector_coverage:D.detector_coverage??null}:null,hint:`${ls} ${Zj(xt,cs,Io,y.headSha)}`,findings:Qe.slice(0,nf).map(le=>({convention_id:le.convention_id,convention_version:le.convention_version,severity:le.severity,action:le.action,...le.downgrade_reason?{downgrade_reason:le.downgrade_reason}:{},summary:le.summary,matched_changed_symbols:(le.matched_changed_symbols??[]).slice(0,jj),matched_symbol_count:le.matched_symbols?.length??0})),...Qe.length>nf?{findings_not_shown:Qe.length-nf}:{},detector_findings:T.detector_findings??[],policy_source:T.policy_source??null,coverage_note:bu(y,D?.evaluated_convention_count,k),base:_,local:P,warnings:h}}s(eS,"runAttestReview");var tS=(()=>{let e=Object.keys(Zo),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Rc(e){return Qj("sha256").update(e,"utf8").digest("hex")}s(Rc,"nodeKeyHash");var e1=["module","class","interface","function","method","type_alias","enum","variable"],of=[{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:e1,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 "+tS+" \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 "+tS+", 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."}}}}],sf=new Map([["codebase_review_verdict","attest_review_changes"]]),oS=new Set([...of.map(e=>e.name),...sf.keys()]),af=new Set(["attest_review_changes",...[...sf].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function iS(e,t,n,r){if(!af.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 o=await eS(e,n,r),i=sf.get(t);return i?{...o,renamed:{from:t,to:i,note:`${t} is ${i} since bridge 0.79.0 \u2014 call ${i}; the old name goes in a later minor.`}}:o}s(iS,"dispatchCloudBackedTool");function ge(e){return typeof e=="string"&&e.length>0?e:void 0}s(ge,"str");function hr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(hr,"num");function nS(e){if(e===void 0)return{repoRoot:Me(),scanDirs:void 0};let t=po(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(nS,"anchorRepo");function rS(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(rS,"dirNotFound");async function sS(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 o=r.findings.filter(a=>a.status==="open").length,i=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:o,warn_count:i,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${o} blocking (open) + ${i} 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,o=ge(n.for_path);if(o!==void 0){let u=Qk(o);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:o,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 Kn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,h=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:h(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let i=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(i!==void 0&&i.length>0){let u=new Map,p=[];for(let k of i){let E=po(k);if(E===null){p.push(k);continue}let S=u.get(E.repoRoot)??new Set;S.add(E.repoRelDir),u.set(E.repoRoot,S)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],h=[],g=[],y=[];for(let[k,E]of u){let S=[...E],R=S.includes(""),P=await Bn(k,{dirs:R?void 0:S,minFiles:r});f.push({repo_root:k,dirs:R?null:S}),h.push(...P.findings),g.push(...P.facts.namespaces.map(K=>({repo_root:k,dir:K.dir,prefix:K.prefix,file_count:K.fileCount}))),y.push(...P.facts.skipped)}let _=h.filter(k=>k.status==="open"),b=h.filter(k=>k.status==="info"),v=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(k=>`${k.namespace.prefix}${k.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.`)+v}}let a=Me(),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:ge(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),o=s(p=>r.findings.filter(f=>f.status===p),"of"),i=o("open"),a=o("warn"),c=o("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=i.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:c.length,findings:[...i,...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 ${i.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${i.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=ge(n.dir),o,i;if(r!==void 0){let u=po(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."};o=u.repoRoot,i=u.repoRelDir===""?void 0:[u.repoRelDir]}else o=Me(),i=void 0;let a=Vn(o,{dirs:i,baseRef:ge(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:o,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:o,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=nS(ge(n.dir));if(r===null)return rS("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=Wn(r.repoRoot,{dirs:r.scanDirs,baseRef:ge(n.base_ref),includeBaseline:n.include_baseline!==!1}),i="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(o.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=o.findings.filter(l=>l.status==="open"),c=o.findings.filter(l=>l.status==="info");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,base_ref:o.facts.baseRef,projects:o.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:o.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.`)+" "+i}}case"check_migration_ledger_drift":{let r=nS(ge(n.dir));if(r===null)return rS("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=du(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:ge(n.remote_db_url)}),i=o.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(o.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:o.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=>o.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=i.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:o.ok,verdict:o.verdict,repo_root:r.repoRoot,projects:i,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:o.facts.remoteConsulted,skipped:o.facts.skipped,database_targets:u,hint:(o.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:o.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=ge(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:ge(n.kind),limit:hr(n.limit)})).map(i=>({...i,nodeKeyHash:Rc(i.nodeKey)}))}case"codebase_trace":{let r=ge(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let o=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:o,maxDepth:hr(n.max_depth),limit:hr(n.limit)})}case"codebase_snippet":{let r=ge(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let o=await e.getCodeSnippet(r);if(!o)throw new Error(`no symbol found for node_key: ${r}`);return{...o,nodeKeyHash:Rc(r)}}case"codebase_map":return e.getArchitecture({topN:hr(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:ge(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:hr(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language,file:o.filePath,start_line:o.startLine,node_key:o.nodeKey,node_key_hash:Rc(o.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.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:ge(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:hr(n.limit)}),o;if(n.include_history!==!1)try{o=Jl(await e.fileHistory({since:ge(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:ge(n.since)})}catch(l){i=Ve(Nt(`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:i.coverage},c=i.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:Rc(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,...o?{history:o}:{}},verdict_args:{detector_findings:i.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:i.coverage,truncated:i.truncated,block_eligible:c,engines:i.engines,findings:i.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 ${i.findings.length} detector row(s) (${c} block-eligible, coverage ${i.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(i=>typeof i=="string"):void 0,o=await e.fileHistory({paths:r,since:ge(n.since),limit:hr(n.limit),includeOwnership:n.include_ownership!==!1});return{history:o.history.map(i=>({path:i.path,last_commits:i.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:i.ownership?{top_authors:i.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:i.ownership.commitsInWindow}:null})),regression:o.regression?{since_input:o.regression.sinceInput,since_resolved:o.regression.sinceResolved,truncated:o.regression.truncated,commits:o.regression.commits.map(i=>({sha:i.sha,date_iso:i.dateIso,author_name:i.authorName,subject:i.subject,files_touched:i.filesTouched}))}:null,ownership_window_commits:o.ownershipWindowCommits,paths_truncated:o.pathsTruncated,hint:o.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(sS,"dispatchLocalTool");var Cc=class{constructor(t=tx,n=null,r=Me,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return of}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&oS.has(r)}async handleToolCall(t,n){let r=n??{},o=typeof r.name=="string"?r.name:"",i=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=af.has(o)?await iS(this.getEngine(),o,i,this.ctx??void 0):await sS(this.getEngine(),o,i),c=JSON.stringify(a,null,2);return this.recordSavings(o,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=Xk(a)?`${Zk} (${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(i=>i&&typeof i=="object"?i.name:void 0).filter(i=>typeof i=="string")),o=this.descriptors().filter(i=>!r.has(i.name));return n.result.tools=[...n.result.tools,...o],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 o=Bx(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};qr();var t1="/mcp-client-metrics-ingest",n1=4e3,r1="codebase_search_tokens_saved";async function aS(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${di()}${t1}`,n=new AbortController,r=setTimeout(()=>n.abort(),n1);try{let o=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:r1,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await o.text().catch(()=>""),o.ok}catch(o){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${o instanceof Error?o.message:String(o)}
1123
- `),!1}finally{clearTimeout(r)}}s(aS,"postSavingsMetric");df();ji();Oo();pe();import{existsSync as k1,readFileSync as x1,readdirSync as S1,statSync as E1}from"node:fs";import{dirname as R1,join as Hi,resolve as pf}from"node:path";var C1=8,T1=128;function A1(e){return S1(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>t.name).sort()}s(A1,"defaultListDirs");function I1(e){let t=Hi(e,".git");if(!k1(t))return null;if(E1(t).isDirectory())return{isDir:!0,gitdir:null};let n=/^gitdir:\s*(.+)\s*$/m.exec(x1(t,"utf8"));return{isDir:!1,gitdir:n?pf(e,n[1].trim()):null}}s(I1,"defaultGitKind");function N1(e){let t=`${Hi(".git","worktrees")}`,n=e.lastIndexOf(t);return n>0?R1(Hi(e.slice(0,n),".git")):null}s(N1,"mainCheckoutOf");function bS(e,t,n={}){try{let r=n.listDirs??A1,o=n.gitKind??I1,i=n.keyOf??yt,a=r(e).slice(0,T1),c=new Set,l=new Map;for(let u of a)try{let p=o(Hi(e,u));if(p===null)continue;l.set(u,p),p.isDir&&c.add(pf(e,u))}catch{}let d=new Map;for(let[u,p]of l){if(!p.isDir&&p.gitdir!==null){let g=N1(p.gitdir);if(g!==null&&c.has(pf(g)))continue}let f=null;try{f=i(Hi(e,u))}catch{f=null}if(f===null||f===t)continue;let h=d.get(f);(!h||p.isDir&&!h.isDir)&&d.set(f,{dir:u,isDir:p.isDir})}return[...d].map(([u,p])=>({dir:p.dir,projectKey:u})).sort((u,p)=>u.dir.localeCompare(p.dir)).slice(0,C1)}catch{return[]}}s(bS,"discoverNestedRepos");Dt();Ic();rr();import{join as Z1}from"node:path";var Q1="<synthetic>";function CS(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:Z1(_p,bp(e.cwd),`${e.transcript_stem}.jsonl`)}s(CS,"transcriptPathFromSideChannel");var Nc=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 o=await(this.deps.stream??yp)(n,{start:this.offset});for(let i of o.events)if(i.kind==="title"){let a=i.title.trim();a.length>0&&(this.title=a)}else i.kind==="assistant"&&!i.isSidechain&&typeof i.model=="string"&&i.model.length>0&&i.model!==Q1&&(this.model=i.model);o.bytesRead>this.offset&&(this.offset=o.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 eH}from"node:child_process";var tH=8,nH=32;function rH(e){return e.split(`
1124
- `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,nH)}s(rH,"parsePorcelain");function oH(e,t=tH){let n=[];for(let r of e){let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(o.length===0)continue;let i=o.includes("/")?o.slice(0,o.lastIndexOf("/")):o;if(!(i.length===0||n.includes(i))&&(n.push(i),n.length>=t))break}return n}s(oH,"condenseToDirs");async function TS(e=iH){let t=await e();if(t===null)return null;let n=oH(rH(t));return n.length>0?n:null}s(TS,"deriveWorkingPaths");async function iH(){return await new Promise(e=>{eH("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(iH,"defaultGitStatus");var mf=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],sH=["install","refresh-rules","doctor","on-session-end","session-end-run","on-session-briefing","on-session-reminder","on-cursor-session-start","guard","guard-inject","guard-gate","guard-stop","guard-difficulty","guard-outcome","guard-capture","gateway","guard-cross-observe","guard-cross-check","on-index-refresh","index-refresh-run","on-prompt-context","on-read-context",...mf],aH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function hf(e){return e.find(t=>!t.startsWith("-"))}s(hf,"firstPositionalOf");function AS(e){let t=hf(e);return t===void 0||!aH.test(t)||sH.includes(t)?null:`maind-mcp-bridge: unknown subcommand "${t}" \u2014 this bridge does not have it (an older version?). Run \`maind-mcp-bridge --help\` for the list.`}s(AS,"unknownSubcommandError");var BW=1;function KW(e){return mf.includes(e)}s(KW,"isHookSubcommand");var GW=6e4;async function WW(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==z()&&Jn(e),e;let t=z();if(t!==null)return t;let n=await zr(H);return n===null&&(Yn("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:H}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1125
- `),process.exit(1)),Yn("paired",null,{version:H}),n.apiKey}s(WW,"ensureApiKey");async function VW(e){let t=await zr(H);return t===null&&(Yn("auth_failed",`${e}; re-authorization did not complete`,{version:H}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1126
- `),process.exit(1)),Yn("paired",null,{version:H}),t.apiKey}s(VW,"reauth");async function qW(){let e=hf(process.argv.slice(2)),t=AS(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1127
- `),process.exit(2)),e==="install"){let x=process.argv.indexOf("install"),T=process.argv.slice(x+1),D=await $x(T);process.exit(D)}if(e==="refresh-rules"){let{runRefreshRules:x}=await Promise.resolve().then(()=>(vc(),Xp));process.exit(await x(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:x}=await Promise.resolve().then(()=>(Af(),cE));process.exit(await x(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:x}=await Promise.resolve().then(()=>($0(),M0));process.exit(await x())}if(e==="session-end-run"){let{runSessionEndWorker:x}=await Promise.resolve().then(()=>(pm(),I0));process.exit(await x())}if(e==="on-session-briefing"){let{runOnSessionBriefing:x}=await Promise.resolve().then(()=>(F0(),L0));process.exit(await x())}if(e==="on-session-reminder"){let{runOnSessionReminder:x}=await Promise.resolve().then(()=>(U0(),H0));process.exit(await x())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:x}=await Promise.resolve().then(()=>(Y0(),J0));process.exit(await x())}if(e==="guard"){let x=process.argv.indexOf("guard"),{runGuard:T}=await Promise.resolve().then(()=>(nR(),tR));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-inject"){let{runGuardInject:x}=await Promise.resolve().then(()=>(pr(),kx));process.exit(await x())}if(e==="guard-gate"){let{runGuardGate:x}=await Promise.resolve().then(()=>(dR(),lR));process.exit(await x())}if(e==="guard-stop"){let{runGuardStop:x}=await Promise.resolve().then(()=>(fR(),pR));process.exit(await x())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:x}=await Promise.resolve().then(()=>(gm(),iR));process.exit(await x())}if(e==="guard-capture"){let{runGuardCapture:x}=await Promise.resolve().then(()=>(yR(),gR));process.exit(await x())}if(e==="gateway"){let x=process.argv.indexOf("gateway"),{runGateway:T}=await Promise.resolve().then(()=>(tC(),eC));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:x}=await Promise.resolve().then(()=>(Im(),Am));process.exit(await x())}if(e==="guard-cross-check"){let{runGuardCrossCheck:x}=await Promise.resolve().then(()=>(Im(),Am));process.exit(await x())}if(e==="on-index-refresh"){let{runOnIndexRefresh:x}=await Promise.resolve().then(()=>(Om(),Nm));process.exit(await x())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:x}=await Promise.resolve().then(()=>(Om(),Nm));process.exit(await x())}if(e==="on-prompt-context"){let{runOnPromptContext:x}=await Promise.resolve().then(()=>(jm(),Fm));process.exit(await x())}if(e==="on-read-context"){let{runOnReadContext:x}=await Promise.resolve().then(()=>(jm(),Fm));process.exit(await x())}if(e!==void 0&&KW(e)){let x=await Promise.resolve().then(()=>(Qi(),QE)),T={"on-session-start":x.runOnSessionStart,"on-tool-use":x.runOnToolUse,"on-file-write":x.runOnFileWrite,"on-file-edit":x.runOnFileEdit,"on-repo-health":x.runOnRepoHealth,"on-write-health":x.runOnWriteHealth,"sync-config":x.runSyncConfig,flush:x.runFlush,status:x.runHookStatus}[e];process.exit(await T())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(H+`
1128
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(zW(),process.exit(0)),process.argv.includes("--reauth")&&(li(),await zr(H,process.stdout)===null&&process.exit(1),Yn("paired",null,{version:H}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1129
- `),process.exit(0));let n=ae(),r=await WW(),o=ne(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new xc:null,c=null,l=new Map,d=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Cc(void 0,a,void 0,{callCloudTool:s((x,T,D)=>c===null?Promise.resolve({kind:"no_session"}):c.callCloudTool(x,T,D),"callCloudTool"),projectKey:o,engineFor:s(x=>{let T=l.get(x);return T===void 0&&(T=nx(x),l.set(x,T)),T},"engineFor"),projectKeyFor:yt}),u=`bridge-${UW()}`,p=s(async()=>{if(!a)return;let x=a.takePending();x.tokens<=0||await aS({apiKey:r,deviceId:n,sessionId:u,tokensSaved:x.tokens,bridgeVersion:H})},"flushSavings"),f=a?setInterval(()=>{p()},GW):null;f?.unref();let h=new Ac({projectKey:o}),g=new Nc({resolvePath:s(()=>CS(h.sideChannel()),"resolvePath"),fallbackModel:s(()=>h.sideChannel()?.model??null,"fallbackModel")}),y=new ds,_=null,b=s(()=>(_===null&&(_=o!==null?bS(ot(),o):[]),_),"nestedRepos"),v=s(x=>b().find(T=>T.projectKey===x)?.dir??null,"nestedDirOf"),k=new Tc({projectKey:o,identity:h,sessionMeta:s(()=>g.read(),"sessionMeta"),postToolCall:s((x,T)=>c===null?Promise.reject(new Error("presence: no active forwarder")):c.postPresenceToolCall(x,T),"postToolCall"),deriveWorkingPaths:s(()=>TS(),"deriveWorkingPaths"),snapshot:o!==null?JW(_S({projectKey:o}),y,v):void 0,nestedProjectKeys:s(()=>b().map(x=>x.projectKey),"nestedProjectKeys")}),E=k.isEnabled?setInterval(()=>{k.pollActivity()},dS):null;if(E?.unref(),k.isEnabled){let x=s(T=>{k.end().finally(()=>process.exit(T))},"endAndExit");process.on("SIGTERM",()=>x(143)),process.on("SIGINT",()=>x(130))}let S=!1,R=s(x=>{if(S)return;S=!0;let T=s(()=>c?.listClientRoots()??Promise.resolve(null),"listRoots");setTimeout(()=>{Promise.resolve().then(()=>(yc(),Ix)).then(({refreshAgentsMdForSession:F})=>F(x,{apiKey:r,projectKey:o,listRoots:T})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(vc(),Xp))).then(({refreshRulesForSession:F})=>F(x,{apiKey:s(()=>r,"apiKey"),listRoots:T})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),P=0,K=Eu();try{for(;;){let x=c?.carryOver()??null,T=new sa({apiKey:r,deviceId:n,bridgeVersion:H,projectKey:o,localRouter:d,presence:k,onConnectionOutcome:s((D,F)=>Yn(D,F,{version:H}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:D})=>R(D),"onSessionReady"),assignedInbox:y,carry:x});c=T;try{await T.run(K);return}catch(D){if(D instanceof ci&&P<BW){P+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${D.message}; re-authorizing\u2026
1130
- `),r=await VW(D.reason);continue}throw D}}}finally{f&&clearInterval(f),E&&clearInterval(E),await k.end(),await p()}}s(qW,"main");function zW(){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, hooks, user-level rule files; --team: AGENTS.md + .mcp.json)"," 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 doctor --migrate-repo-blocks [--yes]"," # list (then remove) the maind blocks earlier installs wrote into this repository"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-mcp [--yes]"," # with the Claude Code plugin maind: list (then remove) the second maind server in ~/.claude.json"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-hooks [--yes]"," # with the Claude Code plugin maind: list (then remove) the bridge's own hooks in settings.json"," npx -y @maind-dev/mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]"," # refresh the user-level rule files with the conventions of <dir>'s repository"," 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 close the tracked session, queue analytics + cost upload for a detached run (MAIND-633)"," 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)","Codex: `install` wires on-session-briefing --host=codex into Codex's config.toml where Codex is installed;"," it answers in Codex's JSON (hookSpecificOutput.additionalContext \u2014 ADR-364)","","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 team conventions block in AGENTS.md (install --team; ADR-364 E4)"," MAIND_NO_RULES_REFRESH Set to 1 to stop refreshing the user-level rule files (Copilot, Cline, Continue; ADR-364 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(`
1131
- `))}s(zW,"printHelp");qW().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1132
- `),process.exit(1)});function JW(e,t,n){return{...e,write(r,o){let i=r;try{i=Km(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(JW,"withAssignedCapture");
1122
+ `)}s(xu,"collectSseText");function ia(e){try{return JSON.parse(e).id??null}catch{return null}}s(ia,"tryExtractId");function Wr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Wr,"isInitializeRequest");function Wb(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(Wb,"isSessionLossBody");function Vb(e){return e instanceof Error?e.message:String(e)}s(Vb,"stringifyErr");function bD(e){return e?.name==="TimeoutError"}s(bD,"isTimeoutError");function sa(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
1123
+ `)}s(sa,"emitJsonRpcError");function wD(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(wD,"extractHint");function vD(e){try{let t=bl(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(vD,"parsePresenceToolResult");re();Au();Iu();Fe();pe();ef();hn();hn();import{readFileSync as Dj}from"node:fs";import{join as Hx}from"node:path";function xc(e){return e?Math.ceil(e.length/4):0}s(xc,"estimateTokens");var Ux=1e6,Sc=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 Bx(e){try{let t=Dj(e,"utf8");return t.length>Ux?t.slice(0,Ux):t}catch{return""}}s(Bx,"readFileCapped");function Pj(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(Pj,"distinctFilePaths");function Kx(e,t,n,r){try{let o=xc(n);if(e==="codebase_search"){let i=Pj(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=xc(Bx(Hx(r,c)));return Math.max(0,a-o)}if(e==="codebase_snippet"){let i=t?.filePath;if(typeof i!="string"||i.length===0)return 0;let a=xc(Bx(Hx(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(Kx,"measureLocalToolSaved");tn();hn();import{createHash as t1}from"node:crypto";tn();import{execFileSync as Fj}from"node:child_process";import{createHash as jj}from"node:crypto";hn();tf();import{realpathSync as Jx}from"node:fs";function Hj(e,t){try{return Jx(e)===Jx(t)}catch{return e===t}}s(Hj,"samePath");var nf=30,Uj=10,Yx=20,Bj=new Map;function rf(e){return e instanceof Error?e.message:String(e)}s(rf,"msg");function Rc(e){let t=e.split(`
1124
+ `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Rc,"firstLine");var Xx=s(e=>e?e.slice(0,12):"?","short");async function Kj(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await zx(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:rf(c)}}},n);return a.locked?a.value.ok?i?(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}:(i||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:i}):(i||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:i})}s(Kj,"refreshIndex");function Gj(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(Gj,"isEmptyRange");function Wj(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(Wj,"localOnly");function Vj(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(Vj,"localGradeBlockers");function qj(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=_u(!1,e.projectKey,e.result);if(!t.persist)return t;let n=Vj(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(qj,"bridgePersistDecision");function Zx(e,t){try{return Fj("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(Zx,"git");function zj(e,t){let n=Vo(e),r=n&&Zx(e,["merge-base",t,`origin/${n}`])||null,o=Zx(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(zj,"gitPersistFacts");function Jj(e,t){return jj("sha256").update(`${e??""}
1125
+ ${JSON.stringify(t)}`).digest("hex")}s(Jj,"payloadKey");function ct(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(ct,"fail");var mr="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Qx(e){let t=wu(e);if(t!==null&&vu(t))return ct("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 ct("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 ct("cloud_unavailable",`review_verdict failed: ${Rc(t?.detail??e)||"no detail"}`,mr)}s(Qx,"fromProtocolText");function Yj(e,t,n){switch(e.kind){case"no_session":return ct("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. ${mr}`);case"transport_error":return e.timedOut?ct("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."):ct("cloud_unavailable",`network error: ${e.message}`,mr);case"http_error":return e.status===401?ct("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Rc(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?ct("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."):ct("cloud_unavailable",`HTTP ${e.status}: ${Rc(e.body)}`,mr);case"rpc_error":return Qx(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Qx(e.text);let r;try{r=JSON.parse(e.text)}catch{return ct("cloud_unavailable",`review_verdict returned non-JSON text: ${Rc(e.text)}`,mr)}return typeof r!="object"||r===null?ct("cloud_unavailable","review_verdict returned no object",mr):{kind:"verdict",body:r}}}}s(Yj,"interpretOutcome");var Xj="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).",Zj={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"},eS=s(e=>e.map(t=>Zj[t]??t).join("; "),"adviceFor");function Qj(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: ${eS(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,o]=t??[];return`the reviewed range starts at ${Xx(n)}, but this branch forks off ${o??"the default branch"} at ${Xx(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${o??"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(Qj,"skipText");function e1(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=eS(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let o=e.reason??"",i=Qj(o,e.detail),a=t===!0&&o!=="no_report"?" The run itself is attestation-grade.":"";return i!==null?`Not recorded: ${i}${a}`:`Not recorded (${o||"the server gave no reason"}).${a}`}s(e1,"recordHint");async function tS(e,t,n){let r=n.repoRoot??Me(),o=r,i=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let le=po(c,r);if(le===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(!Hj(le.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."};o=le.repoRoot,i=n.engineFor(o),a=n.projectKeyFor?.(o)??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??Bj,h=[],g=await Kj(i,o,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 i.reviewChanges(gu(l,d)),_={repo_root:o,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(Gj(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:h};let b;try{b=await i.reviewDetectorScopes({baseRef:l})}catch(le){let Hm=Ve(Ot(`reviewDetectorScopes failed: ${rf(le)}`));b={commit:Hm,local:Hm},h.push(`repo-health detectors unavailable (${rf(le)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:v,dropped:k}=yu(y,b.commit);k>0&&h.push(`${k} symbol(s) exceed the server schema (name > ${ta} or qualified name > ${na} chars) and were left out \u2014 this run is not attestation-grade.`);let E=Jj(a,v),S=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",R=qj({persistWanted:u,since:l,projectKey:a,result:y,payload:v,git:S?(n.persistFacts??zj)(o,y.headSha):null,recordedRunId:f.get(E)??null}),P={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:v.changed_symbols.length,symbols_dropped:k,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,Yx),local_only:Wj(b).slice(0,Yx)}},K=await n.callCloudTool("review_verdict",{attest:v,persist:R.persist,...a?{project_key:a}:{}},{timeoutMs:p}),x=Yj(K,p,R.persist);if(x.kind==="error")return{ok:!1,error:x.error,message:x.message,hint:x.hint,base:_,local:P,warnings:h};let T=x.body;if(T.ok!==!0){let le=T.error==="requires_team"||T.error==="requires_enterprise";return{ok:!1,error:T.error??"unknown_error",message:T.message??"review_verdict returned no message",hint:le?Xj:T.hint??mr,base:_,local:P,warnings:h}}if(T.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:P,warnings:h};let D=T.attest,F=T.run??null,xt=F&&typeof F.id=="string"?{persisted:!0,run_id:F.id,commit_sha:F.commit_sha??null,attestation_format:F.attestation_format??null}:{persisted:!1,reason:R.skipped??T.run_note??"not_persisted",...R.detail?{detail:R.detail}:{}};xt.persisted&&f.set(E,F.id);let cs=typeof D?.attestation_grade=="boolean"?D.attestation_grade:null,Io=Array.isArray(D?.grade_blockers)?D.grade_blockers:[],X=T.counts??{},Qe=Array.isArray(T.findings)?T.findings:[],ls=`Verdict ${T.verdict??"?"}: ${X.block??0} block, ${X.warn??0} warn, ${X.note??0} note`+(T.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:T.verdict??null,counts:X,record:xt,attest:D?{attestation_grade:cs,grade_blockers:Io,attestation_format:D.attestation_format??null,input_hash:D.input_hash??null,policy_hash:D.policy_hash??null,evaluated_convention_count:D.evaluated_convention_count??null,detector_coverage:D.detector_coverage??null}:null,hint:`${ls} ${e1(xt,cs,Io,y.headSha)}`,findings:Qe.slice(0,nf).map(le=>({convention_id:le.convention_id,convention_version:le.convention_version,severity:le.severity,action:le.action,...le.downgrade_reason?{downgrade_reason:le.downgrade_reason}:{},summary:le.summary,matched_changed_symbols:(le.matched_changed_symbols??[]).slice(0,Uj),matched_symbol_count:le.matched_symbols?.length??0})),...Qe.length>nf?{findings_not_shown:Qe.length-nf}:{},detector_findings:T.detector_findings??[],policy_source:T.policy_source??null,coverage_note:bu(y,D?.evaluated_convention_count,k),base:_,local:P,warnings:h}}s(tS,"runAttestReview");var nS=(()=>{let e=Object.keys(Zo),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Cc(e){return t1("sha256").update(e,"utf8").digest("hex")}s(Cc,"nodeKeyHash");var n1=["module","class","interface","function","method","type_alias","enum","variable"],of=[{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:n1,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 "+nS+" \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 "+nS+", 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."}}}}],sf=new Map([["codebase_review_verdict","attest_review_changes"]]),iS=new Set([...of.map(e=>e.name),...sf.keys()]),af=new Set(["attest_review_changes",...[...sf].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function sS(e,t,n,r){if(!af.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 o=await tS(e,n,r),i=sf.get(t);return i?{...o,renamed:{from:t,to:i,note:`${t} is ${i} since bridge 0.79.0 \u2014 call ${i}; the old name goes in a later minor.`}}:o}s(sS,"dispatchCloudBackedTool");function ge(e){return typeof e=="string"&&e.length>0?e:void 0}s(ge,"str");function hr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(hr,"num");function rS(e){if(e===void 0)return{repoRoot:Me(),scanDirs:void 0};let t=po(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(rS,"anchorRepo");function oS(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(oS,"dirNotFound");async function aS(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 o=r.findings.filter(a=>a.status==="open").length,i=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:o,warn_count:i,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${o} blocking (open) + ${i} 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,o=ge(n.for_path);if(o!==void 0){let u=ex(o);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:o,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 Kn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,h=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:h(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let i=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(i!==void 0&&i.length>0){let u=new Map,p=[];for(let k of i){let E=po(k);if(E===null){p.push(k);continue}let S=u.get(E.repoRoot)??new Set;S.add(E.repoRelDir),u.set(E.repoRoot,S)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],h=[],g=[],y=[];for(let[k,E]of u){let S=[...E],R=S.includes(""),P=await Bn(k,{dirs:R?void 0:S,minFiles:r});f.push({repo_root:k,dirs:R?null:S}),h.push(...P.findings),g.push(...P.facts.namespaces.map(K=>({repo_root:k,dir:K.dir,prefix:K.prefix,file_count:K.fileCount}))),y.push(...P.facts.skipped)}let _=h.filter(k=>k.status==="open"),b=h.filter(k=>k.status==="info"),v=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(k=>`${k.namespace.prefix}${k.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.`)+v}}let a=Me(),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:ge(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),o=s(p=>r.findings.filter(f=>f.status===p),"of"),i=o("open"),a=o("warn"),c=o("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=i.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:c.length,findings:[...i,...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 ${i.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${i.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=ge(n.dir),o,i;if(r!==void 0){let u=po(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."};o=u.repoRoot,i=u.repoRelDir===""?void 0:[u.repoRelDir]}else o=Me(),i=void 0;let a=Vn(o,{dirs:i,baseRef:ge(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:o,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:o,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=rS(ge(n.dir));if(r===null)return oS("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=Wn(r.repoRoot,{dirs:r.scanDirs,baseRef:ge(n.base_ref),includeBaseline:n.include_baseline!==!1}),i="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(o.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=o.findings.filter(l=>l.status==="open"),c=o.findings.filter(l=>l.status==="info");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,base_ref:o.facts.baseRef,projects:o.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:o.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.`)+" "+i}}case"check_migration_ledger_drift":{let r=rS(ge(n.dir));if(r===null)return oS("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=du(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:ge(n.remote_db_url)}),i=o.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(o.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:o.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=>o.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=i.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:o.ok,verdict:o.verdict,repo_root:r.repoRoot,projects:i,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:o.facts.remoteConsulted,skipped:o.facts.skipped,database_targets:u,hint:(o.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:o.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=ge(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:ge(n.kind),limit:hr(n.limit)})).map(i=>({...i,nodeKeyHash:Cc(i.nodeKey)}))}case"codebase_trace":{let r=ge(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let o=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:o,maxDepth:hr(n.max_depth),limit:hr(n.limit)})}case"codebase_snippet":{let r=ge(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let o=await e.getCodeSnippet(r);if(!o)throw new Error(`no symbol found for node_key: ${r}`);return{...o,nodeKeyHash:Cc(r)}}case"codebase_map":return e.getArchitecture({topN:hr(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:ge(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:hr(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language,file:o.filePath,start_line:o.startLine,node_key:o.nodeKey,node_key_hash:Cc(o.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.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:ge(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:hr(n.limit)}),o;if(n.include_history!==!1)try{o=Jl(await e.fileHistory({since:ge(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:ge(n.since)})}catch(l){i=Ve(Ot(`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:i.coverage},c=i.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:Cc(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,...o?{history:o}:{}},verdict_args:{detector_findings:i.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:i.coverage,truncated:i.truncated,block_eligible:c,engines:i.engines,findings:i.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 ${i.findings.length} detector row(s) (${c} block-eligible, coverage ${i.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(i=>typeof i=="string"):void 0,o=await e.fileHistory({paths:r,since:ge(n.since),limit:hr(n.limit),includeOwnership:n.include_ownership!==!1});return{history:o.history.map(i=>({path:i.path,last_commits:i.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:i.ownership?{top_authors:i.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:i.ownership.commitsInWindow}:null})),regression:o.regression?{since_input:o.regression.sinceInput,since_resolved:o.regression.sinceResolved,truncated:o.regression.truncated,commits:o.regression.commits.map(i=>({sha:i.sha,date_iso:i.dateIso,author_name:i.authorName,subject:i.subject,files_touched:i.filesTouched}))}:null,ownership_window_commits:o.ownershipWindowCommits,paths_truncated:o.pathsTruncated,hint:o.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(aS,"dispatchLocalTool");var Tc=class{constructor(t=nx,n=null,r=Me,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return of}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&iS.has(r)}async handleToolCall(t,n){let r=n??{},o=typeof r.name=="string"?r.name:"",i=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=af.has(o)?await sS(this.getEngine(),o,i,this.ctx??void 0):await aS(this.getEngine(),o,i),c=JSON.stringify(a,null,2);return this.recordSavings(o,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=Zk(a)?`${Qk} (${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(i=>i&&typeof i=="object"?i.name:void 0).filter(i=>typeof i=="string")),o=this.descriptors().filter(i=>!r.has(i.name));return n.result.tools=[...n.result.tools,...o],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 o=Kx(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};qr();var r1="/mcp-client-metrics-ingest",o1=4e3,i1="codebase_search_tokens_saved";async function cS(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${di()}${r1}`,n=new AbortController,r=setTimeout(()=>n.abort(),o1);try{let o=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:i1,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await o.text().catch(()=>""),o.ok}catch(o){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${o instanceof Error?o.message:String(o)}
1126
+ `),!1}finally{clearTimeout(r)}}s(cS,"postSavingsMetric");df();ji();Oo();pe();import{existsSync as S1,readFileSync as E1,readdirSync as R1,statSync as C1}from"node:fs";import{dirname as T1,join as Hi,resolve as pf}from"node:path";var A1=8,I1=128;function N1(e){return R1(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>t.name).sort()}s(N1,"defaultListDirs");function O1(e){let t=Hi(e,".git");if(!S1(t))return null;if(C1(t).isDirectory())return{isDir:!0,gitdir:null};let n=/^gitdir:\s*(.+)\s*$/m.exec(E1(t,"utf8"));return{isDir:!1,gitdir:n?pf(e,n[1].trim()):null}}s(O1,"defaultGitKind");function D1(e){let t=`${Hi(".git","worktrees")}`,n=e.lastIndexOf(t);return n>0?T1(Hi(e.slice(0,n),".git")):null}s(D1,"mainCheckoutOf");function wS(e,t,n={}){try{let r=n.listDirs??N1,o=n.gitKind??O1,i=n.keyOf??yt,a=r(e).slice(0,I1),c=new Set,l=new Map;for(let u of a)try{let p=o(Hi(e,u));if(p===null)continue;l.set(u,p),p.isDir&&c.add(pf(e,u))}catch{}let d=new Map;for(let[u,p]of l){if(!p.isDir&&p.gitdir!==null){let g=D1(p.gitdir);if(g!==null&&c.has(pf(g)))continue}let f=null;try{f=i(Hi(e,u))}catch{f=null}if(f===null||f===t)continue;let h=d.get(f);(!h||p.isDir&&!h.isDir)&&d.set(f,{dir:u,isDir:p.isDir})}return[...d].map(([u,p])=>({dir:p.dir,projectKey:u})).sort((u,p)=>u.dir.localeCompare(p.dir)).slice(0,A1)}catch{return[]}}s(wS,"discoverNestedRepos");Pt();Nc();rr();import{join as eH}from"node:path";var tH="<synthetic>";function TS(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:eH(_p,bp(e.cwd),`${e.transcript_stem}.jsonl`)}s(TS,"transcriptPathFromSideChannel");var Oc=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 o=await(this.deps.stream??yp)(n,{start:this.offset});for(let i of o.events)if(i.kind==="title"){let a=i.title.trim();a.length>0&&(this.title=a)}else i.kind==="assistant"&&!i.isSidechain&&typeof i.model=="string"&&i.model.length>0&&i.model!==tH&&(this.model=i.model);o.bytesRead>this.offset&&(this.offset=o.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 nH}from"node:child_process";var rH=8,oH=32;function iH(e){return e.split(`
1127
+ `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,oH)}s(iH,"parsePorcelain");function sH(e,t=rH){let n=[];for(let r of e){let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(o.length===0)continue;let i=o.includes("/")?o.slice(0,o.lastIndexOf("/")):o;if(!(i.length===0||n.includes(i))&&(n.push(i),n.length>=t))break}return n}s(sH,"condenseToDirs");async function AS(e=aH){let t=await e();if(t===null)return null;let n=sH(iH(t));return n.length>0?n:null}s(AS,"deriveWorkingPaths");async function aH(){return await new Promise(e=>{nH("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(aH,"defaultGitStatus");var mf=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],cH=["install","refresh-rules","doctor","on-session-end","session-end-run","on-session-briefing","on-session-reminder","on-cursor-session-start","guard","guard-inject","guard-gate","guard-stop","guard-difficulty","guard-outcome","guard-capture","gateway","guard-cross-observe","guard-cross-check","on-index-refresh","index-refresh-run","on-prompt-context","on-read-context",...mf],lH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function hf(e){return e.find(t=>!t.startsWith("-"))}s(hf,"firstPositionalOf");function IS(e){let t=hf(e);return t===void 0||!lH.test(t)||cH.includes(t)?null:`maind-mcp-bridge: unknown subcommand "${t}" \u2014 this bridge does not have it (an older version?). Run \`maind-mcp-bridge --help\` for the list.`}s(IS,"unknownSubcommandError");var GW=1;function WW(e){return mf.includes(e)}s(WW,"isHookSubcommand");var VW=6e4;async function qW(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==z()&&Jn(e),e;let t=z();if(t!==null)return t;let n=await zr(H);return n===null&&(Yn("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:H}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1128
+ `),process.exit(1)),Yn("paired",null,{version:H}),n.apiKey}s(qW,"ensureApiKey");async function zW(e){let t=await zr(H);return t===null&&(Yn("auth_failed",`${e}; re-authorization did not complete`,{version:H}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1129
+ `),process.exit(1)),Yn("paired",null,{version:H}),t.apiKey}s(zW,"reauth");async function JW(){let e=hf(process.argv.slice(2)),t=IS(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1130
+ `),process.exit(2)),e==="install"){let x=process.argv.indexOf("install"),T=process.argv.slice(x+1),D=await Lx(T);process.exit(D)}if(e==="refresh-rules"){let{runRefreshRules:x}=await Promise.resolve().then(()=>(kc(),Xp));process.exit(await x(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:x}=await Promise.resolve().then(()=>(Af(),lE));process.exit(await x(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:x}=await Promise.resolve().then(()=>(L0(),$0));process.exit(await x())}if(e==="session-end-run"){let{runSessionEndWorker:x}=await Promise.resolve().then(()=>(pm(),N0));process.exit(await x())}if(e==="on-session-briefing"){let{runOnSessionBriefing:x}=await Promise.resolve().then(()=>(j0(),F0));process.exit(await x())}if(e==="on-session-reminder"){let{runOnSessionReminder:x}=await Promise.resolve().then(()=>(B0(),U0));process.exit(await x())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:x}=await Promise.resolve().then(()=>(X0(),Y0));process.exit(await x())}if(e==="guard"){let x=process.argv.indexOf("guard"),{runGuard:T}=await Promise.resolve().then(()=>(rR(),nR));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-inject"){let{runGuardInject:x}=await Promise.resolve().then(()=>(pr(),xx));process.exit(await x())}if(e==="guard-gate"){let{runGuardGate:x}=await Promise.resolve().then(()=>(uR(),dR));process.exit(await x())}if(e==="guard-stop"){let{runGuardStop:x}=await Promise.resolve().then(()=>(mR(),fR));process.exit(await x())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:x}=await Promise.resolve().then(()=>(gm(),sR));process.exit(await x())}if(e==="guard-capture"){let{runGuardCapture:x}=await Promise.resolve().then(()=>(_R(),yR));process.exit(await x())}if(e==="gateway"){let x=process.argv.indexOf("gateway"),{runGateway:T}=await Promise.resolve().then(()=>(nC(),tC));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:x}=await Promise.resolve().then(()=>(Im(),Am));process.exit(await x())}if(e==="guard-cross-check"){let{runGuardCrossCheck:x}=await Promise.resolve().then(()=>(Im(),Am));process.exit(await x())}if(e==="on-index-refresh"){let{runOnIndexRefresh:x}=await Promise.resolve().then(()=>(Om(),Nm));process.exit(await x())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:x}=await Promise.resolve().then(()=>(Om(),Nm));process.exit(await x())}if(e==="on-prompt-context"){let{runOnPromptContext:x}=await Promise.resolve().then(()=>(jm(),Fm));process.exit(await x())}if(e==="on-read-context"){let{runOnReadContext:x}=await Promise.resolve().then(()=>(jm(),Fm));process.exit(await x())}if(e!==void 0&&WW(e)){let x=await Promise.resolve().then(()=>(Qi(),e0)),T={"on-session-start":x.runOnSessionStart,"on-tool-use":x.runOnToolUse,"on-file-write":x.runOnFileWrite,"on-file-edit":x.runOnFileEdit,"on-repo-health":x.runOnRepoHealth,"on-write-health":x.runOnWriteHealth,"sync-config":x.runSyncConfig,flush:x.runFlush,status:x.runHookStatus}[e];process.exit(await T())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(H+`
1131
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(YW(),process.exit(0)),process.argv.includes("--reauth")&&(li(),await zr(H,process.stdout)===null&&process.exit(1),Yn("paired",null,{version:H}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1132
+ `),process.exit(0));let n=ae(),r=await qW(),o=ne(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Sc:null,c=null,l=new Map,d=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Tc(void 0,a,void 0,{callCloudTool:s((x,T,D)=>c===null?Promise.resolve({kind:"no_session"}):c.callCloudTool(x,T,D),"callCloudTool"),projectKey:o,engineFor:s(x=>{let T=l.get(x);return T===void 0&&(T=rx(x),l.set(x,T)),T},"engineFor"),projectKeyFor:yt}),u=`bridge-${KW()}`,p=s(async()=>{if(!a)return;let x=a.takePending();x.tokens<=0||await cS({apiKey:r,deviceId:n,sessionId:u,tokensSaved:x.tokens,bridgeVersion:H})},"flushSavings"),f=a?setInterval(()=>{p()},VW):null;f?.unref();let h=new Ic({projectKey:o}),g=new Oc({resolvePath:s(()=>TS(h.sideChannel()),"resolvePath"),fallbackModel:s(()=>h.sideChannel()?.model??null,"fallbackModel")}),y=new ds,_=null,b=s(()=>(_===null&&(_=o!==null?wS(ot(),o):[]),_),"nestedRepos"),v=s(x=>b().find(T=>T.projectKey===x)?.dir??null,"nestedDirOf"),k=new Ac({projectKey:o,identity:h,sessionMeta:s(()=>g.read(),"sessionMeta"),postToolCall:s((x,T)=>c===null?Promise.reject(new Error("presence: no active forwarder")):c.postPresenceToolCall(x,T),"postToolCall"),deriveWorkingPaths:s(()=>AS(),"deriveWorkingPaths"),snapshot:o!==null?XW(bS({projectKey:o}),y,v):void 0,nestedProjectKeys:s(()=>b().map(x=>x.projectKey),"nestedProjectKeys")}),E=k.isEnabled?setInterval(()=>{k.pollActivity()},uS):null;if(E?.unref(),k.isEnabled){let x=s(T=>{k.end().finally(()=>process.exit(T))},"endAndExit");process.on("SIGTERM",()=>x(143)),process.on("SIGINT",()=>x(130))}let S=!1,R=s(x=>{if(S)return;S=!0;let T=s(()=>c?.listClientRoots()??Promise.resolve(null),"listRoots");setTimeout(()=>{Promise.resolve().then(()=>(_c(),Nx)).then(({refreshAgentsMdForSession:F})=>F(x,{apiKey:r,projectKey:o,listRoots:T})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(kc(),Xp))).then(({refreshRulesForSession:F})=>F(x,{apiKey:s(()=>r,"apiKey"),listRoots:T})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),P=0,K=Eu();try{for(;;){let x=c?.carryOver()??null,T=new aa({apiKey:r,deviceId:n,bridgeVersion:H,projectKey:o,localRouter:d,presence:k,onConnectionOutcome:s((D,F)=>Yn(D,F,{version:H}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:D})=>R(D),"onSessionReady"),assignedInbox:y,carry:x});c=T;try{await T.run(K);return}catch(D){if(D instanceof ci&&P<GW){P+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${D.message}; re-authorizing\u2026
1133
+ `),r=await zW(D.reason);continue}throw D}}}finally{f&&clearInterval(f),E&&clearInterval(E),await k.end(),await p()}}s(JW,"main");function YW(){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, hooks, user-level rule files; --team: AGENTS.md + .mcp.json)"," 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 doctor --migrate-repo-blocks [--yes]"," # list (then remove) the maind blocks earlier installs wrote into this repository"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-mcp [--yes]"," # with the Claude Code plugin maind: list (then remove) the second maind server in ~/.claude.json"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-hooks [--yes]"," # with the Claude Code plugin maind: list (then remove) the bridge's own hooks in settings.json"," npx -y @maind-dev/mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]"," # refresh the user-level rule files with the conventions of <dir>'s repository"," 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 close the tracked session, queue analytics + cost upload for a detached run (MAIND-633)"," 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)","Codex: `install` wires on-session-briefing --host=codex into Codex's config.toml where Codex is installed;"," it answers in Codex's JSON (hookSpecificOutput.additionalContext \u2014 ADR-364)","","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 team conventions block in AGENTS.md (install --team; ADR-364 E4)"," MAIND_NO_RULES_REFRESH Set to 1 to stop refreshing the user-level rule files (Copilot, Cline, Continue; ADR-364 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(`
1134
+ `))}s(YW,"printHelp");JW().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1135
+ `),process.exit(1)});function XW(e,t,n){return{...e,write(r,o){let i=r;try{i=Km(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(XW,"withAssignedCapture");