@maind-dev/mcp-bridge 0.102.0 → 0.103.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 xh=Object.defineProperty;var s=(e,t)=>xh(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var n in t)xh(e,n,{get:t[n],enumerable:!0})};import{homedir as OT}from"node:os";import{join as DT}from"node:path";function Cs(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=Bo(r.id),i=Bo(r.key),a=Bo(r.title),c=Bo(r.status);if(!o||!i||!a||!c)continue;let l=r.here===!1?!1:void 0,d=Bo(r.where);if(t.push({id:o,key:i,title:a,status:c,...l===!1?{here:l}:{},...d?{where:d}:{}}),t.length>=PT)break}return t}function Ll(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 Sh(e=OT()){return DT(e,".maind","assigned-told")}function Eh(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 Rh(e){return e==="claude-code"}var PT,Bo,Rs,Ko=w(()=>{"use strict";PT=5,Bo=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Cs,"parseAssignedList");s(Ll,"assignedNoticeText");s(Sh,"assignedToldDir");Rs=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=Cs(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 Ll(t)}};s(Eh,"labelNestedItems");s(Rh,"clientHasHooks")});function Ih(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 Nr(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 Hl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ul(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function Bl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Kl=w(()=>{"use strict";s(Ih,"parseFrame");s(Nr,"denyResult");s(Hl,"toolEvent");s(Ul,"policyEvent");s(Bl,"shaEvent")});import{execFileSync as Dh}from"node:child_process";function Ph(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=WT}function VT(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 BT){let a=r[i];typeof a=="string"&&Nh.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of KT){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Nh.test(l)&&o.push({field:`${i}.${a}`,sha:l})}return o}function qT(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,Oh);for(let o=Oh;o>=GT;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 Or(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function Mh(){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 As(e=process.cwd()){try{let n=Dh("git",["rev-parse","--show-toplevel"],{cwd:e,env:Mh(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function zT(e){return t=>{try{let r=Dh("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Mh(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function Is(e,t){if(t===null)return[];let n=VT(e);if(n.length===0)return[];let r=zT(t),o=[];for(let{field:i,sha:a}of n){let c=qT(a,r);c.verdict!=="proven"&&o.push({...c,field:i})}return o}var BT,KT,Nh,GT,Oh,WT,Gl=w(()=>{"use strict";BT=["commit_sha","base_sha","head_sha"],KT=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Nh=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,GT=7,Oh=12,WT=10;s(Ph,"isDenyGrade");s(VT,"extractShaArgs");s(qT,"classifySha");s(Or,"shaFindingText");s(Mh,"cleanGitEnv");s(As,"resolveRepoRootForSha");s(zT,"gitShaResolver");s(Is,"inspectLineForShas")});var Lh=w(()=>{"use strict"});var G,Vl,N,gt,Go=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})})(Vl||(Vl={}));N=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gt=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,JT,Ne,Ns=w(()=>{Go();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"]),JT=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),Ne=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()}};Ne.create=e=>new Ne(e)});var YT,It,ql=w(()=>{Ns();Go();YT=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"),It=YT});function XT(e){jh=e}function Dr(){return jh}var jh,Os=w(()=>{ql();jh=It;s(XT,"setErrorMap");s(Dr,"getErrorMap")});function A(e,t){let n=Dr(),r=Wo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===It?void 0:It].filter(o=>!!o)});e.common.issues.push(r)}var Wo,ZT,fe,M,On,be,Ds,Ps,Zt,Pr,zl=w(()=>{Os();ql();Wo=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"),ZT=[];s(A,"addIssueToContext");fe=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"}),On=s(e=>({status:"dirty",value:e}),"DIRTY"),be=s(e=>({status:"valid",value:e}),"OK"),Ds=s(e=>e.status==="aborted","isAborted"),Ps=s(e=>e.status==="dirty","isDirty"),Zt=s(e=>e.status==="valid","isValid"),Pr=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Fh=w(()=>{});var O,Hh=w(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}))});function F(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 Gh(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 hA(e){return new RegExp(`^${Gh(e)}$`)}function Wh(e){let t=`${Kh}T${Gh(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 gA(e,t){return!!((t==="v4"||!t)&&cA.test(e)||(t==="v6"||!t)&&dA.test(e))}function yA(e,t){if(!oA.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 _A(e,t){return!!((t==="v4"||!t)&&lA.test(e)||(t==="v6"||!t)&&uA.test(e))}function bA(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 Mr(e){if(e instanceof Oe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ze.create(Mr(r))}return new Oe({...e._def,shape:s(()=>t,"shape")})}else return e instanceof Dt?new Dt({...e._def,type:Mr(e.element)}):e instanceof ze?ze.create(Mr(e.unwrap())):e instanceof _t?_t.create(Mr(e.unwrap())):e instanceof yt?yt.create(e.items.map(t=>Mr(t))):e}function Yl(e,t){let n=gt(e),r=gt(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=Yl(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=Yl(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 Vh(e,t){return new Kn({values:e,typeName:L.ZodEnum,...F(t)})}function Bh(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function qh(e,t={},n){return e?en.create().superRefine((r,o)=>{let i=e(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=Bh(t,r),l=c.fatal??n??!0;o.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=Bh(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}}):en.create()}var Je,Uh,U,QT,eA,tA,nA,rA,oA,iA,sA,aA,Jl,cA,lA,dA,uA,pA,fA,Kh,mA,Qt,Dn,Pn,Mn,$n,$r,Ln,jn,en,Ot,it,Lr,Dt,Oe,Fn,Nt,Ms,Hn,yt,$s,jr,Fr,Ls,Un,Bn,Kn,Gn,tn,Ye,ze,_t,Wn,Vn,Hr,wA,Vo,qo,qn,kA,L,vA,zh,Jh,xA,SA,Yh,EA,RA,CA,TA,AA,IA,NA,OA,DA,PA,MA,$A,LA,jA,FA,HA,UA,BA,KA,GA,WA,VA,qA,zA,JA,YA,XA,ZA,QA,eI,tI,nI,rI,oI,Xh=w(()=>{Ns();Os();Hh();zl();Go();Je=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}},Uh=s((e,t)=>{if(Zt(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 Ne(e.common.issues);return this._error=n,this._error}}},"handleResult");s(F,"processCreateParams");U=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return gt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new fe,ctx:{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Pr(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:gt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Uh(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Zt(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=>Zt(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:gt(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(Pr(o)?o:Promise.resolve(o));return Uh(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 Ye({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 ze.create(this,this._def)}nullable(){return _t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dt.create(this)}promise(){return tn.create(this,this._def)}or(t){return Fn.create([this,t],this._def)}and(t){return Hn.create(this,t,this._def)}transform(t){return new Ye({...F(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Wn({...F(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new Vo({typeName:L.ZodBranded,type:this,...F(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Vn({...F(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 qo.create(this,t)}readonly(){return qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},QT=/^c[^\s-]{8,}$/i,eA=/^[0-9a-z]+$/,tA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nA=/^[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,rA=/^[a-z0-9_-]{21}$/i,oA=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,iA=/^[-+]?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)?)??$/,sA=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cA=/^(?:(?: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])$/,lA=/^(?:(?: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])$/,dA=/^(([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]))$/,uA=/^(([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])$/,pA=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fA=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kh="((\\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])))",mA=new RegExp(`^${Kh}$`);s(Gh,"timeRegexSource");s(hA,"timeRegex");s(Wh,"datetimeRegex");s(gA,"isValidIP");s(yA,"isValidJWT");s(_A,"isValidCidr");Qt=class e extends U{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 fe,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")sA.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")Jl||(Jl=new RegExp(aA,"u")),Jl.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")nA.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")rA.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")QT.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")eA.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")tA.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"?Wh(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"?mA.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?hA(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"?iA.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"duration",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?gA(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"?yA(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"?_A(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"?pA.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"base64",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?fA.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}};Qt.create=e=>new Qt({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...F(e)});s(bA,"floatSafeRemainder");Dn=class e extends U{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 fe;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"?bA(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)}};Dn.create=e=>new Dn({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...F(e)});Pn=class e extends U{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 fe;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}};Pn.create=e=>new Pn({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...F(e)});Mn=class extends U{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 be(t.data)}};Mn.create=e=>new Mn({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...F(e)});$n=class e extends U{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 fe,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}};$n.create=e=>new $n({checks:[],coerce:e?.coerce||!1,typeName:L.ZodDate,...F(e)});$r=class extends U{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 be(t.data)}};$r.create=e=>new $r({typeName:L.ZodSymbol,...F(e)});Ln=class extends U{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 be(t.data)}};Ln.create=e=>new Ln({typeName:L.ZodUndefined,...F(e)});jn=class extends U{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 be(t.data)}};jn.create=e=>new jn({typeName:L.ZodNull,...F(e)});en=class extends U{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return be(t.data)}};en.create=e=>new en({typeName:L.ZodAny,...F(e)});Ot=class extends U{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return be(t.data)}};Ot.create=e=>new Ot({typeName:L.ZodUnknown,...F(e)});it=class extends U{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}};it.create=e=>new it({typeName:L.ZodNever,...F(e)});Lr=class extends U{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 be(t.data)}};Lr.create=e=>new Lr({typeName:L.ZodVoid,...F(e)});Dt=class e extends U{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 Je(n,a,n.path,c)))).then(a=>fe.mergeArray(r,a));let i=[...n.data].map((a,c)=>o.type._parseSync(new Je(n,a,n.path,c)));return fe.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)}};Dt.create=(e,t)=>new Dt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...F(t)});s(Mr,"deepPartialify");Oe=class e extends U{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 it&&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 Je(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof it){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 Je(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=>fe.mergeObjectSync(r,d)):fe.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 Mr(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 ze;)i=i._def.innerType;n[r]=i}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return Vh(G.objectKeys(this.shape))}};Oe.create=(e,t)=>new Oe({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:it.create(),typeName:L.ZodObject,...F(t)});Oe.strictCreate=(e,t)=>new Oe({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:it.create(),typeName:L.ZodObject,...F(t)});Oe.lazycreate=(e,t)=>new Oe({shape:e,unknownKeys:"strip",catchall:it.create(),typeName:L.ZodObject,...F(t)});Fn=class extends U{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 Ne(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 Ne(l));return A(n,{code:C.invalid_union,unionErrors:c}),M}}get options(){return this._def.options}};Fn.create=(e,t)=>new Fn({options:e,typeName:L.ZodUnion,...F(t)});Nt=s(e=>e instanceof Un?Nt(e.schema):e instanceof Ye?Nt(e.innerType()):e instanceof Bn?[e.value]:e instanceof Kn?e.options:e instanceof Gn?G.objectValues(e.enum):e instanceof Wn?Nt(e._def.innerType):e instanceof Ln?[void 0]:e instanceof jn?[null]:e instanceof ze?[void 0,...Nt(e.unwrap())]:e instanceof _t?[null,...Nt(e.unwrap())]:e instanceof Vo||e instanceof qn?Nt(e.unwrap()):e instanceof Vn?Nt(e._def.innerType):[],"getDiscriminator"),Ms=class e extends U{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=Nt(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,...F(r)})}};s(Yl,"mergeValues");Hn=class extends U{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=s((i,a)=>{if(Ds(i)||Ds(a))return M;let c=Yl(i.value,a.value);return c.valid?((Ps(i)||Ps(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}))}};Hn.create=(e,t,n)=>new Hn({left:e,right:t,typeName:L.ZodIntersection,...F(n)});yt=class e extends U{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 Je(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>fe.mergeArray(n,a)):fe.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};yt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:e,typeName:L.ZodTuple,rest:null,...F(t)})};$s=class e extends U{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 Je(r,c,r.path,c)),value:a._parse(new Je(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?fe.mergeObjectAsync(n,o):fe.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:L.ZodRecord,...F(r)}):new e({keyType:Qt.create(),valueType:t,typeName:L.ZodRecord,...F(n)})}},jr=class extends U{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 Je(r,c,r.path,[d,"key"])),value:i._parse(new Je(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}}}};jr.create=(e,t,n)=>new jr({valueType:t,keyType:e,typeName:L.ZodMap,...F(n)});Fr=class e extends U{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 Je(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)}};Fr.create=(e,t)=>new Fr({valueType:e,minSize:null,maxSize:null,typeName:L.ZodSet,...F(t)});Ls=class e extends U{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 Wo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dr(),It].filter(d=>!!d),issueData:{code:C.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function o(c,l){return Wo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dr(),It].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 tn){let c=this;return be(async function(...l){let d=new Ne([]),u=await c._def.args.parseAsync(l,i).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,i).catch(m=>{throw d.addIssue(o(p,m)),d})})}else{let c=this;return be(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new Ne([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,i);if(!p.success)throw new Ne([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:yt.create(t).rest(Ot.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||yt.create([]).rest(Ot.create()),returns:n||Ot.create(),typeName:L.ZodFunction,...F(r)})}},Un=class extends U{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})}};Un.create=(e,t)=>new Un({getter:e,typeName:L.ZodLazy,...F(t)});Bn=class extends U{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}};Bn.create=(e,t)=>new Bn({value:e,typeName:L.ZodLiteral,...F(t)});s(Vh,"createZodEnum");Kn=class e extends U{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 be(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})}};Kn.create=Vh;Gn=class extends U{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 be(t.data)}get enum(){return this._def.values}};Gn.create=(e,t)=>new Gn({values:e,typeName:L.ZodNativeEnum,...F(t)});tn=class extends U{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 be(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};tn.create=(e,t)=>new tn({type:e,typeName:L.ZodPromise,...F(t)});Ye=class extends U{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"?On(l.value):n.value==="dirty"?On(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"?On(c.value):n.value==="dirty"?On(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(!Zt(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=>Zt(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:n.value,value:c})):M);G.assertNever(o)}};Ye.create=(e,t,n)=>new Ye({schema:e,typeName:L.ZodEffects,effect:t,...F(n)});Ye.createWithPreprocess=(e,t,n)=>new Ye({schema:t,effect:{type:"preprocess",transform:e},typeName:L.ZodEffects,...F(n)});ze=class extends U{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===N.undefined?be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ze.create=(e,t)=>new ze({innerType:e,typeName:L.ZodOptional,...F(t)});_t=class extends U{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===N.null?be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_t.create=(e,t)=>new _t({innerType:e,typeName:L.ZodNullable,...F(t)});Wn=class extends U{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}};Wn.create=(e,t)=>new Wn({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...F(t)});Vn=class extends U{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 Pr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ne(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ne(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Vn.create=(e,t)=>new Vn({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...F(t)});Hr=class extends U{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}}};Hr.create=e=>new Hr({typeName:L.ZodNaN,...F(e)});wA=Symbol("zod_brand"),Vo=class extends U{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}},qo=class e extends U{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(),On(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})}},qn=class extends U{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(o=>(Zt(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return Pr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};qn.create=(e,t)=>new qn({innerType:e,typeName:L.ZodReadonly,...F(t)});s(Bh,"cleanParams");s(qh,"custom");kA={object:Oe.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={}));vA=s((e,t={message:`Input not instance of ${e.name}`})=>qh(n=>n instanceof e,t),"instanceOfType"),zh=Qt.create,Jh=Dn.create,xA=Hr.create,SA=Pn.create,Yh=Mn.create,EA=$n.create,RA=$r.create,CA=Ln.create,TA=jn.create,AA=en.create,IA=Ot.create,NA=it.create,OA=Lr.create,DA=Dt.create,PA=Oe.create,MA=Oe.strictCreate,$A=Fn.create,LA=Ms.create,jA=Hn.create,FA=yt.create,HA=$s.create,UA=jr.create,BA=Fr.create,KA=Ls.create,GA=Un.create,WA=Bn.create,VA=Kn.create,qA=Gn.create,zA=tn.create,JA=Ye.create,YA=ze.create,XA=_t.create,ZA=Ye.createWithPreprocess,QA=qo.create,eI=s(()=>zh().optional(),"ostring"),tI=s(()=>Jh().optional(),"onumber"),nI=s(()=>Yh().optional(),"oboolean"),rI={string:s(e=>Qt.create({...e,coerce:!0}),"string"),number:s(e=>Dn.create({...e,coerce:!0}),"number"),boolean:s(e=>Mn.create({...e,coerce:!0}),"boolean"),bigint:s(e=>Pn.create({...e,coerce:!0}),"bigint"),date:s(e=>$n.create({...e,coerce:!0}),"date")},oI=M});var h={};Q(h,{BRAND:()=>wA,DIRTY:()=>On,EMPTY_PATH:()=>ZT,INVALID:()=>M,NEVER:()=>oI,OK:()=>be,ParseStatus:()=>fe,Schema:()=>U,ZodAny:()=>en,ZodArray:()=>Dt,ZodBigInt:()=>Pn,ZodBoolean:()=>Mn,ZodBranded:()=>Vo,ZodCatch:()=>Vn,ZodDate:()=>$n,ZodDefault:()=>Wn,ZodDiscriminatedUnion:()=>Ms,ZodEffects:()=>Ye,ZodEnum:()=>Kn,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Ls,ZodIntersection:()=>Hn,ZodIssueCode:()=>C,ZodLazy:()=>Un,ZodLiteral:()=>Bn,ZodMap:()=>jr,ZodNaN:()=>Hr,ZodNativeEnum:()=>Gn,ZodNever:()=>it,ZodNull:()=>jn,ZodNullable:()=>_t,ZodNumber:()=>Dn,ZodObject:()=>Oe,ZodOptional:()=>ze,ZodParsedType:()=>N,ZodPipeline:()=>qo,ZodPromise:()=>tn,ZodReadonly:()=>qn,ZodRecord:()=>$s,ZodSchema:()=>U,ZodSet:()=>Fr,ZodString:()=>Qt,ZodSymbol:()=>$r,ZodTransformer:()=>Ye,ZodTuple:()=>yt,ZodType:()=>U,ZodUndefined:()=>Ln,ZodUnion:()=>Fn,ZodUnknown:()=>Ot,ZodVoid:()=>Lr,addIssueToContext:()=>A,any:()=>AA,array:()=>DA,bigint:()=>SA,boolean:()=>Yh,coerce:()=>rI,custom:()=>qh,date:()=>EA,datetimeRegex:()=>Wh,defaultErrorMap:()=>It,discriminatedUnion:()=>LA,effect:()=>JA,enum:()=>VA,function:()=>KA,getErrorMap:()=>Dr,getParsedType:()=>gt,instanceof:()=>vA,intersection:()=>jA,isAborted:()=>Ds,isAsync:()=>Pr,isDirty:()=>Ps,isValid:()=>Zt,late:()=>kA,lazy:()=>GA,literal:()=>WA,makeIssue:()=>Wo,map:()=>UA,nan:()=>xA,nativeEnum:()=>qA,never:()=>NA,null:()=>TA,nullable:()=>XA,number:()=>Jh,object:()=>PA,objectUtil:()=>Vl,oboolean:()=>nI,onumber:()=>tI,optional:()=>YA,ostring:()=>eI,pipeline:()=>QA,preprocess:()=>ZA,promise:()=>zA,quotelessJson:()=>JT,record:()=>HA,set:()=>BA,setErrorMap:()=>XT,strictObject:()=>MA,string:()=>zh,symbol:()=>RA,transformer:()=>JA,tuple:()=>FA,undefined:()=>CA,union:()=>$A,unknown:()=>IA,util:()=>G,void:()=>OA});var Xl=w(()=>{Os();zl();Fh();Go();Xh();Ns()});var we=w(()=>{Xl();Xl()});var Zl,Ql=w(()=>{"use strict";we();Zl=h.object({id:h.string().min(1),title:h.string().min(1).max(200),type:h.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:h.enum(["community","curated"]),lesson_class:h.enum(["general","architecture"]).default("general"),quality_tier:h.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:h.object({source:h.enum(["memory","vault","claude-md"]),source_id:h.string().min(1),migrated_at:h.string(),migrated_from_workspace:h.string().optional()}).optional(),context:h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),summary:h.string().min(1).max(500),problem:h.string().optional(),solution:h.string().optional(),gotchas:h.array(h.string()).default([]),template_body:h.string().min(1).optional(),target_file:h.string().min(1).optional(),submitted_by:h.string().optional(),evidence:h.string().optional(),last_validated_at:h.string().optional(),tool_versions:h.record(h.string(),h.string()).optional(),upvotes:h.number().int().nonnegative().default(0),version:h.number().int().min(1).default(1),changed_at:h.string().optional(),changelog:h.string().max(500).optional(),revision_of:h.string().optional(),org_id:h.string().uuid().optional(),org_name:h.string().optional(),scope:h.literal("private").optional(),body:h.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:h.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:h.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var iI,Zh=w(()=>{"use strict";we();Ql();iI=Zl.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:h.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:h.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:h.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:h.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var Qh,eg,tg,ng,ed,rg,og,ig,sI,sg=w(()=>{"use strict";we();Qh=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],eg=h.enum(Qh),tg=["new_to_ai_agents","new_to_this_client","experienced"],ng=h.enum(tg),ed=[{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"}],rg=ed.map(e=>e.header),og=h.object({experience_level:h.array(ng).default([]),stack_filters:h.array(h.string()).default([])}).default({experience_level:[],stack_filters:[]}),ig=h.object({id:h.string().min(1),client:eg,title:h.string().min(1),last_updated:h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:og,version:h.number().int().min(1).default(1),changelog:h.string().max(500).optional()}),sI=ig.extend({body:h.string().min(1)})});var cg,js,lg,Fs,aI,cI,dg,ug,pg,fg,Hs,lI,dI,ag,uI,mg,pI,hg=w(()=>{"use strict";we();cg=["operating_procedure","code_review","communication_style"],js=h.enum(cg),lg=["info","recommended","required"],Fs=h.enum(lg),aI=["optional","default_on","mandatory"],cI=h.enum(aI),dg=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],ug=h.enum(dg),pg=["verify","contribute","mixed"],fg=h.enum(pg),Hs=h.object({clients:h.array(ug).default([]),stacks:h.array(h.string()).default([]),intents:h.array(fg).default([])}).default({clients:[],stacks:[],intents:[]}),lI=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,dI=64,ag=200,uI=h.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),mg=h.object({id:h.string().min(5).max(dI).regex(lI,"id must match conv_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),scope:js,version:h.number().int().min(1),changed_at:uI,changelog:h.string().max(500).optional(),applies_to:Hs,severity:Fs.default("recommended"),disableability:cI.default("default_on"),summary:h.string().min(1).max(ag,`summary must be \u2264 ${ag} chars (rendered as one line in init-push)`),review_gate:h.object({enabled:h.boolean(),min_matched_symbols:h.number().int().min(1).max(8).default(2),hard:h.boolean().default(!1)}).optional(),gateway_gate:h.object({enabled:h.boolean(),deny_tools:h.array(h.string().min(1).max(128)).min(1).max(16),servers:h.array(h.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),pI=mg.extend({body:h.string().min(1)})});var nn=w(()=>{"use strict";Ql();Zh();sg();hg()});var td,Us,nd,gg,yg,_g,fI,bg=w(()=>{"use strict";we();td=h.object({type:h.literal("text"),md:h.string().min(1).max(2e4)}),Us=h.number().min(0).max(1).optional(),nd=h.object({type:h.literal("media"),kind:h.enum(["image","video"]),url:h.string().url().max(2048),alt:h.string().max(500).optional(),caption:h.string().max(500).optional(),fog:h.object({top:Us,right:Us,bottom:Us,left:Us}).optional()}),gg=h.object({label:h.string().min(1).max(40),color:h.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),yg=h.object({type:h.literal("accordion"),title:h.string().min(1).max(200),subtag:gg.optional(),blocks:h.array(h.discriminatedUnion("type",[td,nd])).max(50)}),_g=h.discriminatedUnion("type",[td,nd,yg]),fI=h.array(_g).max(100)});var wg,mI,kg,vg,hI,gI,yI,xg=w(()=>{"use strict";we();wg=["free","solo_pro","team","enterprise"],mI=h.enum(wg),kg=["solo_pro","team","enterprise"],vg=h.enum(kg),hI=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),gI=h.object({user_id:h.string().uuid(),tier:vg,reason:h.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:hI.nullable().optional(),auto_revoke_on_stripe:h.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),yI=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var Sg=w(()=>{"use strict"});var _I,bI,wI,Eg=w(()=>{"use strict";we();_I=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),bI=h.object({org_id:h.string().uuid(),seats:h.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:h.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:_I.nullable().optional(),auto_revoke_on_stripe:h.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),wI=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var Rg,kI,Cg,Tg,Ag,Ig,vI,Ng=w(()=>{"use strict";we();Rg=h.enum(["info","important","critical"]),kI=h.enum(["pass","warn","fail"]),Cg=h.object({type:h.enum(["template","lesson"]),id:h.string().min(1)}),Tg=h.object({languages:h.array(h.string()).optional(),tools:h.array(h.string()).optional()}).optional(),Ag=h.discriminatedUnion("kind",[h.object({kind:h.literal("file-exists"),path:h.string().min(1)}),h.object({kind:h.literal("any-file-exists"),paths:h.array(h.string().min(1)).min(1)}),h.object({kind:h.literal("any-agent-config")}),h.object({kind:h.literal("file-size-budget"),field:h.enum(["claude_md","readme"]),max_chars:h.number().int().positive()}),h.object({kind:h.literal("readme-section-present"),headers:h.array(h.string().min(1)).min(1)}),h.object({kind:h.literal("adr-dir-present")}),h.object({kind:h.literal("git-present")}),h.object({kind:h.literal("quality-gates-configured"),pass_if_at_least:h.number().int().min(1).max(4).optional(),warn_if_at_least:h.number().int().min(0).max(4).optional()}),h.object({kind:h.literal("storage-risk-safe"),allow_unknown:h.boolean().optional()}),h.object({kind:h.literal("doc-path-discoverability")})]),Ig=h.object({id:h.string().min(1),title:h.string().min(1),severity:Rg,weight:h.number().int().positive().max(100),applies_when:Tg,check:Ag,fail_message:h.string().min(1),warn_message:h.string().optional(),remediation:Cg.optional()}),vI=h.object({version:h.literal(1),checks:h.array(Ig).min(1)})});function SI(e){if(!xI.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Bs(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 EI(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var xI,Ks,Og,Dg,bt,rd,Pg,RI,Mg=w(()=>{"use strict";we();xI=/^\d{4}-\d{2}-\d{2}$/;s(SI,"isRealDate");Ks=h.string().refine(SI,{message:"expected a real calendar date as YYYY-MM-DD"}),Og=["exact","prefix"],Dg=h.enum(Og),bt=h.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),rd=[2e5,272e3],Pg=h.object({model_pattern:h.string().min(1).max(100),match_kind:Dg,valid_from:Ks,valid_to:Ks.nullable().optional(),input:bt,output:bt,cache_read:bt,cache_write_5m:bt,cache_write_1h:bt,long_context:h.enum(["same_price","tiered"]).optional(),input_above_200k:bt.optional(),output_above_200k:bt.optional(),cache_read_above_200k:bt.optional(),cache_write_5m_above_200k:bt.optional(),cache_write_1h_above_200k:bt.optional(),context_threshold_tokens:h.number().int().positive().nullable().optional(),source_url:h.string().url().max(500).nullable().optional(),note:h.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>Bs(e)===0||Bs(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"||Bs(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=>Bs(e)===0||e.context_threshold_tokens==null||rd.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${rd.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Bs,"aboveRateCount");s(EI,"rowKey");RI=h.object({changelog:h.string().min(1).max(500),as_of:Ks,source_url:h.string().url().max(500),rows:h.array(Pg).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((o,i)=>{let a=EI(o),c=n.get(a);c!==void 0?t.addIssue({code:h.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:h.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var Ur=w(()=>{"use strict"});var zo=w(()=>{"use strict"});var Fg=w(()=>{"use strict";zo();Ur()});var Hg=w(()=>{"use strict";Ur()});var Ug=w(()=>{"use strict";nn();zo();Ur()});var Bg=w(()=>{"use strict";zo();Ur()});var Kg=w(()=>{"use strict";Ur();Fg();Hg();Ug();Bg();zo()});var WI,VI,Gg,qI,Wg,od,Vg,qg,zg,Jg,zI,id=w(()=>{"use strict";we();nn();WI=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,VI=64,Gg=200,qI=1e3,Wg=h.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),od=h.enum(["low","medium","high"]),Vg=h.object({owner:h.string().min(1).max(160).optional(),risk_level:od.optional(),reviewed_at:Wg.optional()}).default({}),qg=h.object({tags:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),limit:h.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),zg=h.object({lesson_query:qg,lesson_pins:h.array(h.string()).default([]),lesson_excludes:h.array(h.string()).default([]),convention_ids:h.array(h.string()).default([]),template_ids:h.array(h.string()).default([]),setup_guide_ids:h.array(h.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Jg=h.object({id:h.string().min(6).max(VI).regex(WI,"id must match skill_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),version:h.number().int().min(1),changed_at:Wg,tier:h.enum(["community","curated"]).default("curated"),summary:h.string().min(1).max(Gg,`summary must be \u2264 ${Gg} chars (rendered as one line in skill_index)`),description:h.string().max(qI).optional(),applies_to:Hs,membership:zg,governance:Vg}),zI=Jg.extend({body:h.string().default(""),org_id:h.string().uuid().optional(),org_name:h.string().optional()})});var Yg,Xg,Zg,Qg,ey,ty,JI,ny,YI,XI,ry=w(()=>{"use strict";we();id();Yg=h.enum(["maind","agent-skill"]),Xg=h.enum(["ready","needs_attention","blocked"]),Zg=h.enum(["info","important","critical"]),Qg=h.enum(["pass","warn","fail"]),ey=h.enum(["structure","governance","scope","membership","package","references"]),ty=h.object({id:h.string().min(1),title:h.string().min(1),status:Qg,severity:Zg,category:ey,field:h.string().nullable().optional(),message:h.string().min(1),hint:h.string().optional()}),JI=h.object({lesson_ids:h.array(h.string()).optional(),convention_ids:h.array(h.string()).optional(),template_ids:h.array(h.string()).optional(),setup_guide_ids:h.array(h.string()).optional()}).default({}),ny=h.object({name:h.string().min(1).max(64),description:h.string().min(1).max(1024),license:h.string().optional(),compatibility:h.union([h.string(),h.array(h.string())]).optional(),metadata:h.record(h.string()).default({}),"allowed-tools":h.union([h.string(),h.array(h.string())]).optional()}).passthrough(),YI=h.object({directory_name:h.string().min(1).max(120).optional(),frontmatter:ny,body:h.string().default(""),file_listing:h.array(h.string()).optional()}),XI=h.object({format:Yg,subject:h.string().min(1),status:Xg,summary:h.string().min(1),counts:h.object({pass:h.number().int().min(0),warn:h.number().int().min(0),fail:h.number().int().min(0)}),checks:h.array(ty),next_steps:h.array(h.string()),trust_note:h.string().min(1)})});var sd=w(()=>{"use strict"});var oy,QI,iy,sy,ay,Br,eN,cy,ly,dy,uy,py,fy,my,hy,tN,gy,yy,_y,rn,ad,by,wy,nN,ky=w(()=>{"use strict";we();nn();sd();oy=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],QI=h.enum(oy),iy=["verdict","advisory"],sy=h.enum(iy),ay=["block","warn","note"],Br=h.enum(ay),eN=h.object({convention_id:h.string().min(1).max(64),convention_version:h.number().int().min(1),severity:Fs,scope:js,grade:sy,matched_symbols:h.array(h.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:h.array(h.string().min(1).max(512)).max(64).default([]),summary:h.string().max(2e3),hard:h.boolean().optional()}),cy=["open","warn","info"],ly=h.enum(cy),dy=["introduced","pre_existing"],uy=h.enum(dy),py=["full","partial","none"],fy=h.enum(py),my=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),rule_id:h.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:ly,baseline:uy,evidence_hash:h.string().regex(/^[a-f0-9]{64}$/),count:h.number().int().min(1).max(1e5)}),hy=h.object({version:h.literal(1).default(1),actions:h.object({required:Br.default("block"),recommended:Br.default("warn"),info:Br.default("note")}).default({}),overrides:h.array(h.object({convention_id:h.string().min(1).max(64),action:Br})).max(64).default([]),risk_flag_action:h.enum(["warn","note","ignore"]).default("warn"),detector_overrides:h.array(h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Br,reason:h.string().min(1).max(200)})).max(32).optional()}),tN=hy.parse({}),gy=["ran","not_applicable","unavailable","ungraded"],yy=h.enum(gy),_y=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),state:yy}),rn=1e3,ad=h.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),by=h.object({name:h.string().min(1).max(200),qualified_name:h.string().min(1).max(512).optional(),kind:h.string().min(1).max(64).optional(),language:h.string().min(1).max(32).optional(),change:h.enum(["added","modified","co_located"]).optional(),changed_line_count:h.number().int().min(0).max(1e4).optional()}),wy=h.object({base_kind:h.enum(["uncommitted","ref"]),changed_file_count:h.number().int().min(0),stale_file_count:h.number().int().min(0),unindexed_file_count:h.number().int().min(0).optional(),truncated:h.boolean(),hunk_coverage:h.enum(["full","partial","none"]),detector_coverage:fy}),nN=h.object({changed_symbols:h.array(by).max(rn),risk_flags:h.array(h.string().max(64)).max(16),detector_findings:h.array(my).max(64),detector_runs:h.array(_y).min(1).max(32),diff_stats:wy,commit_sha:ad.optional(),base_sha:ad.optional(),merge_base_sha:ad.optional(),dirty:h.boolean().optional(),code_index_version:h.string().min(1).max(32).optional()})});var vy,xy,Sy,Ey,Ry,cd,rN,oN,Cy,Ty,Ay,Iy,Ny,iN,sN,Oy,Dy,Py,aN,My=w(()=>{"use strict";we();vy=14,xy=14,Sy=14,Ey=1,Ry=365,cd=h.number().int().min(Ey).max(Ry),rN=["propose","direct"],oN="propose",Cy=["propose","direct"],Ty="propose",Ay=["propose","direct"],Iy="propose",Ny=["off","propose","direct"],iN=["member","admin","owner"],sN="member",Oy="off",Dy="en",Py=h.object({version:h.literal(1).default(1),at_risk_days:cd.default(vy),stagnation_days:cd.default(xy),agent_date_mode:h.enum(rN).default(oN),health_manual_ttl_days:cd.default(Sy),agent_event_mode:h.enum(Cy).default(Ty),agent_update_mode:h.enum(Ay).default(Iy),agent_pull_mode:h.enum(Ny).default(Oy),org_wide_authoring_min_role:h.enum(iN).default(sN),planning_language:h.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Dy)}),aN=Py.parse({})});var $y,cN,Ly=w(()=>{"use strict";we();$y=h.object({version:h.literal(1).default(1),org_visibility:h.boolean().default(!1),session_span_visibility:h.boolean().default(!0)}),cN=$y.parse({})});var jy,Fy,lN,dN,Hy=w(()=>{"use strict";we();jy=h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),Fy=h.object({id:h.string().uuid(),user_id:h.string().uuid(),project:h.string().max(200).nullable().optional(),title:h.string().min(1).max(200),body:h.string().min(1).max(2e4),context:jy.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:h.string(),updated_at:h.string(),last_recalled_at:h.string().nullable().optional(),recall_count:h.number().int().nonnegative().default(0),graduated_draft_id:h.string().uuid().nullable().optional(),deleted_at:h.string().nullable().optional()}),lN=Fy.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:h.number()}),dN=h.object({id:h.string().uuid(),title:h.string(),summary:h.string(),tags:h.array(h.string()).default([])})});var Uy=w(()=>{"use strict"});function Gs(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=pN.exec(r);if(!c)return;let l=c[3]??"";if(uN.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 uN,pN,By=w(()=>{"use strict";uN=new Set(["|",">","|-",">-","|+",">+"]),pN=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(Gs,"plainScalarViolations")});function Yo(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 Ky=w(()=>{"use strict";s(Yo,"compareSemver")});var Xo=w(()=>{"use strict";nn();bg();nn();nn();xg();Sg();Eg();Ng();Mg();Kg();nn();id();ry();ky();My();Ly();Hy();Uy();sd();By();Ky()});function Gy(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
- `).slice(0,1e3)}var Wy=w(()=>{"use strict";s(Gy,"nodeEmbedText")});var ld,dd=w(()=>{"use strict";ld=["function","method","class","interface","enum","type_alias"]});function Vy(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 qy=w(()=>{"use strict";s(Vy,"cosineSimilarity")});import{execFileSync as fN}from"node:child_process";import{createHash as mN}from"node:crypto";import{readFileSync as hN}from"node:fs";import{posix as st}from"node:path";function zy(e){let t=mN("sha256"),n=[];try{n=fN("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(l=>gN.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=hN(st.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=Jy(l,o,0),u=st.dirname(l)==="."?"":st.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=Yy(o(l));if(!d||typeof d.name!="string")continue;let u=st.dirname(l)==="."?"":st.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 Jy(e,t,n){let r=Yy(t(e));if(!r)return{};let o=st.dirname(e)==="."?"":st.dirname(e),i={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=st.normalize(st.join(o,a.endsWith(".json")?a:a+".json"));i=Jy(d,t,n+1)}let c=r.compilerOptions??{},l={...i};return typeof c.outDir=="string"&&(l.outDir=st.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=st.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 Yy(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 Sh=Object.defineProperty;var s=(e,t)=>Sh(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Sh(e,n,{get:t[n],enumerable:!0})};import{homedir as DT}from"node:os";import{join as PT}from"node:path";function Cs(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=Bo(r.id),i=Bo(r.key),a=Bo(r.title),c=Bo(r.status);if(!o||!i||!a||!c)continue;let l=r.here===!1?!1:void 0,d=Bo(r.where);if(t.push({id:o,key:i,title:a,status:c,...l===!1?{here:l}:{},...d?{where:d}:{}}),t.length>=MT)break}return t}function Ll(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 Eh(e=DT()){return PT(e,".maind","assigned-told")}function Rh(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 Ch(e){return e==="claude-code"}var MT,Bo,Rs,Ko=w(()=>{"use strict";MT=5,Bo=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Cs,"parseAssignedList");s(Ll,"assignedNoticeText");s(Eh,"assignedToldDir");Rs=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=Cs(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 Ll(t)}};s(Rh,"labelNestedItems");s(Ch,"clientHasHooks")});function Nh(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 Nr(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 Hl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ul(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function Bl(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Kl=w(()=>{"use strict";s(Nh,"parseFrame");s(Nr,"denyResult");s(Hl,"toolEvent");s(Ul,"policyEvent");s(Bl,"shaEvent")});import{execFileSync as Ph}from"node:child_process";function Mh(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=VT}function qT(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 KT){let a=r[i];typeof a=="string"&&Oh.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of GT){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Oh.test(l)&&o.push({field:`${i}.${a}`,sha:l})}return o}function zT(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,Dh);for(let o=Dh;o>=WT;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 Or(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function $h(){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 As(e=process.cwd()){try{let n=Ph("git",["rev-parse","--show-toplevel"],{cwd:e,env:$h(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function JT(e){return t=>{try{let r=Ph("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:$h(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function Is(e,t){if(t===null)return[];let n=qT(e);if(n.length===0)return[];let r=JT(t),o=[];for(let{field:i,sha:a}of n){let c=zT(a,r);c.verdict!=="proven"&&o.push({...c,field:i})}return o}var KT,GT,Oh,WT,Dh,VT,Gl=w(()=>{"use strict";KT=["commit_sha","base_sha","head_sha"],GT=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Oh=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,WT=7,Dh=12,VT=10;s(Mh,"isDenyGrade");s(qT,"extractShaArgs");s(zT,"classifySha");s(Or,"shaFindingText");s($h,"cleanGitEnv");s(As,"resolveRepoRootForSha");s(JT,"gitShaResolver");s(Is,"inspectLineForShas")});var jh=w(()=>{"use strict"});var G,Vl,N,gt,Go=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})})(Vl||(Vl={}));N=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gt=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,YT,Ne,Ns=w(()=>{Go();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"]),YT=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),Ne=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()}};Ne.create=e=>new Ne(e)});var XT,It,ql=w(()=>{Ns();Go();XT=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"),It=XT});function ZT(e){Fh=e}function Dr(){return Fh}var Fh,Os=w(()=>{ql();Fh=It;s(ZT,"setErrorMap");s(Dr,"getErrorMap")});function A(e,t){let n=Dr(),r=Wo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===It?void 0:It].filter(o=>!!o)});e.common.issues.push(r)}var Wo,QT,fe,M,On,be,Ds,Ps,Zt,Pr,zl=w(()=>{Os();ql();Wo=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"),QT=[];s(A,"addIssueToContext");fe=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"}),On=s(e=>({status:"dirty",value:e}),"DIRTY"),be=s(e=>({status:"valid",value:e}),"OK"),Ds=s(e=>e.status==="aborted","isAborted"),Ps=s(e=>e.status==="dirty","isDirty"),Zt=s(e=>e.status==="valid","isValid"),Pr=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Hh=w(()=>{});var O,Uh=w(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}))});function F(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 Wh(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 gA(e){return new RegExp(`^${Wh(e)}$`)}function Vh(e){let t=`${Gh}T${Wh(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 yA(e,t){return!!((t==="v4"||!t)&&lA.test(e)||(t==="v6"||!t)&&uA.test(e))}function _A(e,t){if(!iA.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 bA(e,t){return!!((t==="v4"||!t)&&dA.test(e)||(t==="v6"||!t)&&pA.test(e))}function wA(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 Mr(e){if(e instanceof Oe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ze.create(Mr(r))}return new Oe({...e._def,shape:s(()=>t,"shape")})}else return e instanceof Dt?new Dt({...e._def,type:Mr(e.element)}):e instanceof ze?ze.create(Mr(e.unwrap())):e instanceof _t?_t.create(Mr(e.unwrap())):e instanceof yt?yt.create(e.items.map(t=>Mr(t))):e}function Yl(e,t){let n=gt(e),r=gt(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=Yl(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=Yl(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 qh(e,t){return new Kn({values:e,typeName:L.ZodEnum,...F(t)})}function Kh(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function zh(e,t={},n){return e?en.create().superRefine((r,o)=>{let i=e(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=Kh(t,r),l=c.fatal??n??!0;o.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=Kh(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}}):en.create()}var Je,Bh,U,eA,tA,nA,rA,oA,iA,sA,aA,cA,Jl,lA,dA,uA,pA,fA,mA,Gh,hA,Qt,Dn,Pn,Mn,$n,$r,Ln,jn,en,Ot,it,Lr,Dt,Oe,Fn,Nt,Ms,Hn,yt,$s,jr,Fr,Ls,Un,Bn,Kn,Gn,tn,Ye,ze,_t,Wn,Vn,Hr,kA,Vo,qo,qn,vA,L,xA,Jh,Yh,SA,EA,Xh,RA,CA,TA,AA,IA,NA,OA,DA,PA,MA,$A,LA,jA,FA,HA,UA,BA,KA,GA,WA,VA,qA,zA,JA,YA,XA,ZA,QA,eI,tI,nI,rI,oI,iI,Zh=w(()=>{Ns();Os();Uh();zl();Go();Je=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}},Bh=s((e,t)=>{if(Zt(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 Ne(e.common.issues);return this._error=n,this._error}}},"handleResult");s(F,"processCreateParams");U=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return gt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new fe,ctx:{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Pr(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:gt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Bh(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Zt(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=>Zt(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:gt(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(Pr(o)?o:Promise.resolve(o));return Bh(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 Ye({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 ze.create(this,this._def)}nullable(){return _t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dt.create(this)}promise(){return tn.create(this,this._def)}or(t){return Fn.create([this,t],this._def)}and(t){return Hn.create(this,t,this._def)}transform(t){return new Ye({...F(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Wn({...F(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new Vo({typeName:L.ZodBranded,type:this,...F(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Vn({...F(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 qo.create(this,t)}readonly(){return qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eA=/^c[^\s-]{8,}$/i,tA=/^[0-9a-z]+$/,nA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rA=/^[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,oA=/^[a-z0-9_-]{21}$/i,iA=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sA=/^[-+]?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)?)??$/,aA=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lA=/^(?:(?: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])$/,dA=/^(?:(?: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])$/,uA=/^(([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]))$/,pA=/^(([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])$/,fA=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mA=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gh="((\\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])))",hA=new RegExp(`^${Gh}$`);s(Wh,"timeRegexSource");s(gA,"timeRegex");s(Vh,"datetimeRegex");s(yA,"isValidIP");s(_A,"isValidJWT");s(bA,"isValidCidr");Qt=class e extends U{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 fe,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")aA.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")Jl||(Jl=new RegExp(cA,"u")),Jl.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")rA.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")oA.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")eA.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")tA.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")nA.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"?Vh(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"?hA.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{code:C.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?gA(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"?sA.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"duration",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?yA(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"?_A(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"?bA(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"?fA.test(t.data)||(o=this._getOrReturnCtx(t,o),A(o,{validation:"base64",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?mA.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}};Qt.create=e=>new Qt({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...F(e)});s(wA,"floatSafeRemainder");Dn=class e extends U{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 fe;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"?wA(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)}};Dn.create=e=>new Dn({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...F(e)});Pn=class e extends U{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 fe;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}};Pn.create=e=>new Pn({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...F(e)});Mn=class extends U{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 be(t.data)}};Mn.create=e=>new Mn({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...F(e)});$n=class e extends U{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 fe,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}};$n.create=e=>new $n({checks:[],coerce:e?.coerce||!1,typeName:L.ZodDate,...F(e)});$r=class extends U{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 be(t.data)}};$r.create=e=>new $r({typeName:L.ZodSymbol,...F(e)});Ln=class extends U{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 be(t.data)}};Ln.create=e=>new Ln({typeName:L.ZodUndefined,...F(e)});jn=class extends U{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 be(t.data)}};jn.create=e=>new jn({typeName:L.ZodNull,...F(e)});en=class extends U{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return be(t.data)}};en.create=e=>new en({typeName:L.ZodAny,...F(e)});Ot=class extends U{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return be(t.data)}};Ot.create=e=>new Ot({typeName:L.ZodUnknown,...F(e)});it=class extends U{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}};it.create=e=>new it({typeName:L.ZodNever,...F(e)});Lr=class extends U{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 be(t.data)}};Lr.create=e=>new Lr({typeName:L.ZodVoid,...F(e)});Dt=class e extends U{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 Je(n,a,n.path,c)))).then(a=>fe.mergeArray(r,a));let i=[...n.data].map((a,c)=>o.type._parseSync(new Je(n,a,n.path,c)));return fe.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)}};Dt.create=(e,t)=>new Dt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...F(t)});s(Mr,"deepPartialify");Oe=class e extends U{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 it&&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 Je(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof it){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 Je(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=>fe.mergeObjectSync(r,d)):fe.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 Mr(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 ze;)i=i._def.innerType;n[r]=i}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return qh(G.objectKeys(this.shape))}};Oe.create=(e,t)=>new Oe({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:it.create(),typeName:L.ZodObject,...F(t)});Oe.strictCreate=(e,t)=>new Oe({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:it.create(),typeName:L.ZodObject,...F(t)});Oe.lazycreate=(e,t)=>new Oe({shape:e,unknownKeys:"strip",catchall:it.create(),typeName:L.ZodObject,...F(t)});Fn=class extends U{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 Ne(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 Ne(l));return A(n,{code:C.invalid_union,unionErrors:c}),M}}get options(){return this._def.options}};Fn.create=(e,t)=>new Fn({options:e,typeName:L.ZodUnion,...F(t)});Nt=s(e=>e instanceof Un?Nt(e.schema):e instanceof Ye?Nt(e.innerType()):e instanceof Bn?[e.value]:e instanceof Kn?e.options:e instanceof Gn?G.objectValues(e.enum):e instanceof Wn?Nt(e._def.innerType):e instanceof Ln?[void 0]:e instanceof jn?[null]:e instanceof ze?[void 0,...Nt(e.unwrap())]:e instanceof _t?[null,...Nt(e.unwrap())]:e instanceof Vo||e instanceof qn?Nt(e.unwrap()):e instanceof Vn?Nt(e._def.innerType):[],"getDiscriminator"),Ms=class e extends U{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=Nt(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,...F(r)})}};s(Yl,"mergeValues");Hn=class extends U{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=s((i,a)=>{if(Ds(i)||Ds(a))return M;let c=Yl(i.value,a.value);return c.valid?((Ps(i)||Ps(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}))}};Hn.create=(e,t,n)=>new Hn({left:e,right:t,typeName:L.ZodIntersection,...F(n)});yt=class e extends U{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 Je(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>fe.mergeArray(n,a)):fe.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};yt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:e,typeName:L.ZodTuple,rest:null,...F(t)})};$s=class e extends U{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 Je(r,c,r.path,c)),value:a._parse(new Je(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?fe.mergeObjectAsync(n,o):fe.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:L.ZodRecord,...F(r)}):new e({keyType:Qt.create(),valueType:t,typeName:L.ZodRecord,...F(n)})}},jr=class extends U{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 Je(r,c,r.path,[d,"key"])),value:i._parse(new Je(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}}}};jr.create=(e,t,n)=>new jr({valueType:t,keyType:e,typeName:L.ZodMap,...F(n)});Fr=class e extends U{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 Je(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)}};Fr.create=(e,t)=>new Fr({valueType:e,minSize:null,maxSize:null,typeName:L.ZodSet,...F(t)});Ls=class e extends U{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 Wo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dr(),It].filter(d=>!!d),issueData:{code:C.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function o(c,l){return Wo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dr(),It].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 tn){let c=this;return be(async function(...l){let d=new Ne([]),u=await c._def.args.parseAsync(l,i).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,i).catch(m=>{throw d.addIssue(o(p,m)),d})})}else{let c=this;return be(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new Ne([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,i);if(!p.success)throw new Ne([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:yt.create(t).rest(Ot.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||yt.create([]).rest(Ot.create()),returns:n||Ot.create(),typeName:L.ZodFunction,...F(r)})}},Un=class extends U{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})}};Un.create=(e,t)=>new Un({getter:e,typeName:L.ZodLazy,...F(t)});Bn=class extends U{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}};Bn.create=(e,t)=>new Bn({value:e,typeName:L.ZodLiteral,...F(t)});s(qh,"createZodEnum");Kn=class e extends U{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 be(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})}};Kn.create=qh;Gn=class extends U{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 be(t.data)}get enum(){return this._def.values}};Gn.create=(e,t)=>new Gn({values:e,typeName:L.ZodNativeEnum,...F(t)});tn=class extends U{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 be(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};tn.create=(e,t)=>new tn({type:e,typeName:L.ZodPromise,...F(t)});Ye=class extends U{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"?On(l.value):n.value==="dirty"?On(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"?On(c.value):n.value==="dirty"?On(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(!Zt(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=>Zt(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:n.value,value:c})):M);G.assertNever(o)}};Ye.create=(e,t,n)=>new Ye({schema:e,typeName:L.ZodEffects,effect:t,...F(n)});Ye.createWithPreprocess=(e,t,n)=>new Ye({schema:t,effect:{type:"preprocess",transform:e},typeName:L.ZodEffects,...F(n)});ze=class extends U{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===N.undefined?be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ze.create=(e,t)=>new ze({innerType:e,typeName:L.ZodOptional,...F(t)});_t=class extends U{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===N.null?be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_t.create=(e,t)=>new _t({innerType:e,typeName:L.ZodNullable,...F(t)});Wn=class extends U{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}};Wn.create=(e,t)=>new Wn({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...F(t)});Vn=class extends U{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 Pr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ne(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ne(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Vn.create=(e,t)=>new Vn({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...F(t)});Hr=class extends U{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}}};Hr.create=e=>new Hr({typeName:L.ZodNaN,...F(e)});kA=Symbol("zod_brand"),Vo=class extends U{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}},qo=class e extends U{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(),On(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})}},qn=class extends U{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(o=>(Zt(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return Pr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};qn.create=(e,t)=>new qn({innerType:e,typeName:L.ZodReadonly,...F(t)});s(Kh,"cleanParams");s(zh,"custom");vA={object:Oe.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={}));xA=s((e,t={message:`Input not instance of ${e.name}`})=>zh(n=>n instanceof e,t),"instanceOfType"),Jh=Qt.create,Yh=Dn.create,SA=Hr.create,EA=Pn.create,Xh=Mn.create,RA=$n.create,CA=$r.create,TA=Ln.create,AA=jn.create,IA=en.create,NA=Ot.create,OA=it.create,DA=Lr.create,PA=Dt.create,MA=Oe.create,$A=Oe.strictCreate,LA=Fn.create,jA=Ms.create,FA=Hn.create,HA=yt.create,UA=$s.create,BA=jr.create,KA=Fr.create,GA=Ls.create,WA=Un.create,VA=Bn.create,qA=Kn.create,zA=Gn.create,JA=tn.create,YA=Ye.create,XA=ze.create,ZA=_t.create,QA=Ye.createWithPreprocess,eI=qo.create,tI=s(()=>Jh().optional(),"ostring"),nI=s(()=>Yh().optional(),"onumber"),rI=s(()=>Xh().optional(),"oboolean"),oI={string:s(e=>Qt.create({...e,coerce:!0}),"string"),number:s(e=>Dn.create({...e,coerce:!0}),"number"),boolean:s(e=>Mn.create({...e,coerce:!0}),"boolean"),bigint:s(e=>Pn.create({...e,coerce:!0}),"bigint"),date:s(e=>$n.create({...e,coerce:!0}),"date")},iI=M});var h={};ee(h,{BRAND:()=>kA,DIRTY:()=>On,EMPTY_PATH:()=>QT,INVALID:()=>M,NEVER:()=>iI,OK:()=>be,ParseStatus:()=>fe,Schema:()=>U,ZodAny:()=>en,ZodArray:()=>Dt,ZodBigInt:()=>Pn,ZodBoolean:()=>Mn,ZodBranded:()=>Vo,ZodCatch:()=>Vn,ZodDate:()=>$n,ZodDefault:()=>Wn,ZodDiscriminatedUnion:()=>Ms,ZodEffects:()=>Ye,ZodEnum:()=>Kn,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Ls,ZodIntersection:()=>Hn,ZodIssueCode:()=>C,ZodLazy:()=>Un,ZodLiteral:()=>Bn,ZodMap:()=>jr,ZodNaN:()=>Hr,ZodNativeEnum:()=>Gn,ZodNever:()=>it,ZodNull:()=>jn,ZodNullable:()=>_t,ZodNumber:()=>Dn,ZodObject:()=>Oe,ZodOptional:()=>ze,ZodParsedType:()=>N,ZodPipeline:()=>qo,ZodPromise:()=>tn,ZodReadonly:()=>qn,ZodRecord:()=>$s,ZodSchema:()=>U,ZodSet:()=>Fr,ZodString:()=>Qt,ZodSymbol:()=>$r,ZodTransformer:()=>Ye,ZodTuple:()=>yt,ZodType:()=>U,ZodUndefined:()=>Ln,ZodUnion:()=>Fn,ZodUnknown:()=>Ot,ZodVoid:()=>Lr,addIssueToContext:()=>A,any:()=>IA,array:()=>PA,bigint:()=>EA,boolean:()=>Xh,coerce:()=>oI,custom:()=>zh,date:()=>RA,datetimeRegex:()=>Vh,defaultErrorMap:()=>It,discriminatedUnion:()=>jA,effect:()=>YA,enum:()=>qA,function:()=>GA,getErrorMap:()=>Dr,getParsedType:()=>gt,instanceof:()=>xA,intersection:()=>FA,isAborted:()=>Ds,isAsync:()=>Pr,isDirty:()=>Ps,isValid:()=>Zt,late:()=>vA,lazy:()=>WA,literal:()=>VA,makeIssue:()=>Wo,map:()=>BA,nan:()=>SA,nativeEnum:()=>zA,never:()=>OA,null:()=>AA,nullable:()=>ZA,number:()=>Yh,object:()=>MA,objectUtil:()=>Vl,oboolean:()=>rI,onumber:()=>nI,optional:()=>XA,ostring:()=>tI,pipeline:()=>eI,preprocess:()=>QA,promise:()=>JA,quotelessJson:()=>YT,record:()=>UA,set:()=>KA,setErrorMap:()=>ZT,strictObject:()=>$A,string:()=>Jh,symbol:()=>CA,transformer:()=>YA,tuple:()=>HA,undefined:()=>TA,union:()=>LA,unknown:()=>NA,util:()=>G,void:()=>DA});var Xl=w(()=>{Os();zl();Hh();Go();Zh();Ns()});var we=w(()=>{Xl();Xl()});var Zl,Ql=w(()=>{"use strict";we();Zl=h.object({id:h.string().min(1),title:h.string().min(1).max(200),type:h.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:h.enum(["community","curated"]),lesson_class:h.enum(["general","architecture"]).default("general"),quality_tier:h.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:h.object({source:h.enum(["memory","vault","claude-md"]),source_id:h.string().min(1),migrated_at:h.string(),migrated_from_workspace:h.string().optional()}).optional(),context:h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),summary:h.string().min(1).max(500),problem:h.string().optional(),solution:h.string().optional(),gotchas:h.array(h.string()).default([]),template_body:h.string().min(1).optional(),target_file:h.string().min(1).optional(),submitted_by:h.string().optional(),evidence:h.string().optional(),last_validated_at:h.string().optional(),tool_versions:h.record(h.string(),h.string()).optional(),upvotes:h.number().int().nonnegative().default(0),version:h.number().int().min(1).default(1),changed_at:h.string().optional(),changelog:h.string().max(500).optional(),revision_of:h.string().optional(),org_id:h.string().uuid().optional(),org_name:h.string().optional(),scope:h.literal("private").optional(),body:h.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:h.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:h.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var sI,Qh=w(()=>{"use strict";we();Ql();sI=Zl.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:h.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:h.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:h.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:h.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var eg,tg,ng,rg,ed,og,ig,sg,aI,ag=w(()=>{"use strict";we();eg=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],tg=h.enum(eg),ng=["new_to_ai_agents","new_to_this_client","experienced"],rg=h.enum(ng),ed=[{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"}],og=ed.map(e=>e.header),ig=h.object({experience_level:h.array(rg).default([]),stack_filters:h.array(h.string()).default([])}).default({experience_level:[],stack_filters:[]}),sg=h.object({id:h.string().min(1),client:tg,title:h.string().min(1),last_updated:h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:ig,version:h.number().int().min(1).default(1),changelog:h.string().max(500).optional()}),aI=sg.extend({body:h.string().min(1)})});var lg,js,dg,Fs,cI,lI,ug,pg,fg,mg,Hs,dI,uI,cg,pI,hg,fI,gg=w(()=>{"use strict";we();lg=["operating_procedure","code_review","communication_style"],js=h.enum(lg),dg=["info","recommended","required"],Fs=h.enum(dg),cI=["optional","default_on","mandatory"],lI=h.enum(cI),ug=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],pg=h.enum(ug),fg=["verify","contribute","mixed"],mg=h.enum(fg),Hs=h.object({clients:h.array(pg).default([]),stacks:h.array(h.string()).default([]),intents:h.array(mg).default([])}).default({clients:[],stacks:[],intents:[]}),dI=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,uI=64,cg=200,pI=h.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),hg=h.object({id:h.string().min(5).max(uI).regex(dI,"id must match conv_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),scope:js,version:h.number().int().min(1),changed_at:pI,changelog:h.string().max(500).optional(),applies_to:Hs,severity:Fs.default("recommended"),disableability:lI.default("default_on"),summary:h.string().min(1).max(cg,`summary must be \u2264 ${cg} chars (rendered as one line in init-push)`),review_gate:h.object({enabled:h.boolean(),min_matched_symbols:h.number().int().min(1).max(8).default(2),hard:h.boolean().default(!1)}).optional(),gateway_gate:h.object({enabled:h.boolean(),deny_tools:h.array(h.string().min(1).max(128)).min(1).max(16),servers:h.array(h.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),fI=hg.extend({body:h.string().min(1)})});var nn=w(()=>{"use strict";Ql();Qh();ag();gg()});var td,Us,nd,yg,_g,bg,mI,wg=w(()=>{"use strict";we();td=h.object({type:h.literal("text"),md:h.string().min(1).max(2e4)}),Us=h.number().min(0).max(1).optional(),nd=h.object({type:h.literal("media"),kind:h.enum(["image","video"]),url:h.string().url().max(2048),alt:h.string().max(500).optional(),caption:h.string().max(500).optional(),fog:h.object({top:Us,right:Us,bottom:Us,left:Us}).optional()}),yg=h.object({label:h.string().min(1).max(40),color:h.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),_g=h.object({type:h.literal("accordion"),title:h.string().min(1).max(200),subtag:yg.optional(),blocks:h.array(h.discriminatedUnion("type",[td,nd])).max(50)}),bg=h.discriminatedUnion("type",[td,nd,_g]),mI=h.array(bg).max(100)});var kg,hI,vg,xg,gI,yI,_I,Sg=w(()=>{"use strict";we();kg=["free","solo_pro","team","enterprise"],hI=h.enum(kg),vg=["solo_pro","team","enterprise"],xg=h.enum(vg),gI=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),yI=h.object({user_id:h.string().uuid(),tier:xg,reason:h.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:gI.nullable().optional(),auto_revoke_on_stripe:h.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),_I=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var Eg=w(()=>{"use strict"});var bI,wI,kI,Rg=w(()=>{"use strict";we();bI=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),wI=h.object({org_id:h.string().uuid(),seats:h.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:h.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:bI.nullable().optional(),auto_revoke_on_stripe:h.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),kI=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var Cg,vI,Tg,Ag,Ig,Ng,xI,Og=w(()=>{"use strict";we();Cg=h.enum(["info","important","critical"]),vI=h.enum(["pass","warn","fail"]),Tg=h.object({type:h.enum(["template","lesson"]),id:h.string().min(1)}),Ag=h.object({languages:h.array(h.string()).optional(),tools:h.array(h.string()).optional()}).optional(),Ig=h.discriminatedUnion("kind",[h.object({kind:h.literal("file-exists"),path:h.string().min(1)}),h.object({kind:h.literal("any-file-exists"),paths:h.array(h.string().min(1)).min(1)}),h.object({kind:h.literal("any-agent-config")}),h.object({kind:h.literal("file-size-budget"),field:h.enum(["claude_md","readme"]),max_chars:h.number().int().positive()}),h.object({kind:h.literal("readme-section-present"),headers:h.array(h.string().min(1)).min(1)}),h.object({kind:h.literal("adr-dir-present")}),h.object({kind:h.literal("git-present")}),h.object({kind:h.literal("quality-gates-configured"),pass_if_at_least:h.number().int().min(1).max(4).optional(),warn_if_at_least:h.number().int().min(0).max(4).optional()}),h.object({kind:h.literal("storage-risk-safe"),allow_unknown:h.boolean().optional()}),h.object({kind:h.literal("doc-path-discoverability")})]),Ng=h.object({id:h.string().min(1),title:h.string().min(1),severity:Cg,weight:h.number().int().positive().max(100),applies_when:Ag,check:Ig,fail_message:h.string().min(1),warn_message:h.string().optional(),remediation:Tg.optional()}),xI=h.object({version:h.literal(1),checks:h.array(Ng).min(1)})});function EI(e){if(!SI.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Bs(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 RI(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var SI,Ks,Dg,Pg,bt,rd,Mg,CI,$g=w(()=>{"use strict";we();SI=/^\d{4}-\d{2}-\d{2}$/;s(EI,"isRealDate");Ks=h.string().refine(EI,{message:"expected a real calendar date as YYYY-MM-DD"}),Dg=["exact","prefix"],Pg=h.enum(Dg),bt=h.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),rd=[2e5,272e3],Mg=h.object({model_pattern:h.string().min(1).max(100),match_kind:Pg,valid_from:Ks,valid_to:Ks.nullable().optional(),input:bt,output:bt,cache_read:bt,cache_write_5m:bt,cache_write_1h:bt,long_context:h.enum(["same_price","tiered"]).optional(),input_above_200k:bt.optional(),output_above_200k:bt.optional(),cache_read_above_200k:bt.optional(),cache_write_5m_above_200k:bt.optional(),cache_write_1h_above_200k:bt.optional(),context_threshold_tokens:h.number().int().positive().nullable().optional(),source_url:h.string().url().max(500).nullable().optional(),note:h.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>Bs(e)===0||Bs(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"||Bs(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=>Bs(e)===0||e.context_threshold_tokens==null||rd.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${rd.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Bs,"aboveRateCount");s(RI,"rowKey");CI=h.object({changelog:h.string().min(1).max(500),as_of:Ks,source_url:h.string().url().max(500),rows:h.array(Mg).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((o,i)=>{let a=RI(o),c=n.get(a);c!==void 0?t.addIssue({code:h.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:h.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var Ur=w(()=>{"use strict"});var zo=w(()=>{"use strict"});var Hg=w(()=>{"use strict";zo();Ur()});var Ug=w(()=>{"use strict";Ur()});var Bg=w(()=>{"use strict";nn();zo();Ur()});var Kg=w(()=>{"use strict";zo();Ur()});var Gg=w(()=>{"use strict";Ur();Hg();Ug();Bg();Kg();zo()});var VI,qI,Wg,zI,Vg,od,qg,zg,Jg,Yg,JI,id=w(()=>{"use strict";we();nn();VI=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,qI=64,Wg=200,zI=1e3,Vg=h.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,h.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),od=h.enum(["low","medium","high"]),qg=h.object({owner:h.string().min(1).max(160).optional(),risk_level:od.optional(),reviewed_at:Vg.optional()}).default({}),zg=h.object({tags:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),limit:h.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),Jg=h.object({lesson_query:zg,lesson_pins:h.array(h.string()).default([]),lesson_excludes:h.array(h.string()).default([]),convention_ids:h.array(h.string()).default([]),template_ids:h.array(h.string()).default([]),setup_guide_ids:h.array(h.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Yg=h.object({id:h.string().min(6).max(qI).regex(VI,"id must match skill_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),version:h.number().int().min(1),changed_at:Vg,tier:h.enum(["community","curated"]).default("curated"),summary:h.string().min(1).max(Wg,`summary must be \u2264 ${Wg} chars (rendered as one line in skill_index)`),description:h.string().max(zI).optional(),applies_to:Hs,membership:Jg,governance:qg}),JI=Yg.extend({body:h.string().default(""),org_id:h.string().uuid().optional(),org_name:h.string().optional()})});var Xg,Zg,Qg,ey,ty,ny,YI,ry,XI,ZI,oy=w(()=>{"use strict";we();id();Xg=h.enum(["maind","agent-skill"]),Zg=h.enum(["ready","needs_attention","blocked"]),Qg=h.enum(["info","important","critical"]),ey=h.enum(["pass","warn","fail"]),ty=h.enum(["structure","governance","scope","membership","package","references"]),ny=h.object({id:h.string().min(1),title:h.string().min(1),status:ey,severity:Qg,category:ty,field:h.string().nullable().optional(),message:h.string().min(1),hint:h.string().optional()}),YI=h.object({lesson_ids:h.array(h.string()).optional(),convention_ids:h.array(h.string()).optional(),template_ids:h.array(h.string()).optional(),setup_guide_ids:h.array(h.string()).optional()}).default({}),ry=h.object({name:h.string().min(1).max(64),description:h.string().min(1).max(1024),license:h.string().optional(),compatibility:h.union([h.string(),h.array(h.string())]).optional(),metadata:h.record(h.string()).default({}),"allowed-tools":h.union([h.string(),h.array(h.string())]).optional()}).passthrough(),XI=h.object({directory_name:h.string().min(1).max(120).optional(),frontmatter:ry,body:h.string().default(""),file_listing:h.array(h.string()).optional()}),ZI=h.object({format:Xg,subject:h.string().min(1),status:Zg,summary:h.string().min(1),counts:h.object({pass:h.number().int().min(0),warn:h.number().int().min(0),fail:h.number().int().min(0)}),checks:h.array(ny),next_steps:h.array(h.string()),trust_note:h.string().min(1)})});var sd=w(()=>{"use strict"});var iy,eN,sy,ay,cy,Br,tN,ly,dy,uy,py,fy,my,hy,gy,nN,yy,_y,by,rn,ad,wy,ky,rN,vy=w(()=>{"use strict";we();nn();sd();iy=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],eN=h.enum(iy),sy=["verdict","advisory"],ay=h.enum(sy),cy=["block","warn","note"],Br=h.enum(cy),tN=h.object({convention_id:h.string().min(1).max(64),convention_version:h.number().int().min(1),severity:Fs,scope:js,grade:ay,matched_symbols:h.array(h.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:h.array(h.string().min(1).max(512)).max(64).default([]),summary:h.string().max(2e3),hard:h.boolean().optional()}),ly=["open","warn","info"],dy=h.enum(ly),uy=["introduced","pre_existing"],py=h.enum(uy),fy=["full","partial","none"],my=h.enum(fy),hy=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),rule_id:h.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:dy,baseline:py,evidence_hash:h.string().regex(/^[a-f0-9]{64}$/),count:h.number().int().min(1).max(1e5)}),gy=h.object({version:h.literal(1).default(1),actions:h.object({required:Br.default("block"),recommended:Br.default("warn"),info:Br.default("note")}).default({}),overrides:h.array(h.object({convention_id:h.string().min(1).max(64),action:Br})).max(64).default([]),risk_flag_action:h.enum(["warn","note","ignore"]).default("warn"),detector_overrides:h.array(h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Br,reason:h.string().min(1).max(200)})).max(32).optional()}),nN=gy.parse({}),yy=["ran","not_applicable","unavailable","ungraded"],_y=h.enum(yy),by=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),state:_y}),rn=1e3,ad=h.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),wy=h.object({name:h.string().min(1).max(200),qualified_name:h.string().min(1).max(512).optional(),kind:h.string().min(1).max(64).optional(),language:h.string().min(1).max(32).optional(),change:h.enum(["added","modified","co_located"]).optional(),changed_line_count:h.number().int().min(0).max(1e4).optional()}),ky=h.object({base_kind:h.enum(["uncommitted","ref"]),changed_file_count:h.number().int().min(0),stale_file_count:h.number().int().min(0),unindexed_file_count:h.number().int().min(0).optional(),truncated:h.boolean(),hunk_coverage:h.enum(["full","partial","none"]),detector_coverage:my}),rN=h.object({changed_symbols:h.array(wy).max(rn),risk_flags:h.array(h.string().max(64)).max(16),detector_findings:h.array(hy).max(64),detector_runs:h.array(by).min(1).max(32),diff_stats:ky,commit_sha:ad.optional(),base_sha:ad.optional(),merge_base_sha:ad.optional(),dirty:h.boolean().optional(),code_index_version:h.string().min(1).max(32).optional()})});var xy,Sy,Ey,Ry,Cy,cd,oN,iN,Ty,Ay,Iy,Ny,Oy,sN,aN,Dy,Py,My,cN,$y=w(()=>{"use strict";we();xy=14,Sy=14,Ey=14,Ry=1,Cy=365,cd=h.number().int().min(Ry).max(Cy),oN=["propose","direct"],iN="propose",Ty=["propose","direct"],Ay="propose",Iy=["propose","direct"],Ny="propose",Oy=["off","propose","direct"],sN=["member","admin","owner"],aN="member",Dy="off",Py="en",My=h.object({version:h.literal(1).default(1),at_risk_days:cd.default(xy),stagnation_days:cd.default(Sy),agent_date_mode:h.enum(oN).default(iN),health_manual_ttl_days:cd.default(Ey),agent_event_mode:h.enum(Ty).default(Ay),agent_update_mode:h.enum(Iy).default(Ny),agent_pull_mode:h.enum(Oy).default(Dy),org_wide_authoring_min_role:h.enum(sN).default(aN),planning_language:h.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Py)}),cN=My.parse({})});var Ly,lN,jy=w(()=>{"use strict";we();Ly=h.object({version:h.literal(1).default(1),org_visibility:h.boolean().default(!1),session_span_visibility:h.boolean().default(!0)}),lN=Ly.parse({})});var Fy,Hy,dN,uN,Uy=w(()=>{"use strict";we();Fy=h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),Hy=h.object({id:h.string().uuid(),user_id:h.string().uuid(),project:h.string().max(200).nullable().optional(),title:h.string().min(1).max(200),body:h.string().min(1).max(2e4),context:Fy.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:h.string(),updated_at:h.string(),last_recalled_at:h.string().nullable().optional(),recall_count:h.number().int().nonnegative().default(0),graduated_draft_id:h.string().uuid().nullable().optional(),deleted_at:h.string().nullable().optional()}),dN=Hy.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:h.number()}),uN=h.object({id:h.string().uuid(),title:h.string(),summary:h.string(),tags:h.array(h.string()).default([])})});var By=w(()=>{"use strict"});function Gs(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=fN.exec(r);if(!c)return;let l=c[3]??"";if(pN.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 pN,fN,Ky=w(()=>{"use strict";pN=new Set(["|",">","|-",">-","|+",">+"]),fN=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(Gs,"plainScalarViolations")});function Yo(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 Gy=w(()=>{"use strict";s(Yo,"compareSemver")});var Xo=w(()=>{"use strict";nn();wg();nn();nn();Sg();Eg();Rg();Og();$g();Gg();nn();id();oy();vy();$y();jy();Uy();By();sd();Ky();Gy()});function Wy(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
+ `).slice(0,1e3)}var Vy=w(()=>{"use strict";s(Wy,"nodeEmbedText")});var ld,dd=w(()=>{"use strict";ld=["function","method","class","interface","enum","type_alias"]});function qy(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 zy=w(()=>{"use strict";s(qy,"cosineSimilarity")});import{execFileSync as mN}from"node:child_process";import{createHash as hN}from"node:crypto";import{readFileSync as gN}from"node:fs";import{posix as st}from"node:path";function Jy(e){let t=hN("sha256"),n=[];try{n=mN("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
+ `).filter(l=>yN.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=gN(st.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=Yy(l,o,0),u=st.dirname(l)==="."?"":st.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=Xy(o(l));if(!d||typeof d.name!="string")continue;let u=st.dirname(l)==="."?"":st.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 Yy(e,t,n){let r=Xy(t(e));if(!r)return{};let o=st.dirname(e)==="."?"":st.dirname(e),i={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=st.normalize(st.join(o,a.endsWith(".json")?a:a+".json"));i=Yy(d,t,n+1)}let c=r.compilerOptions??{},l={...i};return typeof c.outDir=="string"&&(l.outDir=st.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=st.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 Xy(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(yN(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function yN(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 gN,Xy=w(()=>{"use strict";gN=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(zy,"loadModuleConfig");s(Jy,"compilerFacts");s(Yy,"parseJsonc");s(yN,"dropTrailingCommas")});import{posix as at}from"node:path";function Zo(e,t){let n=at.normalize(e).replace(/^\.\//,""),r=[],o=Ws.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 Ws)r.push(c+l)}if(!o&&!i){for(let c of Ws)r.push(n+c);for(let c of Ws)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function Qy(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=Qy(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 Qo(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=Qo(n[o]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?Qo(e):null}function Qo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Qo(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of _N)if(n in t){let r=Qo(t[n]);if(r)return r}}return null}function bN(e,t){let n=at.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let o=at.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),i=at.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===o||n.startsWith(o+"/"))&&r.unshift(at.join(i,n.slice(o.length+1)))}return r}var Ws,_N,ud,Zy,Kr,pd=w(()=>{"use strict";Ws=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],_N=["import","default","node","require","types"],ud={kind:"unresolved"},Zy={kind:"external"};s(Zo,"resolvePathCandidates");Kr=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=`${at.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=Zo(at.join(at.dirname(t),n),this.files);return i?{kind:"file",path:i}:ud}if(n.startsWith("node:"))return Zy;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}:ud}return Zy}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(i=>i.dir===""||t.startsWith(i.dir+"/"));if(!r?.paths)return null;let o=at.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=Zo(at.join(o,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return ud}}return null}viaPackage(t,n){let r=[],o=Qy(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 bN(t,i)){let c=Zo(at.join(t.dir,a),this.files);if(c)return c}return null}};s(Qy,"exportTarget");s(Qo,"conditionTarget");s(bN,"toSource")});function wt(e){return`${e}#<module>`}function kt(e,t,n){return`${e}#${t}:${n}`}var zn=w(()=>{"use strict";s(wt,"moduleKey");s(kt,"symbolKey")});import{posix as e_}from"node:path";function n_(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),wN.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(o,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===kt(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 r_(e,t,n=new Kr({packages:[],tsconfigs:[]},t.files)){let r=SN(),o=new fd(e,t,n);for(let i of e)i.language==="python"?EN(i.filePath,i.refs,i.imports,t,r.push):o.resolveFile(i,r.push);return r.edges}function xN(e,t,n){return t.startsWith(".")?Zo(e_.join(e_.dirname(e),t),n):null}function SN(){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 EN(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=xN(e,i.specifier,r.files);a&&o(i.fromModuleKey,wt(a),"imports")}}function RN(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return kt(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var wN,t_,kN,vN,fd,o_=w(()=>{"use strict";zn();pd();wN=new Set(["function","method","class","interface","enum","type_alias"]),t_=["function","class","variable","enum","interface","type_alias"],kN=8,vN=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(n_,"buildResolutionIndex");s(r_,"resolveCrossFileEdges");s(xN,"resolveImportTarget");s(SN,"edgeCollector");s(EN,"legacyFacts");s(RN,"classKeyOfMethod");fd=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(wt(t.filePath),wt(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(vN.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=RN(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=kt(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=kt(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=kt(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>kN)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=t_.indexOf(i.slice(i.lastIndexOf(":")+1));return a<0?t_.length:a},"rank");return{kind:"symbol",key:[...r].sort((i,a)=>o(i)-o(a))[0]}}}});function Gr(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 ei(e){return e.toLowerCase().endsWith(".d.ts")}var Vs=w(()=>{"use strict";s(Gr,"languageForPath");s(ei,"isSkippablePath")});import{appendFileSync as CN,existsSync as i_,mkdirSync as TN,readFileSync as AN}from"node:fs";import{join as IN}from"node:path";function ti(e,t={}){try{if(!i_(e)){if(!t.create)return"skipped";TN(e,{recursive:!0})}let n=IN(e,".gitignore"),r=i_(n)?AN(n,"utf8"):null,o=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),i=qs.filter(l=>!o.has(l));if(i.length===0)return"unchanged";let a=r===null?[...NN,...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(_N(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function _N(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 yN,Zy=w(()=>{"use strict";yN=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(Jy,"loadModuleConfig");s(Yy,"compilerFacts");s(Xy,"parseJsonc");s(_N,"dropTrailingCommas")});import{posix as at}from"node:path";function Zo(e,t){let n=at.normalize(e).replace(/^\.\//,""),r=[],o=Ws.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 Ws)r.push(c+l)}if(!o&&!i){for(let c of Ws)r.push(n+c);for(let c of Ws)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function e_(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=e_(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 Qo(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=Qo(n[o]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?Qo(e):null}function Qo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Qo(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of bN)if(n in t){let r=Qo(t[n]);if(r)return r}}return null}function wN(e,t){let n=at.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let o=at.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),i=at.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===o||n.startsWith(o+"/"))&&r.unshift(at.join(i,n.slice(o.length+1)))}return r}var Ws,bN,ud,Qy,Kr,pd=w(()=>{"use strict";Ws=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],bN=["import","default","node","require","types"],ud={kind:"unresolved"},Qy={kind:"external"};s(Zo,"resolvePathCandidates");Kr=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=`${at.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=Zo(at.join(at.dirname(t),n),this.files);return i?{kind:"file",path:i}:ud}if(n.startsWith("node:"))return Qy;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}:ud}return Qy}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(i=>i.dir===""||t.startsWith(i.dir+"/"));if(!r?.paths)return null;let o=at.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=Zo(at.join(o,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return ud}}return null}viaPackage(t,n){let r=[],o=e_(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 wN(t,i)){let c=Zo(at.join(t.dir,a),this.files);if(c)return c}return null}};s(e_,"exportTarget");s(Qo,"conditionTarget");s(wN,"toSource")});function wt(e){return`${e}#<module>`}function kt(e,t,n){return`${e}#${t}:${n}`}var zn=w(()=>{"use strict";s(wt,"moduleKey");s(kt,"symbolKey")});import{posix as t_}from"node:path";function r_(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),kN.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(o,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===kt(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 o_(e,t,n=new Kr({packages:[],tsconfigs:[]},t.files)){let r=EN(),o=new fd(e,t,n);for(let i of e)i.language==="python"?RN(i.filePath,i.refs,i.imports,t,r.push):o.resolveFile(i,r.push);return r.edges}function SN(e,t,n){return t.startsWith(".")?Zo(t_.join(t_.dirname(e),t),n):null}function EN(){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 RN(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=SN(e,i.specifier,r.files);a&&o(i.fromModuleKey,wt(a),"imports")}}function CN(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return kt(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var kN,n_,vN,xN,fd,i_=w(()=>{"use strict";zn();pd();kN=new Set(["function","method","class","interface","enum","type_alias"]),n_=["function","class","variable","enum","interface","type_alias"],vN=8,xN=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(r_,"buildResolutionIndex");s(o_,"resolveCrossFileEdges");s(SN,"resolveImportTarget");s(EN,"edgeCollector");s(RN,"legacyFacts");s(CN,"classKeyOfMethod");fd=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(wt(t.filePath),wt(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(xN.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=CN(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=kt(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=kt(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=kt(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>vN)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=n_.indexOf(i.slice(i.lastIndexOf(":")+1));return a<0?n_.length:a},"rank");return{kind:"symbol",key:[...r].sort((i,a)=>o(i)-o(a))[0]}}}});function Gr(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 ei(e){return e.toLowerCase().endsWith(".d.ts")}var Vs=w(()=>{"use strict";s(Gr,"languageForPath");s(ei,"isSkippablePath")});import{appendFileSync as TN,existsSync as s_,mkdirSync as AN,readFileSync as IN}from"node:fs";import{join as NN}from"node:path";function ti(e,t={}){try{if(!s_(e)){if(!t.create)return"skipped";AN(e,{recursive:!0})}let n=NN(e,".gitignore"),r=s_(n)?IN(n,"utf8"):null,o=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),i=qs.filter(l=>!o.has(l));if(i.length===0)return"unchanged";let a=r===null?[...ON,...i]:i,c=r&&!r.endsWith(`
8
8
  `)?`
9
- `:"";return CN(n,c+a.join(`
9
+ `:"";return TN(n,c+a.join(`
10
10
  `)+`
11
- `),r===null?"created":"appended"}catch{return"skipped"}}var qs,md,NN,zs=w(()=>{"use strict";qs=[".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"],md=["# 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).'],NN=md;s(ti,"ensureMaindLocalIgnore")});import{execFileSync as ON}from"node:child_process";import{createHash as DN}from"node:crypto";import{existsSync as PN,readFileSync as MN,readdirSync as $N,statSync as LN}from"node:fs";import{posix as Ys,sep as s_}from"node:path";function I(e,t){try{return ON("git",[...jN,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function FN(e){return s_==="/"?e:e.split(s_).join("/")}function Js(e){let t=[];for(let n of e){let r=FN(n).trim();if(!r||ei(r))continue;let o=Gr(r);o&&t.push({path:r,language:o})}return t}function c_(e){return Js(e)}function l_(e){let t=Pt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Js(t.split(`
12
- `));let n=[];return d_(e,"",n),Js(n)}function d_(e,t,n){let r;try{r=$N(Ys.join(e,t),{withFileTypes:!0})}catch{return}for(let o of r){if(o.name.startsWith(".")&&o.name!=="."&&a_.has(o.name)||a_.has(o.name))continue;let i=t?`${t}/${o.name}`:o.name;o.isDirectory()?d_(e,i,n):o.isFile()&&n.push(i)}}function gd(e,t){return yd(e,t)??t}function yd(e,t){let n=I(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Xs(e,t={}){if(ni(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?gd(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=Pt(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(`
11
+ `),r===null?"created":"appended"}catch{return"skipped"}}var qs,md,ON,zs=w(()=>{"use strict";qs=[".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"],md=["# 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).'],ON=md;s(ti,"ensureMaindLocalIgnore")});import{execFileSync as DN}from"node:child_process";import{createHash as PN}from"node:crypto";import{existsSync as MN,readFileSync as $N,readdirSync as LN,statSync as jN}from"node:fs";import{posix as Ys,sep as a_}from"node:path";function I(e,t){try{return DN("git",[...FN,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function HN(e){return a_==="/"?e:e.split(a_).join("/")}function Js(e){let t=[];for(let n of e){let r=HN(n).trim();if(!r||ei(r))continue;let o=Gr(r);o&&t.push({path:r,language:o})}return t}function l_(e){return Js(e)}function d_(e){let t=Pt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Js(t.split(`
12
+ `));let n=[];return u_(e,"",n),Js(n)}function u_(e,t,n){let r;try{r=LN(Ys.join(e,t),{withFileTypes:!0})}catch{return}for(let o of r){if(o.name.startsWith(".")&&o.name!=="."&&c_.has(o.name)||c_.has(o.name))continue;let i=t?`${t}/${o.name}`:o.name;o.isDirectory()?u_(e,i,n):o.isFile()&&n.push(i)}}function gd(e,t){return yd(e,t)??t}function yd(e,t){let n=I(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Xs(e,t={}){if(ni(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?gd(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=Pt(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
13
  `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=hd((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=Pt(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=hd(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 hd(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function _d(e,t={}){let n=Xs(e,t);return n===null?null:Js(n.keys())}function u_(e,t){try{let n=LN(Ys.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Zs(e){return DN("sha256").update(e).digest("hex")}function ni(e){return Pt(e,["rev-parse","HEAD"])?.trim()??null}function Qs(e,t){return Pt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function bd(e){let t=Pt(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
15
- `).filter(o=>o.trim().length>0),r=UN(e);return n.some(o=>r===null||!p_(e,o,r))?!0:r!==null&&HN(e,r)}function HN(e,t){if(!PN(Ys.join(e,".maind",".gitignore")))return!1;let n=Pt(e,["ls-files","--full-name","--",".maind/.gitignore"]);return n===null?!0:n.trim().length>0?!1:!p_(e,`?? ${t}`,t)}function UN(e){let t=Pt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function p_(e,t,n){let r=t[0],o=t[1];if(hd(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=Pt(e,["show",`HEAD:${n}`]);if(p===null)return!1;i=p}else return!1;let a;try{a=MN(Ys.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=s(p=>p.replace(/\r\n/g,`
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=hd(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 hd(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function _d(e,t={}){let n=Xs(e,t);return n===null?null:Js(n.keys())}function p_(e,t){try{let n=jN(Ys.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Zs(e){return PN("sha256").update(e).digest("hex")}function ni(e){return Pt(e,["rev-parse","HEAD"])?.trim()??null}function Qs(e,t){return Pt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function bd(e){let t=Pt(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
15
+ `).filter(o=>o.trim().length>0),r=BN(e);return n.some(o=>r===null||!f_(e,o,r))?!0:r!==null&&UN(e,r)}function UN(e,t){if(!MN(Ys.join(e,".maind",".gitignore")))return!1;let n=Pt(e,["ls-files","--full-name","--",".maind/.gitignore"]);return n===null?!0:n.trim().length>0?!1:!f_(e,`?? ${t}`,t)}function BN(e){let t=Pt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function f_(e,t,n){let r=t[0],o=t[1];if(hd(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=Pt(e,["show",`HEAD:${n}`]);if(p===null)return!1;i=p}else return!1;let a;try{a=$N(Ys.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=s(p=>p.replace(/\r\n/g,`
16
16
  `),"norm"),l=c(i),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...qs,...md]);return d.slice(l.length).split(`
17
- `).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var a_,jN,Pt,Te=w(()=>{"use strict";Vs();zs();a_=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),jN=["-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");Pt=I;s(FN,"toPosix");s(Js,"classify");s(c_,"classifyPaths");s(l_,"discoverSourceFiles");s(d_,"walk");s(gd,"resolveDiffBase");s(yd,"resolveMergeBase");s(Xs,"enumerateChangedPaths");s(hd,"unquote");s(_d,"changedSourceFiles");s(u_,"statFile");s(Zs,"hashContent");s(ni,"headCommit");s(Qs,"resolveCommitSha");s(bd,"isWorktreeDirty");s(HN,"hasForeignUntrackedIgnore");s(UN,"toolIgnoreRepoPath");s(p_,"isToolOnlyIgnoreChange")});function m_(e,t={}){if(I(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?gd(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")>BN?c="none":VN(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 VN(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=WN.exec(l);if(d){if(o++,o>KN){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<GN&&r.addedLines.push(l.slice(1))}c()}var BN,KN,GN,f_,WN,h_=w(()=>{"use strict";Te();BN=16*1024*1024,KN=500,GN=4e3,f_=256*1024,WN=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(m_,"changedHunks");s(VN,"parseUnifiedDiff")});function kd(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>=w_&&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 JN(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function y_(e){return e.split(qN).filter(t=>t.trim().length>0)}function __(e){let[t,n,r,o,i]=e.replace(/\n+$/,"").split(zN);return!t||!o?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:o,subject:i??""}}function YN(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 k_(e,t,n={}){let r=JN(n.limit,20,100),o=n.includeOwnership!==!1,i=Math.max(r,b_),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,wd),l=[];for(let u of c){let p=I(e,["log","-n",String(i),g_,"--",u]),f=p===null?[]:y_(p).map(__).filter(m=>m!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:o?{topAuthors:YN(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=Qs(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=I(e,["log",...p,"-n",String(ea+1),g_,"--name-only","--",...c]),m=[];if(f!==null)for(let g of y_(f)){let y=g.split(`
20
- `),_=__(y[0]??"");if(!_)continue;let b=y.slice(1).filter(k=>k.trim().length>0).length;m.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,ea),truncated:m.length>ea}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>wd}}var qN,zN,b_,wd,ea,g_,w_,vd=w(()=>{"use strict";Te();qN="",zN="\0",b_=200,wd=50,ea=100,g_="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",w_=10;s(kd,"aggregateHistoryContext");s(JN,"clamp");s(y_,"splitRecords");s(__,"parseHistoryRecord");s(YN,"aggregateOwnership");s(k_,"readFileHistory")});import{execFileSync as XN}from"node:child_process";import{readdirSync as ZN,statSync as v_}from"node:fs";import{isAbsolute as QN,join as xd,relative as eO,resolve as tO}from"node:path";function rO(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function oO(e,t){try{let n=XN("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 iO(e){let t;try{t=ZN(e)}catch{return null}for(let n of t.filter(rO))try{let r=v_(xd(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function sO(e){try{return v_(e).isDirectory()}catch{return!1}}function aO(e,t){let n=eO(e,t);return!n||n.startsWith("..")?t:n}function Sd(e){let t=nO.filter(c=>sO(xd(e,c))),n=oO(e,"core.hooksPath"),r=n?QN(n)?n:tO(e,n):xd(e,".git","hooks"),o=aO(e,r),i=iO(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 Ed(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 nO,Rd=w(()=>{"use strict";nO=[".githooks",".husky"];s(rO,"isRealHook");s(oO,"gitConfig");s(iO,"hasExecutableHook");s(sO,"isDir");s(aO,"displayPath");s(Sd,"resolveHookState");s(Ed,"describeHookState")});import{posix as x_}from"node:path";function Wr(e){let t=cO.exec(e);return t?t[1]:null}function Mt(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Jn(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=x_.basename(i),c=Wr(a);if(c===null)continue;let l=x_.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)=>Mt(c.version,l.version))})).sort((i,a)=>i.dir.localeCompare(a.dir))}function ri(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 cO,oi=w(()=>{"use strict";Te();cO=/^(\d+)_.+\.sql$/;s(Wr,"parseMigrationVersion");s(Mt,"compareVersions");s(Jn,"discoverSupabaseProjects");s(ri,"resolveDefaultBranch")});import{execFileSync as lO}from"node:child_process";import{existsSync as ke,readFileSync as on,readdirSync as ta,statSync as Td}from"node:fs";import{posix as W}from"node:path";function fO(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(ke(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&&Id(n,i))){let c=mO(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=W.dirname(r)}return null}function mO(e,t){let n=[];for(let r of uO){let o;try{o=ta(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=Td(c),u=Td(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>pO)continue;on(c).equals(on(l))||n.push(a)}catch{continue}}}return n.sort()}function I_(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 ${Nd}.`})}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=hO(e.hooks);return a&&t.push(a),gO(t)}function hO(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:Ed(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 gO(e){return[...e].sort((t,n)=>S_[t.status]-S_[n.status]||t.id.localeCompare(n.id))}function N_(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function $t(e){let t=e?.trim();return t||null}function yO(e){let t=$t(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 _O(e){let t=$t(I(e,["rev-parse","--git-dir"]));if(!t)return null;let n=W.isAbsolute(t)?t:W.join(e,t);return ke(W.join(n,"rebase-merge"))||ke(W.join(n,"rebase-apply"))?"rebase":ke(W.join(n,"MERGE_HEAD"))?"merge":ke(W.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function bO(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 wO(e){let t=W.join(e,Nd);if(!ke(t))return[];try{return on(t,"utf8").split(`
22
- `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function kO(e){try{return Jn(e).map(t=>W.join(W.dirname(t.dir),"config.toml"))}catch{return[]}}function vO(e){let t=I(e,["ls-files","-z","--",...dO]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let o=A_[W.basename(r)];if(o===void 0)continue;let i=W.dirname(r);if(!xO(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 xO(e,t){return t==="."?!0:Ad(e,t)}function Ad(e,t){if(ke(W.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(on(W.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function O_(e,t={}){if($t(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=$t(I(e,["rev-parse","--abbrev-ref","HEAD"])),o=r==="HEAD",i=o?null:r,a=yO(e),c=$t(I(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let K=$t(I(e,["rev-parse","HEAD"])),x=$t(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=$t(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 m=(I(e,["status","--porcelain"])??"").split(`
23
- `).filter(K=>K.trim().length>0).length,g=_O(e),y=$t(I(e,["rev-parse","--show-toplevel"]))??e,_=bO(I(e,["worktree","list","--porcelain"])??""),b=_[0]?.path??null,k=b!=null&&Id(b,y),v=Math.max(0,_.length-1),E=null;if(b&&!Id(b,y)){let K=s(T=>ke(W.join(b,T))&&!ke(W.join(y,T)),"here"),x=[...T_,...kO(y),...wO(y),...t.probePaths??[]];E={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(x.filter(K))],missingDeps:vO(y).filter(T=>K(T.dir))}}let S=fO(y,e),R=t.includeRelease===!1?null:IO(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:m,detachedHead:o,inProgressOp:g,isSharedMainTree:k,otherWorktrees:v,worktreeParity:E,toolCopyDrift:S,stalePackageBuilds:D_(y),release:R,unmergedMigrations:P,hooks:Sd(e)}}function Id(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function RO(e){let t=new Set;Ad(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<R_;){let o=n.pop();if(o===void 0)break;if(o.depth>=EO)continue;let i;try{i=ta(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>=R_)break;Ad(e,c)&&t.add(c),n.push({rel:c,depth:o.depth+1})}}return[...t].sort()}function CO(e){let t=[];try{let n=W.join(e,"pnpm-workspace.yaml");if(ke(n)){let r=!1;for(let o of on(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(ke(r)){let o=JSON.parse(on(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 TO(e){let t=[];for(let n of RO(e)){let r=n==="."?e:W.join(e,n),o=s(i=>n==="."?i:W.join(n,i),"prefix");for(let i of CO(r)){if(t.length>=Cd)break;if(!(i.startsWith("!")||i.includes("**")))try{if(i.endsWith("/*")){let a=i.slice(0,-2),c=W.join(r,a);if(!ke(c))continue;for(let l of ta(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(o(W.join(a,l.name))),t.length>=Cd)break}else i.includes("*")||t.push(o(i))}catch{}}}return t.slice(0,Cd)}function C_(e){let t=null,n=0,r=[e];for(;r.length>0&&n<E_;){let o=r.pop();if(o===void 0)break;let i;try{i=ta(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=Td(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=E_)break}}}return t}function AO(e,t){let n=new Set;for(let r of t)try{let o=W.join(e,r,"package.json");if(!ke(o))continue;let i=JSON.parse(on(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 D_(e){let t=[],n=TO(e),r=AO(e,n);for(let o of n)try{let i=W.join(e,o,"package.json");if(!ke(i))continue;let a=JSON.parse(on(i,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let k=b.replace(/^\.\//,"").split("/")[0];return k==="build"||k==="dist"?k:null},"builtSeg"),l=c(a.types??a.typings),d=c(a.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",f=W.join(e,o,"src"),m=W.join(e,o,u);if(!ke(f)||!ke(m))continue;let g=C_(f),y=C_(m);if(g===null||y===null)continue;let _=g-y;_>SO&&t.push({packageDir:o,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((o,i)=>o.packageDir.localeCompare(i.packageDir))}function IO(e,t){if(!t)return null;let n=NO(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 NO(e,t){try{return lO("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function ii(e,t={}){let n=await O_(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=I_(n),o=N_(r);return{ok:o,verdict:o?"clean":"diverged",reason:null,findings:r,facts:n}}var T_,Nd,A_,dO,uO,pO,S_,SO,Cd,E_,EO,R_,Od=w(()=>{"use strict";Rd();Te();oi();T_=["supabase/config.toml","supabase/.temp",".env"],Nd=".maind/worktree-requirements",A_={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},dO=Object.keys(A_).flatMap(e=>[e,"*/"+e]),uO=["scripts"],pO=512*1024;s(fO,"gatherToolCopyDrift");s(mO,"compareToolDirs");s(I_,"computeDivergence");s(hO,"computeHookFinding");S_={open:0,warn:1,info:2,passed:3};s(gO,"sortFindings");s(N_,"isHealthy");s($t,"trimOrNull");s(yO,"resolveDefaultBranch");s(_O,"detectInProgressOp");s(bO,"parseWorktrees");s(wO,"readWorktreeRequirements");s(kO,"discoverSupabaseConfigProbes");s(vO,"discoverDependencyDirs");s(xO,"isWorkspaceRoot");s(Ad,"hasWorkspaceMarkers");s(O_,"gatherRepoHealthFacts");s(Id,"samePath");SO=2e3,Cd=64,E_=4e3,EO=3,R_=400;s(RO,"findWorkspaceRoots");s(CO,"workspacePatternsAt");s(TO,"listWorkspacePackageDirs");s(C_,"newestMtimeUnder");s(AO,"consumedWorkspaceNames");s(D_,"gatherStalePackageBuilds");s(IO,"gatherReleaseFact");s(NO,"runGh");s(ii,"checkDivergence")});import{existsSync as Dd,readdirSync as P_}from"node:fs";import{posix as vt}from"node:path";function Md(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Pd)}function j_(e,t={}){let n=t.minFiles??$d;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??M_)}function Vr(e){return`${e.dir}#${e.prefix}`}function ai(e){let t=OO.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function F_(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let o of e.namespaces){let i=Vr(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),m=`${o.prefix}${l}`;t.push(p?{id:`number.collision:${i}#${l}`,status:"open",namespace:o,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${o.prefix}${Ld(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:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((o,i)=>r[o.status]-r[i.status]||o.id.localeCompare(i.id))}function H_(e){return!e.some(t=>t.status==="open")}function Ld(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 jd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function U_(e,t){let n=jd(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},o=ai(vt.basename(n));if(!o)return r;let i=`${vt.dirname(n)}#${o.prefix}`,a=e.namespaces.find(u=>Vr(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:Ld(c.keys(),o.number)}}function B_(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 K_(e,t){if(!e)return[];let n=[...t].sort((o,i)=>i.length-o.length),r=[];for(let o of e.split(`
17
+ `).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var c_,FN,Pt,Te=w(()=>{"use strict";Vs();zs();c_=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),FN=["-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");Pt=I;s(HN,"toPosix");s(Js,"classify");s(l_,"classifyPaths");s(d_,"discoverSourceFiles");s(u_,"walk");s(gd,"resolveDiffBase");s(yd,"resolveMergeBase");s(Xs,"enumerateChangedPaths");s(hd,"unquote");s(_d,"changedSourceFiles");s(p_,"statFile");s(Zs,"hashContent");s(ni,"headCommit");s(Qs,"resolveCommitSha");s(bd,"isWorktreeDirty");s(UN,"hasForeignUntrackedIgnore");s(BN,"toolIgnoreRepoPath");s(f_,"isToolOnlyIgnoreChange")});function h_(e,t={}){if(I(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?gd(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")>KN?c="none":qN(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 qN(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=VN.exec(l);if(d){if(o++,o>GN){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<WN&&r.addedLines.push(l.slice(1))}c()}var KN,GN,WN,m_,VN,g_=w(()=>{"use strict";Te();KN=16*1024*1024,GN=500,WN=4e3,m_=256*1024,VN=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(h_,"changedHunks");s(qN,"parseUnifiedDiff")});function kd(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>=k_&&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 YN(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function __(e){return e.split(zN).filter(t=>t.trim().length>0)}function b_(e){let[t,n,r,o,i]=e.replace(/\n+$/,"").split(JN);return!t||!o?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:o,subject:i??""}}function XN(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 v_(e,t,n={}){let r=YN(n.limit,20,100),o=n.includeOwnership!==!1,i=Math.max(r,w_),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,wd),l=[];for(let u of c){let p=I(e,["log","-n",String(i),y_,"--",u]),f=p===null?[]:__(p).map(b_).filter(m=>m!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:o?{topAuthors:XN(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=Qs(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=I(e,["log",...p,"-n",String(ea+1),y_,"--name-only","--",...c]),m=[];if(f!==null)for(let g of __(f)){let y=g.split(`
20
+ `),_=b_(y[0]??"");if(!_)continue;let b=y.slice(1).filter(k=>k.trim().length>0).length;m.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,ea),truncated:m.length>ea}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>wd}}var zN,JN,w_,wd,ea,y_,k_,vd=w(()=>{"use strict";Te();zN="",JN="\0",w_=200,wd=50,ea=100,y_="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",k_=10;s(kd,"aggregateHistoryContext");s(YN,"clamp");s(__,"splitRecords");s(b_,"parseHistoryRecord");s(XN,"aggregateOwnership");s(v_,"readFileHistory")});import{execFileSync as ZN}from"node:child_process";import{readdirSync as QN,statSync as x_}from"node:fs";import{isAbsolute as eO,join as xd,relative as tO,resolve as nO}from"node:path";function oO(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function iO(e,t){try{let n=ZN("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 sO(e){let t;try{t=QN(e)}catch{return null}for(let n of t.filter(oO))try{let r=x_(xd(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function aO(e){try{return x_(e).isDirectory()}catch{return!1}}function cO(e,t){let n=tO(e,t);return!n||n.startsWith("..")?t:n}function Sd(e){let t=rO.filter(c=>aO(xd(e,c))),n=iO(e,"core.hooksPath"),r=n?eO(n)?n:nO(e,n):xd(e,".git","hooks"),o=cO(e,r),i=sO(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 Ed(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 rO,Rd=w(()=>{"use strict";rO=[".githooks",".husky"];s(oO,"isRealHook");s(iO,"gitConfig");s(sO,"hasExecutableHook");s(aO,"isDir");s(cO,"displayPath");s(Sd,"resolveHookState");s(Ed,"describeHookState")});import{posix as S_}from"node:path";function Wr(e){let t=lO.exec(e);return t?t[1]:null}function Mt(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Jn(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=S_.basename(i),c=Wr(a);if(c===null)continue;let l=S_.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)=>Mt(c.version,l.version))})).sort((i,a)=>i.dir.localeCompare(a.dir))}function ri(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 lO,oi=w(()=>{"use strict";Te();lO=/^(\d+)_.+\.sql$/;s(Wr,"parseMigrationVersion");s(Mt,"compareVersions");s(Jn,"discoverSupabaseProjects");s(ri,"resolveDefaultBranch")});import{execFileSync as dO}from"node:child_process";import{existsSync as ke,readFileSync as on,readdirSync as ta,statSync as Td}from"node:fs";import{posix as W}from"node:path";function mO(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(ke(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&&Id(n,i))){let c=hO(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=W.dirname(r)}return null}function hO(e,t){let n=[];for(let r of pO){let o;try{o=ta(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=Td(c),u=Td(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>fO)continue;on(c).equals(on(l))||n.push(a)}catch{continue}}}return n.sort()}function N_(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 ${Nd}.`})}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=gO(e.hooks);return a&&t.push(a),yO(t)}function gO(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:Ed(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 yO(e){return[...e].sort((t,n)=>E_[t.status]-E_[n.status]||t.id.localeCompare(n.id))}function O_(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function $t(e){let t=e?.trim();return t||null}function _O(e){let t=$t(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 bO(e){let t=$t(I(e,["rev-parse","--git-dir"]));if(!t)return null;let n=W.isAbsolute(t)?t:W.join(e,t);return ke(W.join(n,"rebase-merge"))||ke(W.join(n,"rebase-apply"))?"rebase":ke(W.join(n,"MERGE_HEAD"))?"merge":ke(W.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function wO(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 kO(e){let t=W.join(e,Nd);if(!ke(t))return[];try{return on(t,"utf8").split(`
22
+ `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function vO(e){try{return Jn(e).map(t=>W.join(W.dirname(t.dir),"config.toml"))}catch{return[]}}function xO(e){let t=I(e,["ls-files","-z","--",...uO]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let o=I_[W.basename(r)];if(o===void 0)continue;let i=W.dirname(r);if(!SO(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 SO(e,t){return t==="."?!0:Ad(e,t)}function Ad(e,t){if(ke(W.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(on(W.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function D_(e,t={}){if($t(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=$t(I(e,["rev-parse","--abbrev-ref","HEAD"])),o=r==="HEAD",i=o?null:r,a=_O(e),c=$t(I(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let K=$t(I(e,["rev-parse","HEAD"])),x=$t(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=$t(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 m=(I(e,["status","--porcelain"])??"").split(`
23
+ `).filter(K=>K.trim().length>0).length,g=bO(e),y=$t(I(e,["rev-parse","--show-toplevel"]))??e,_=wO(I(e,["worktree","list","--porcelain"])??""),b=_[0]?.path??null,k=b!=null&&Id(b,y),v=Math.max(0,_.length-1),E=null;if(b&&!Id(b,y)){let K=s(T=>ke(W.join(b,T))&&!ke(W.join(y,T)),"here"),x=[...A_,...vO(y),...kO(y),...t.probePaths??[]];E={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(x.filter(K))],missingDeps:xO(y).filter(T=>K(T.dir))}}let S=mO(y,e),R=t.includeRelease===!1?null:NO(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:m,detachedHead:o,inProgressOp:g,isSharedMainTree:k,otherWorktrees:v,worktreeParity:E,toolCopyDrift:S,stalePackageBuilds:P_(y),release:R,unmergedMigrations:P,hooks:Sd(e)}}function Id(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function CO(e){let t=new Set;Ad(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<C_;){let o=n.pop();if(o===void 0)break;if(o.depth>=RO)continue;let i;try{i=ta(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>=C_)break;Ad(e,c)&&t.add(c),n.push({rel:c,depth:o.depth+1})}}return[...t].sort()}function TO(e){let t=[];try{let n=W.join(e,"pnpm-workspace.yaml");if(ke(n)){let r=!1;for(let o of on(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(ke(r)){let o=JSON.parse(on(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 AO(e){let t=[];for(let n of CO(e)){let r=n==="."?e:W.join(e,n),o=s(i=>n==="."?i:W.join(n,i),"prefix");for(let i of TO(r)){if(t.length>=Cd)break;if(!(i.startsWith("!")||i.includes("**")))try{if(i.endsWith("/*")){let a=i.slice(0,-2),c=W.join(r,a);if(!ke(c))continue;for(let l of ta(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(o(W.join(a,l.name))),t.length>=Cd)break}else i.includes("*")||t.push(o(i))}catch{}}}return t.slice(0,Cd)}function T_(e){let t=null,n=0,r=[e];for(;r.length>0&&n<R_;){let o=r.pop();if(o===void 0)break;let i;try{i=ta(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=Td(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=R_)break}}}return t}function IO(e,t){let n=new Set;for(let r of t)try{let o=W.join(e,r,"package.json");if(!ke(o))continue;let i=JSON.parse(on(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 P_(e){let t=[],n=AO(e),r=IO(e,n);for(let o of n)try{let i=W.join(e,o,"package.json");if(!ke(i))continue;let a=JSON.parse(on(i,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let k=b.replace(/^\.\//,"").split("/")[0];return k==="build"||k==="dist"?k:null},"builtSeg"),l=c(a.types??a.typings),d=c(a.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",f=W.join(e,o,"src"),m=W.join(e,o,u);if(!ke(f)||!ke(m))continue;let g=T_(f),y=T_(m);if(g===null||y===null)continue;let _=g-y;_>EO&&t.push({packageDir:o,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((o,i)=>o.packageDir.localeCompare(i.packageDir))}function NO(e,t){if(!t)return null;let n=OO(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 OO(e,t){try{return dO("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function ii(e,t={}){let n=await D_(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=N_(n),o=O_(r);return{ok:o,verdict:o?"clean":"diverged",reason:null,findings:r,facts:n}}var A_,Nd,I_,uO,pO,fO,E_,EO,Cd,R_,RO,C_,Od=w(()=>{"use strict";Rd();Te();oi();A_=["supabase/config.toml","supabase/.temp",".env"],Nd=".maind/worktree-requirements",I_={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},uO=Object.keys(I_).flatMap(e=>[e,"*/"+e]),pO=["scripts"],fO=512*1024;s(mO,"gatherToolCopyDrift");s(hO,"compareToolDirs");s(N_,"computeDivergence");s(gO,"computeHookFinding");E_={open:0,warn:1,info:2,passed:3};s(yO,"sortFindings");s(O_,"isHealthy");s($t,"trimOrNull");s(_O,"resolveDefaultBranch");s(bO,"detectInProgressOp");s(wO,"parseWorktrees");s(kO,"readWorktreeRequirements");s(vO,"discoverSupabaseConfigProbes");s(xO,"discoverDependencyDirs");s(SO,"isWorkspaceRoot");s(Ad,"hasWorkspaceMarkers");s(D_,"gatherRepoHealthFacts");s(Id,"samePath");EO=2e3,Cd=64,R_=4e3,RO=3,C_=400;s(CO,"findWorkspaceRoots");s(TO,"workspacePatternsAt");s(AO,"listWorkspacePackageDirs");s(T_,"newestMtimeUnder");s(IO,"consumedWorkspaceNames");s(P_,"gatherStalePackageBuilds");s(NO,"gatherReleaseFact");s(OO,"runGh");s(ii,"checkDivergence")});import{existsSync as Dd,readdirSync as M_}from"node:fs";import{posix as vt}from"node:path";function Md(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Pd)}function F_(e,t={}){let n=t.minFiles??$d;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??$_)}function Vr(e){return`${e.dir}#${e.prefix}`}function ai(e){let t=DO.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function H_(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let o of e.namespaces){let i=Vr(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),m=`${o.prefix}${l}`;t.push(p?{id:`number.collision:${i}#${l}`,status:"open",namespace:o,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${o.prefix}${Ld(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:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((o,i)=>r[o.status]-r[i.status]||o.id.localeCompare(i.id))}function U_(e){return!e.some(t=>t.status==="open")}function Ld(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 jd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function B_(e,t){let n=jd(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},o=ai(vt.basename(n));if(!o)return r;let i=`${vt.dirname(n)}#${o.prefix}`,a=e.namespaces.find(u=>Vr(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:Ld(c.keys(),o.number)}}function K_(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 G_(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 si(e){let t=e?.trim();return t||null}function Yn(e){return e?e.split(`
27
- `).filter(Boolean):[]}function DO(e){let t=si(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 G_(e,t={}){let n=t.minFiles??$d,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=vt.dirname(a),l=ai(vt.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=>j_(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>Vr(a).localeCompare(Vr(c)))}async function Fd(e,t={}){let n=[];if(si(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=G_(e,t),i=new Map(o.map(_=>[Vr(_),_])),a=[...new Set(o.map(_=>_.dir))],c=new Map,l=s((_,b,k)=>{let v=vt.dirname(_),E=ai(vt.basename(_));if(!E)return;let S=`${v}#${E.prefix}`;if(!i.has(S))return;let R=c.get(S)??new Map,P=R.get(E.number)??[];P.push({kind:b,where:k,path:_}),R.set(E.number,P),c.set(S,R)},"record"),d=s((_,b,k)=>{if(a.length===0)return;let v=I(e,["ls-tree","-r","--name-only",_,"--",...a]);if(v===null){n.push(`could not read ${k}`);return}for(let E of Yn(v))l(E,b,k)},"scanTree");for(let _ of a){let b=vt.join(e,_);if(Dd(b))try{for(let k of P_(b))l(`${_}/${k}`,"self","this worktree")}catch{n.push(`could not read ${_}`)}}let u=DO(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=si(I(e,["rev-parse","--abbrev-ref","HEAD"])),m=new Map;if(t.includeBranches!==!1)for(let _ of Yn(I(e,["for-each-ref","--format=%(refname:short)%00%(objectname)","refs/heads"]))){let[b="",k=""]=_.split("\0");!b||b===f||(d(b,"branch",`Branch ${b}`),m.set(b,k))}let g;if(t.includeRemoteBranches??t.includeBranches!==!1){let _=Yn(I(e,["remote"])).map(S=>S.trim()),b=K_(I(e,["for-each-ref","--format=%(refname)%00%(objectname)%00%(committerdate:raw)%00%(symref)","refs/remotes"]),_),k=new Set;u&&k.add(`refs/remotes/origin/${u}`),p&&k.add(p.startsWith("refs/")?p:`refs/remotes/${p}`);let v=si(I(e,["rev-parse","--symbolic-full-name","--verify","--quiet","@{upstream}"]));v?.startsWith("refs/remotes/")&&k.add(v);let E=B_(b,{excludeRefs:k,ownBranch:f&&f!=="HEAD"?f:null,localTips:m,nowMs:t.nowMs??Date.now(),maxAgeDays:t.remoteBranchMaxAgeDays??$_,limit:t.remoteBranchLimit??L_});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 _=si(I(e,["rev-parse","--show-toplevel"]));for(let b of Yn(I(e,["worktree","list","--porcelain"]))){if(!b.startsWith("worktree "))continue;let k=b.slice(9).trim();if(!(!k||k===_||!Dd(k)))for(let v of a){let E=vt.join(k,v);if(Dd(E))try{for(let S of P_(E))l(`${v}/${S}`,"worktree",`Worktree ${k}`)}catch{n.push(`could not read ${v} in ${k}`)}}}}let y=[];if(p&&a.length>0){let _=I(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);_===null?n.push(Pd):y=Yn(_);let b=I(e,["ls-files","--others","--exclude-standard","--",...a]);b!==null&&(y=[...y,...Yn(b)]);let k=I(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);k!==null&&(y=[...y,...Yn(k)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:o,sightingsByNamespace:c,addedPaths:y,skipped:n,...g?{remoteBranches:g}:{}}}async function Xn(e,t={}){let n=await Fd(e,t),r=F_(n);return{ok:H_(r),findings:r,facts:n}}async function Zn(e,t,n={}){let r=jd(t);if(!ai(vt.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let o=await Fd(e,{...n,dirs:n.dirs??[vt.dirname(r)]});return U_(o,r)}var Pd,OO,$d,M_,$_,L_,ci=w(()=>{"use strict";Te();Pd="could not diff against the base ref \u2014 everything reported as info";s(Md,"isNumberCollisionsGraded");OO=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,$d=3,M_=.8,$_=30,L_=100;s(j_,"isCounterNamespace");s(Vr,"namespaceKey");s(ai,"parseNumbered");s(F_,"computeNumberCollisions");s(H_,"isCollisionFree");s(Ld,"suggestNextNumber");s(jd,"normaliseRepoPath");s(U_,"checkProposedNumber");s(B_,"selectRemoteBranches");s(K_,"parseRemoteRefs");s(si,"trimOrNull");s(Yn,"lines");s(DO,"resolveDefaultBranch");s(G_,"detectNamespaces");s(Fd,"gatherNumberCollisionFacts");s(Xn,"checkNumberCollisions");s(Zn,"checkNumberForPath")});import{execFileSync as PO}from"node:child_process";import{createHash as MO}from"node:crypto";function Hd(e){return MO("sha256").update(e).digest("hex")}function $O(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 LO(e){let t=$O(e);return t?Hd(t):null}function FO(e){return typeof e=="string"&&jO.test(e)}function W_(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(FO(t))return t;let n;try{n=PO("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?LO(n):null}var jO,Ud=w(()=>{"use strict";s(Hd,"sha256Hex");s($O,"normalizeRemoteUrl");s(LO,"projectKeyFromRemote");jO=/^[a-f0-9]{64}$/;s(FO,"isProjectKey");s(W_,"computeProjectKey")});function Wd(e){return`spec.${e}`}function qr(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 HO(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 V_(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(HO)}function di(e){return Hd(JSON.stringify(V_(e)))}var li,Bd,Kd,Gd,Vd=w(()=>{"use strict";Ud();li={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"]}},Bd="number.collision",Kd="theme.dead_class",Gd="acl.missing_revoke";s(Wd,"specDriftRuleId");s(qr,"gradeEngineStatus");s(HO,"codePointCompare");s(V_,"normalizeEvidenceForHash");s(di,"hashDetectorEvidence")});import{existsSync as UO,readFileSync as q_}from"node:fs";import{posix as BO}from"node:path";function oa(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 ia(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 ui(e){return e==='"'||e==="'"||e==="`"}function sa(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function na(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(ui(i)){o=oa(e,o);continue}if(sa(e,o)){o=ia(e,o);continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r===0))return e.slice(t,o+1);o++}return null}function KO(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(sa(e,t)){t=ia(e,t);continue}break}return e.slice(t)}function zr(e){let t=[],n=0,r=0,o=0;for(;o<e.length;){let i=e[o];if(ui(i)){o=oa(e,o);continue}if(sa(e,o)){o=ia(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=>KO(i).trim()).filter(i=>i.length>0)}function X_(e){let t=oa(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,o)=>o==="n"?`
29
- `:o==="r"?"\r":o==="t"?" ":o)}function GO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zd(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${GO(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(ui(a)){o=oa(e,o);continue}if(sa(e,o)){o=ia(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 na(e,o);if(a===";")return null;o++}return null}function Jd(e){let t={};if(!e.startsWith("{"))return t;for(let n of zr(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();ui(i[0]??"")&&(t[o]=X_(i))}return t}function WO(e,t){if(!e.startsWith("{"))return null;for(let n of zr(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 Z_(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Q_(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function eb(e,t){let n=zd(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Q_(),o=[],i=0;for(let a of zr(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=Jd(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");o.push({key:l,fields:Z_(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 tb(e,t){let n=zd(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=Q_(),o=[],i=0,a=s((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of zr(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){i++;continue}let y=Jd(f);for(let[_,b]of Object.entries(u.fields??{}))m[_]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let _=WO(f,u.children);g=_&&_.startsWith("[")?na(_,0):null}}else{if(!f.startsWith("[")){i++;continue}let y=zr(f.slice(1,-1));for(let[_,b]of Object.entries(u.fields??{})){let k=y[Number(b)];m[_]=k!==void 0&&ui(k[0]??"")?X_(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?na(_,0):null}}if(p){let y=m[t.key_field];if(!y){i++;continue}let _=(t.partition_by??[]).map(b=>m[b]??"");o.push({key:y,fields:Z_(m,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,m)}},"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 z_(e,t){return t.extractor==="object-array"?eb(e,t):tb(e,t)}function nb(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 rb(e,t,n){return`spec.drift:${e}#${t}:${n}`}function VO(e){return e.orderPath.join(" / ")||"(flat)"}function ob(e,t,n,r){let o=[],i=s((d,u,p,f,m,g)=>{o.push({id:rb(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:m,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){i("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${VO(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=d.fields[p]??"",m=u.fields[p]??"";f!==m&&i("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${m||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),f=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),m=new Set(f),g=p.filter(y=>m.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";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(nb(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 qO(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 J_(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 ib(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 m of r){let g=u.get(m.spec.path),y=u.get(m.impl.path);if(g==null||y==null){let v=g==null?m.spec.path:m.impl.path;p.push(J_(m.id,`Declared file could not be read: ${v}`)),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=z_(g,m.spec),b=z_(y,m.impl);if(_.error||b.error){p.push(J_(m.id,_.error??b.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=_.dropped>0||b.dropped>0;f.push({id:m.id,measured:!0,specRecords:_.records.length,implRecords:b.records.length,partial:k}),k&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${_.dropped} specification and ${b.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),p.push(...ob(m,_.records,b.records,e.files)),p.push(...qO(m,{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(rb(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)=>Y_[u.status]-Y_[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 qd(e){let t=e?.trim();return t||null}function aa(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 m=r(f.extractor);if(!m)return i(`${u}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return i(`${u}: unknown \`${p}.extractor\` "${m}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return i(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="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 zO(e){let t=qd(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 JO(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 sb(e,t={}){let n=s((g,y)=>BO.join(g,y),"join"),r=t.manifestPath??ra,o=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:o};if(qd(I(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!UO(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}=aa(q_(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 JO(c))try{d.set(g,q_(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,m=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:zO(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=qd(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())m.set(_,I(e,["show",`${f}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:f,files:u,skipped:o}}async function Qn(e,t={}){let n=await sb(e,t);return{...ib(n,t),facts:n}}function Yd(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var ra,Y_,pi=w(()=>{"use strict";Te();ra=".maind/spec-contracts.json";s(oa,"endOfString");s(ia,"skipComment");s(ui,"isQuote");s(sa,"isCommentStart");s(na,"sliceBalanced");s(KO,"stripLeadingTrivia");s(zr,"splitTopLevel");s(X_,"readStringLiteral");s(GO,"escapeRe");s(zd,"findSymbolArray");s(Jd,"parseObjectFields");s(WO,"objectFieldRaw");s(Z_,"pickFields");s(Q_,"makeOrdinals");s(eb,"extractObjectArray");s(tb,"extractNestedList");s(z_,"extractRecords");s(nb,"isGrounded");s(rb,"findingId");s(VO,"partitionOf");s(ob,"compareContract");s(qO,"checkAssertions");s(J_,"unreadable");Y_={open:0,warn:1,info:2,passed:3};s(ib,"computeSpecDrift");s(qd,"trimOrNull");s(aa,"parseManifest");s(zO,"resolveDefaultBranch");s(JO,"declaredPaths");s(sb,"gatherSpecDriftFacts");s(Qn,"checkSpecDrift");s(Yd,"isSpecDriftGraded")});import{execFileSync as YO}from"node:child_process";import{existsSync as XO,readFileSync as ZO}from"node:fs";import{join as QO}from"node:path";function fi(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":eD.test(o)?"never-published":"released"})}return t}function cb(e){let t=new Map;for(let n of fi(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 lb(e,t){let n=cb(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of fi(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 db(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=lb(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 ab(e,t){try{return YO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function tD(e,t={}){let n=ab(["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=QO(e,a);return{path:a,head:XO(c)?ZO(c,"utf8"):null,base:o===null?null:ab(["show",`${o}:${a}`],e)}});return{isRepo:!0,baseRef:o,files:i}}function Xd(e,t={}){return db(tD(e,t))}var eD,ca=w(()=>{"use strict";eD=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;s(fi,"parseVersionHeadings");s(cb,"findDuplicateHeadings");s(lb,"classifyIntroduced");s(db,"computeChangelogDuplicates");s(ab,"git");s(tD,"gatherChangelogFacts");s(Xd,"checkChangelogDuplicates")});import{execFileSync as nD}from"node:child_process";import{existsSync as rD,readFileSync as ub}from"node:fs";import{dirname as pb,join as fb}from"node:path";function hb(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(Yo);for(let a of i){if(r.has(a)||Yo(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(Yo))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 mb(e){let t=fi(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 Zd(e,t){try{return nD("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function gb(e,t=null){let n=Zd(["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(ub(fb(e,o),"utf8"))}catch{continue}if(i.private===!0||typeof i.name!="string"||typeof i.version!="string")continue;let a=pb(o)==="."?"":pb(o),c=fb(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=rD(c)?mb(ub(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Zd(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:mb(p).documented;r.push({dir:a,name:i.name,version:i.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function oD(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 yb(e,t={}){if(Zd(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=gb(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??oD,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 Qd(e,t={}){return hb(await yb(e,t))}var eu=w(()=>{"use strict";Xo();ca();s(hb,"computeReleaseClaims");s(mb,"claimsOf");s(Zd,"git");s(gb,"discoverPackages");s(oD,"packument");s(yb,"gatherReleaseClaimsFacts");s(Qd,"checkReleaseClaims")});import{execFileSync as iD}from"node:child_process";import{existsSync as sD,readFileSync as aD}from"node:fs";import{join as cD}from"node:path";function nu(e){let t=[],n=!1;for(let r of e.split(`
33
- `)){let o=r.trim();if(n){o===kb&&(n=!1);continue}if(o===wb){n=!0;continue}t.push(r)}return t.join(`
34
- `)}function _b(e){return e.split(`
35
- `).map(t=>t.trim()).filter(t=>t.length>0)}function vb(e,t){let n=new Map;for(let i of _b(t??""))n.set(i,(n.get(i)??0)+1);let r=[];for(let i of _b(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 xb(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=vb(nu(n.head),n.base===null?null:nu(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 tu(e,t){try{return iD("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function Sb(e,t={}){let n=tu(["ls-files","-z","--",...bb],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&tu(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,i=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=cD(e,a);return{path:a,head:sD(c)?aD(c,"utf8"):null,base:r===null?null:tu(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:i}}function ru(e,t={}){return xb(Sb(e,t))}var bb,wb,kb,ou=w(()=>{"use strict";bb=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],wb="<!-- maind:conventions v1 begin -->",kb="<!-- maind:conventions v1 end -->";s(nu,"stripManagedConventionsBlock");s(_b,"contentLines");s(vb,"proseDelta");s(xb,"computeAgentDocProse");s(tu,"git");s(Sb,"gatherAgentDocProseFacts");s(ru,"checkAgentDocProse")});var Eb,Rb,iu=w(()=>{"use strict";Eb=[".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"],Rb=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 lD}from"node:child_process";import{existsSync as dD,readFileSync as uD}from"node:fs";import{join as pD}from"node:path";function Tb(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?[]:Gs(n.base).map(o=>o.value));for(let o of Gs(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 Cb(e,t){try{return lD("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function Ab(e,t={}){let n=Cb(["ls-files","-z","--",...Eb],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=pD(e,i);return{path:i,content:dD(a)?uD(a,"utf8"):null,base:o===null?null:Cb(["show",`${o}:${i}`],e)}})}}function su(e,t={}){return Tb(Ab(e,t))}var au=w(()=>{"use strict";Xo();iu();s(Tb,"computeWorkflowYaml");s(Cb,"git");s(Ab,"gatherWorkflowYamlFacts");s(su,"checkWorkflowYaml")});import{readFileSync as fD}from"node:fs";import{join as mD,posix as hD}from"node:path";function Ib(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 ct(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 Lt(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 gD(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&&!Lt(a[1]).map(f=>ct(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||!Lt(c[1]).map(p=>ct(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Lt(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ct(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Lt(o)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...mi]};f[2]!=="("&&mi.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Nb(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(yD.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!Lt(l[1]).map(f=>ct(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=Lt(p).map(m=>ct(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(f.length===0)return null;c=f}let d=Lt(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ct(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Lt(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase(),g=f[2]==="(";if(m==="ALL")return{tables:c,roles:d,writePrivs:[...mi]};!g&&mi.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function lu(e){let t=new Map,n=[...e].sort((o,i)=>Mt(o.version,i.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let o of n){let i=Ib(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=gD(c);if(!p)continue;let f=p.roles.includes("anon"),m=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),m)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(f&&(r.anonAddressed=!1),m)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=ct(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 Lt(p)){let m=ct(f);m&&m.schema==="public"&&t.delete(m.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=ct(u[1]),f=ct(u[2]);if(p&&f&&p.schema==="public"){let m=t.get(p.name);m&&(t.delete(p.name),t.set(f.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=Nb(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,m=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!m&&!g)continue;for(let y of f){let _=t.get(y);if(_&&(m&&(_.anonAddressed=!0),g))for(let b of p.writePrivs)_.authWritesRevoked.add(b)}continue}}}return t}function cu(e){let t=[];for(let[n,r]of lu(e)){let o=[];r.anonAddressed||o.push("anon"),mi.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 Ob(e){let t=cu(e.files),n=new Map;if(e.baseFiles!==null)for(let r of cu(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 Db(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function uu(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(la)||t.endsWith(du))}function bD(e,t){try{let n=fD(e,"utf8");return n.length>t?null:n}catch{return null}}function wD(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} ${la}`),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=hD.basename(u),f=Wr(p);if(f===null)continue;let m=I(e,["show",`${r}:${u}`]);if(m===null)return o.push(`could not read ${u} at ${r} ${du}`),null;l.push({name:p,version:f,content:m})}return l}function er(e,t={}){let n=t.maxFileBytes??_D,r=[],o=Jn(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=ri(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${la}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of o){let m=[];for(let _ of f.files){let b=bD(mD(e,_.path),n);if(b===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}m.push({ref:_,content:b})}let g=m.map(({ref:_,content:b})=>({name:_.name,version:_.version,content:b})),y=a===null?null:wD(e,f.dir,m,a,r);c.push(...Ob({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:lu(g).size})}let d=l.reduce((f,m)=>f+m.migrationCount,0),u=Db(d,c.length),p={open:0,info:1};return c.sort((f,m)=>p[f.status]-p[m.status]||f.id.localeCompare(m.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var mi,yD,_D,la,du,da=w(()=>{"use strict";Te();oi();s(Ib,"stripSql");s(ct,"normalizeQualifiedIdent");s(Lt,"splitTopLevel");mi=["INSERT","UPDATE","DELETE"];s(gD,"parseDefaultAclTables");yD=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Nb,"parseTableRevoke");s(lu,"foldTableAcl");s(cu,"evaluateTableAcl");s(Ob,"computeTableAclFindings");s(Db,"deriveTableAclVerdict");_D=5e6,la="\u2014 findings reported ungraded (open)",du="\u2014 baseline degraded";s(uu,"isTableAclGraded");s(bD,"safeRead");s(wD,"baseFilesFor");s(er,"checkTableAclLint")});import{readFileSync as kD}from"node:fs";import{join as pu}from"node:path";function mu(e){return e.verdict!=="no_opinion"&&e.graded}function hu(e){let t=new Set;for(let n of e.matchAll(vD))t.add(n[1]);return t}function gu(e){return new Set([...e].map(t=>t.split("-")[0]))}function Fb(e){return e.split(`
27
+ `).filter(Boolean):[]}function PO(e){let t=si(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 W_(e,t={}){let n=t.minFiles??$d,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=vt.dirname(a),l=ai(vt.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=>F_(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>Vr(a).localeCompare(Vr(c)))}async function Fd(e,t={}){let n=[];if(si(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=W_(e,t),i=new Map(o.map(_=>[Vr(_),_])),a=[...new Set(o.map(_=>_.dir))],c=new Map,l=s((_,b,k)=>{let v=vt.dirname(_),E=ai(vt.basename(_));if(!E)return;let S=`${v}#${E.prefix}`;if(!i.has(S))return;let R=c.get(S)??new Map,P=R.get(E.number)??[];P.push({kind:b,where:k,path:_}),R.set(E.number,P),c.set(S,R)},"record"),d=s((_,b,k)=>{if(a.length===0)return;let v=I(e,["ls-tree","-r","--name-only",_,"--",...a]);if(v===null){n.push(`could not read ${k}`);return}for(let E of Yn(v))l(E,b,k)},"scanTree");for(let _ of a){let b=vt.join(e,_);if(Dd(b))try{for(let k of M_(b))l(`${_}/${k}`,"self","this worktree")}catch{n.push(`could not read ${_}`)}}let u=PO(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=si(I(e,["rev-parse","--abbrev-ref","HEAD"])),m=new Map;if(t.includeBranches!==!1)for(let _ of Yn(I(e,["for-each-ref","--format=%(refname:short)%00%(objectname)","refs/heads"]))){let[b="",k=""]=_.split("\0");!b||b===f||(d(b,"branch",`Branch ${b}`),m.set(b,k))}let g;if(t.includeRemoteBranches??t.includeBranches!==!1){let _=Yn(I(e,["remote"])).map(S=>S.trim()),b=G_(I(e,["for-each-ref","--format=%(refname)%00%(objectname)%00%(committerdate:raw)%00%(symref)","refs/remotes"]),_),k=new Set;u&&k.add(`refs/remotes/origin/${u}`),p&&k.add(p.startsWith("refs/")?p:`refs/remotes/${p}`);let v=si(I(e,["rev-parse","--symbolic-full-name","--verify","--quiet","@{upstream}"]));v?.startsWith("refs/remotes/")&&k.add(v);let E=K_(b,{excludeRefs:k,ownBranch:f&&f!=="HEAD"?f:null,localTips:m,nowMs:t.nowMs??Date.now(),maxAgeDays:t.remoteBranchMaxAgeDays??L_,limit:t.remoteBranchLimit??j_});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 _=si(I(e,["rev-parse","--show-toplevel"]));for(let b of Yn(I(e,["worktree","list","--porcelain"]))){if(!b.startsWith("worktree "))continue;let k=b.slice(9).trim();if(!(!k||k===_||!Dd(k)))for(let v of a){let E=vt.join(k,v);if(Dd(E))try{for(let S of M_(E))l(`${v}/${S}`,"worktree",`Worktree ${k}`)}catch{n.push(`could not read ${v} in ${k}`)}}}}let y=[];if(p&&a.length>0){let _=I(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);_===null?n.push(Pd):y=Yn(_);let b=I(e,["ls-files","--others","--exclude-standard","--",...a]);b!==null&&(y=[...y,...Yn(b)]);let k=I(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);k!==null&&(y=[...y,...Yn(k)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:o,sightingsByNamespace:c,addedPaths:y,skipped:n,...g?{remoteBranches:g}:{}}}async function Xn(e,t={}){let n=await Fd(e,t),r=H_(n);return{ok:U_(r),findings:r,facts:n}}async function Zn(e,t,n={}){let r=jd(t);if(!ai(vt.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let o=await Fd(e,{...n,dirs:n.dirs??[vt.dirname(r)]});return B_(o,r)}var Pd,DO,$d,$_,L_,j_,ci=w(()=>{"use strict";Te();Pd="could not diff against the base ref \u2014 everything reported as info";s(Md,"isNumberCollisionsGraded");DO=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,$d=3,$_=.8,L_=30,j_=100;s(F_,"isCounterNamespace");s(Vr,"namespaceKey");s(ai,"parseNumbered");s(H_,"computeNumberCollisions");s(U_,"isCollisionFree");s(Ld,"suggestNextNumber");s(jd,"normaliseRepoPath");s(B_,"checkProposedNumber");s(K_,"selectRemoteBranches");s(G_,"parseRemoteRefs");s(si,"trimOrNull");s(Yn,"lines");s(PO,"resolveDefaultBranch");s(W_,"detectNamespaces");s(Fd,"gatherNumberCollisionFacts");s(Xn,"checkNumberCollisions");s(Zn,"checkNumberForPath")});import{execFileSync as MO}from"node:child_process";import{createHash as $O}from"node:crypto";function Hd(e){return $O("sha256").update(e).digest("hex")}function LO(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 jO(e){let t=LO(e);return t?Hd(t):null}function HO(e){return typeof e=="string"&&FO.test(e)}function V_(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(HO(t))return t;let n;try{n=MO("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?jO(n):null}var FO,Ud=w(()=>{"use strict";s(Hd,"sha256Hex");s(LO,"normalizeRemoteUrl");s(jO,"projectKeyFromRemote");FO=/^[a-f0-9]{64}$/;s(HO,"isProjectKey");s(V_,"computeProjectKey")});function Wd(e){return`spec.${e}`}function qr(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 UO(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 q_(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(UO)}function di(e){return Hd(JSON.stringify(q_(e)))}var li,Bd,Kd,Gd,Vd=w(()=>{"use strict";Ud();li={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"]}},Bd="number.collision",Kd="theme.dead_class",Gd="acl.missing_revoke";s(Wd,"specDriftRuleId");s(qr,"gradeEngineStatus");s(UO,"codePointCompare");s(q_,"normalizeEvidenceForHash");s(di,"hashDetectorEvidence")});import{existsSync as BO,readFileSync as z_}from"node:fs";import{posix as KO}from"node:path";function oa(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 ia(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 ui(e){return e==='"'||e==="'"||e==="`"}function sa(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function na(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(ui(i)){o=oa(e,o);continue}if(sa(e,o)){o=ia(e,o);continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r===0))return e.slice(t,o+1);o++}return null}function GO(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(sa(e,t)){t=ia(e,t);continue}break}return e.slice(t)}function zr(e){let t=[],n=0,r=0,o=0;for(;o<e.length;){let i=e[o];if(ui(i)){o=oa(e,o);continue}if(sa(e,o)){o=ia(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=>GO(i).trim()).filter(i=>i.length>0)}function Z_(e){let t=oa(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,o)=>o==="n"?`
29
+ `:o==="r"?"\r":o==="t"?" ":o)}function WO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zd(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${WO(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(ui(a)){o=oa(e,o);continue}if(sa(e,o)){o=ia(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 na(e,o);if(a===";")return null;o++}return null}function Jd(e){let t={};if(!e.startsWith("{"))return t;for(let n of zr(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();ui(i[0]??"")&&(t[o]=Z_(i))}return t}function VO(e,t){if(!e.startsWith("{"))return null;for(let n of zr(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 Q_(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function eb(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function tb(e,t){let n=zd(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=eb(),o=[],i=0;for(let a of zr(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=Jd(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");o.push({key:l,fields:Q_(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 nb(e,t){let n=zd(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=eb(),o=[],i=0,a=s((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of zr(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){i++;continue}let y=Jd(f);for(let[_,b]of Object.entries(u.fields??{}))m[_]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let _=VO(f,u.children);g=_&&_.startsWith("[")?na(_,0):null}}else{if(!f.startsWith("[")){i++;continue}let y=zr(f.slice(1,-1));for(let[_,b]of Object.entries(u.fields??{})){let k=y[Number(b)];m[_]=k!==void 0&&ui(k[0]??"")?Z_(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?na(_,0):null}}if(p){let y=m[t.key_field];if(!y){i++;continue}let _=(t.partition_by??[]).map(b=>m[b]??"");o.push({key:y,fields:Q_(m,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,m)}},"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 J_(e,t){return t.extractor==="object-array"?tb(e,t):nb(e,t)}function rb(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 ob(e,t,n){return`spec.drift:${e}#${t}:${n}`}function qO(e){return e.orderPath.join(" / ")||"(flat)"}function ib(e,t,n,r){let o=[],i=s((d,u,p,f,m,g)=>{o.push({id:ob(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:m,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){i("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${qO(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=d.fields[p]??"",m=u.fields[p]??"";f!==m&&i("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${m||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),f=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),m=new Set(f),g=p.filter(y=>m.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";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(rb(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 zO(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 Y_(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 sb(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 m of r){let g=u.get(m.spec.path),y=u.get(m.impl.path);if(g==null||y==null){let v=g==null?m.spec.path:m.impl.path;p.push(Y_(m.id,`Declared file could not be read: ${v}`)),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=J_(g,m.spec),b=J_(y,m.impl);if(_.error||b.error){p.push(Y_(m.id,_.error??b.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=_.dropped>0||b.dropped>0;f.push({id:m.id,measured:!0,specRecords:_.records.length,implRecords:b.records.length,partial:k}),k&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${_.dropped} specification and ${b.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),p.push(...ib(m,_.records,b.records,e.files)),p.push(...zO(m,{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(ob(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)=>X_[u.status]-X_[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 qd(e){let t=e?.trim();return t||null}function aa(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 m=r(f.extractor);if(!m)return i(`${u}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return i(`${u}: unknown \`${p}.extractor\` "${m}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return i(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="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 JO(e){let t=qd(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 YO(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 ab(e,t={}){let n=s((g,y)=>KO.join(g,y),"join"),r=t.manifestPath??ra,o=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:o};if(qd(I(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!BO(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}=aa(z_(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 YO(c))try{d.set(g,z_(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,m=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:JO(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=qd(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())m.set(_,I(e,["show",`${f}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:f,files:u,skipped:o}}async function Qn(e,t={}){let n=await ab(e,t);return{...sb(n,t),facts:n}}function Yd(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var ra,X_,pi=w(()=>{"use strict";Te();ra=".maind/spec-contracts.json";s(oa,"endOfString");s(ia,"skipComment");s(ui,"isQuote");s(sa,"isCommentStart");s(na,"sliceBalanced");s(GO,"stripLeadingTrivia");s(zr,"splitTopLevel");s(Z_,"readStringLiteral");s(WO,"escapeRe");s(zd,"findSymbolArray");s(Jd,"parseObjectFields");s(VO,"objectFieldRaw");s(Q_,"pickFields");s(eb,"makeOrdinals");s(tb,"extractObjectArray");s(nb,"extractNestedList");s(J_,"extractRecords");s(rb,"isGrounded");s(ob,"findingId");s(qO,"partitionOf");s(ib,"compareContract");s(zO,"checkAssertions");s(Y_,"unreadable");X_={open:0,warn:1,info:2,passed:3};s(sb,"computeSpecDrift");s(qd,"trimOrNull");s(aa,"parseManifest");s(JO,"resolveDefaultBranch");s(YO,"declaredPaths");s(ab,"gatherSpecDriftFacts");s(Qn,"checkSpecDrift");s(Yd,"isSpecDriftGraded")});import{execFileSync as XO}from"node:child_process";import{existsSync as ZO,readFileSync as QO}from"node:fs";import{join as eD}from"node:path";function fi(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":tD.test(o)?"never-published":"released"})}return t}function lb(e){let t=new Map;for(let n of fi(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 db(e,t){let n=lb(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of fi(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 ub(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=db(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 cb(e,t){try{return XO("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function nD(e,t={}){let n=cb(["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=eD(e,a);return{path:a,head:ZO(c)?QO(c,"utf8"):null,base:o===null?null:cb(["show",`${o}:${a}`],e)}});return{isRepo:!0,baseRef:o,files:i}}function Xd(e,t={}){return ub(nD(e,t))}var tD,ca=w(()=>{"use strict";tD=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;s(fi,"parseVersionHeadings");s(lb,"findDuplicateHeadings");s(db,"classifyIntroduced");s(ub,"computeChangelogDuplicates");s(cb,"git");s(nD,"gatherChangelogFacts");s(Xd,"checkChangelogDuplicates")});import{execFileSync as rD}from"node:child_process";import{existsSync as oD,readFileSync as pb}from"node:fs";import{dirname as fb,join as mb}from"node:path";function gb(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(Yo);for(let a of i){if(r.has(a)||Yo(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(Yo))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 hb(e){let t=fi(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 Zd(e,t){try{return rD("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function yb(e,t=null){let n=Zd(["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(pb(mb(e,o),"utf8"))}catch{continue}if(i.private===!0||typeof i.name!="string"||typeof i.version!="string")continue;let a=fb(o)==="."?"":fb(o),c=mb(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=oD(c)?hb(pb(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Zd(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:hb(p).documented;r.push({dir:a,name:i.name,version:i.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function iD(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 _b(e,t={}){if(Zd(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=yb(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??iD,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 Qd(e,t={}){return gb(await _b(e,t))}var eu=w(()=>{"use strict";Xo();ca();s(gb,"computeReleaseClaims");s(hb,"claimsOf");s(Zd,"git");s(yb,"discoverPackages");s(iD,"packument");s(_b,"gatherReleaseClaimsFacts");s(Qd,"checkReleaseClaims")});import{execFileSync as sD}from"node:child_process";import{existsSync as aD,readFileSync as cD}from"node:fs";import{join as lD}from"node:path";function nu(e){let t=[],n=!1;for(let r of e.split(`
33
+ `)){let o=r.trim();if(n){o===vb&&(n=!1);continue}if(o===kb){n=!0;continue}t.push(r)}return t.join(`
34
+ `)}function bb(e){return e.split(`
35
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function xb(e,t){let n=new Map;for(let i of bb(t??""))n.set(i,(n.get(i)??0)+1);let r=[];for(let i of bb(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 Sb(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=xb(nu(n.head),n.base===null?null:nu(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 tu(e,t){try{return sD("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function Eb(e,t={}){let n=tu(["ls-files","-z","--",...wb],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&tu(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,i=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=lD(e,a);return{path:a,head:aD(c)?cD(c,"utf8"):null,base:r===null?null:tu(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:i}}function ru(e,t={}){return Sb(Eb(e,t))}var wb,kb,vb,ou=w(()=>{"use strict";wb=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],kb="<!-- maind:conventions v1 begin -->",vb="<!-- maind:conventions v1 end -->";s(nu,"stripManagedConventionsBlock");s(bb,"contentLines");s(xb,"proseDelta");s(Sb,"computeAgentDocProse");s(tu,"git");s(Eb,"gatherAgentDocProseFacts");s(ru,"checkAgentDocProse")});var Rb,Cb,iu=w(()=>{"use strict";Rb=[".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"],Cb=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 dD}from"node:child_process";import{existsSync as uD,readFileSync as pD}from"node:fs";import{join as fD}from"node:path";function Ab(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?[]:Gs(n.base).map(o=>o.value));for(let o of Gs(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 Tb(e,t){try{return dD("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function Ib(e,t={}){let n=Tb(["ls-files","-z","--",...Rb],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=fD(e,i);return{path:i,content:uD(a)?pD(a,"utf8"):null,base:o===null?null:Tb(["show",`${o}:${i}`],e)}})}}function su(e,t={}){return Ab(Ib(e,t))}var au=w(()=>{"use strict";Xo();iu();s(Ab,"computeWorkflowYaml");s(Tb,"git");s(Ib,"gatherWorkflowYamlFacts");s(su,"checkWorkflowYaml")});import{readFileSync as mD}from"node:fs";import{join as hD,posix as gD}from"node:path";function Nb(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 ct(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 Lt(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 yD(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&&!Lt(a[1]).map(f=>ct(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||!Lt(c[1]).map(p=>ct(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Lt(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ct(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Lt(o)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...mi]};f[2]!=="("&&mi.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Ob(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(_D.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!Lt(l[1]).map(f=>ct(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=Lt(p).map(m=>ct(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(f.length===0)return null;c=f}let d=Lt(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ct(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Lt(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase(),g=f[2]==="(";if(m==="ALL")return{tables:c,roles:d,writePrivs:[...mi]};!g&&mi.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function lu(e){let t=new Map,n=[...e].sort((o,i)=>Mt(o.version,i.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let o of n){let i=Nb(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=yD(c);if(!p)continue;let f=p.roles.includes("anon"),m=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),m)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(f&&(r.anonAddressed=!1),m)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=ct(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 Lt(p)){let m=ct(f);m&&m.schema==="public"&&t.delete(m.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=ct(u[1]),f=ct(u[2]);if(p&&f&&p.schema==="public"){let m=t.get(p.name);m&&(t.delete(p.name),t.set(f.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=Ob(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,m=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!m&&!g)continue;for(let y of f){let _=t.get(y);if(_&&(m&&(_.anonAddressed=!0),g))for(let b of p.writePrivs)_.authWritesRevoked.add(b)}continue}}}return t}function cu(e){let t=[];for(let[n,r]of lu(e)){let o=[];r.anonAddressed||o.push("anon"),mi.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 Db(e){let t=cu(e.files),n=new Map;if(e.baseFiles!==null)for(let r of cu(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 Pb(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function uu(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(la)||t.endsWith(du))}function wD(e,t){try{let n=mD(e,"utf8");return n.length>t?null:n}catch{return null}}function kD(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} ${la}`),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=gD.basename(u),f=Wr(p);if(f===null)continue;let m=I(e,["show",`${r}:${u}`]);if(m===null)return o.push(`could not read ${u} at ${r} ${du}`),null;l.push({name:p,version:f,content:m})}return l}function er(e,t={}){let n=t.maxFileBytes??bD,r=[],o=Jn(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=ri(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${la}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of o){let m=[];for(let _ of f.files){let b=wD(hD(e,_.path),n);if(b===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}m.push({ref:_,content:b})}let g=m.map(({ref:_,content:b})=>({name:_.name,version:_.version,content:b})),y=a===null?null:kD(e,f.dir,m,a,r);c.push(...Db({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:lu(g).size})}let d=l.reduce((f,m)=>f+m.migrationCount,0),u=Pb(d,c.length),p={open:0,info:1};return c.sort((f,m)=>p[f.status]-p[m.status]||f.id.localeCompare(m.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var mi,_D,bD,la,du,da=w(()=>{"use strict";Te();oi();s(Nb,"stripSql");s(ct,"normalizeQualifiedIdent");s(Lt,"splitTopLevel");mi=["INSERT","UPDATE","DELETE"];s(yD,"parseDefaultAclTables");_D=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Ob,"parseTableRevoke");s(lu,"foldTableAcl");s(cu,"evaluateTableAcl");s(Db,"computeTableAclFindings");s(Pb,"deriveTableAclVerdict");bD=5e6,la="\u2014 findings reported ungraded (open)",du="\u2014 baseline degraded";s(uu,"isTableAclGraded");s(wD,"safeRead");s(kD,"baseFilesFor");s(er,"checkTableAclLint")});import{readFileSync as vD}from"node:fs";import{join as pu}from"node:path";function mu(e){return e.verdict!=="no_opinion"&&e.graded}function hu(e){let t=new Set;for(let n of e.matchAll(xD))t.add(n[1]);return t}function gu(e){return new Set([...e].map(t=>t.split("-")[0]))}function Hb(e){return e.split(`
38
38
  `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
39
- `)}function yu(e){let t=gu(e.tokens),n=[];for(let{path:r,content:o}of e.sources){let i=Fb(o),a=new Set;for(let c of i.matchAll(xD)){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 Pb(e){return`${e.file} ${e.klass}`}function SD(e,t){let n=t===null?null:new Set(t.map(Pb));return e.map(r=>({...r,status:n!==null&&n.has(Pb(r))?"info":"open"}))}function Hb(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function _u(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function $b(e,t){let n=I(e,["ls-files","--",...t]);return n===null?[]:n.split(`
40
- `).filter(Boolean)}function tr(e,t={}){let n=t.maxFileBytes??ED,r=new Set;for(let u of $b(e,["*.css"])){let p=fu(pu(e,u),n);if(p!==null)for(let f of hu(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=>Mb.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):Mb,i=[];for(let u of $b(e,o)){if(!_u(u))continue;let p=fu(pu(e,u),n);p!==null&&i.push({path:u,content:p})}let a=yu({tokens:r,sources:i}),c=t.includeBaseline===!1?null:RD(e,o,n,t.baseRef),l=SD(a,c?.findings??null),d=Hb(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:gu(r).size,findings:l,scannedFiles:i.length,graded:c!==null,baseRef:c?.mergeBase??null}}function RD(e,t,n,r){let o=r??TD(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}`]):fu(pu(e,p),n),"atBase"),d=new Set;for(let p of Lb(e,i,["*.css"])){let f=l(p);if(f!==null)for(let m of hu(f))d.add(m)}if(d.size===0)return{findings:[],mergeBase:i};let u=[];for(let p of Lb(e,i,t)){if(!_u(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:yu({tokens:d,sources:u}),mergeBase:i}}function Lb(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=>CD(o,i)))}function CD(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 TD(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 fu(e,t){try{let n=kD(e,"utf8");return n.length>t?null:n}catch{return null}}var jb,vD,xD,Mb,ED,ua=w(()=>{"use strict";Te();s(mu,"isThemeClassDriftGraded");jb=["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"],vD=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,xD=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+jb.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(hu,"extractTokens");s(gu,"deriveNamespaces");s(Fb,"stripCommentLines");s(yu,"evaluateThemeClasses");s(Pb,"findingKey");s(SD,"gradeAgainstBaseline");s(Hb,"deriveThemeClassVerdict");Mb=["*.ts","*.tsx","*.js","*.jsx"],ED=15e5;s(_u,"isScannableSource");s($b,"listTracked");s(tr,"checkThemeClassDrift");s(RD,"baselineFindings");s(Lb,"listTrackedAt");s(CD,"matchesSourcePattern");s(TD,"resolveBaseRef");s(fu,"safeRead")});function bu(e){return li[e].version}function Ft(e,t,n,r){return{detector_id:e,detector_version:bu(e),state:t,finding_count:n,...r?{reason:r}:{}}}function X(e,t,n){return{summary:Ft(e,t,0,n),findings:[]}}function Vb(e){return e==="open"||e==="warn"||e==="info"}function AD(e){let t="det_number_collisions";if(!e.ok)return X(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return X(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return X(t,"not_applicable","no numbered namespaces");if(!Md(n))return X(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let o=[];for(let i of r){if(!Vb(i.status))continue;let{level:a,baseline:c}=qr(i.status);o.push({detector_id:t,rule_id:Bd,level:a,baseline:c,evidence:[...i.ownPath?[i.ownPath]:[],...i.sightings.map(l=>l.path)],title:i.title})}return{summary:Ft(t,"ran",o.length),findings:o}}function ID(e){let t="det_spec_drift";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return X(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return X(t,"not_applicable",n.reason??"no opinion");if(!Yd(n))return X(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let o of n.findings){if(!Vb(o.status))continue;let{level:i,baseline:a}=qr(o.status,{excepted:o.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Wd(o.dimension),level:i,baseline:a,evidence:[o.id],title:o.title})}return{summary:Ft(t,"ran",r.length),findings:r}}function ND(e){let t="det_theme_class_drift";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable","no theme tokens");if(!mu(n))return X(t,"ungraded","no merge-base to grade against");let r=[];for(let o of n.findings){let{level:i,baseline:a}=qr(o.status);r.push({detector_id:t,rule_id:Kd,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:Ft(t,"ran",r.length),findings:r}}function OD(e){let t="det_table_acl_lint";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable","no supabase migrations");if(!uu(n))return X(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}=qr(o.status);r.push({detector_id:t,rule_id:Gd,level:i,baseline:a,evidence:[o.project,o.table,...o.missing],title:o.title})}return{summary:Ft(t,"ran",r.length),findings:r}}function DD(e){let t="det_changelog_duplicates";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return X(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:Ft(t,"ran",r.length),findings:r}}function PD(e){let t="det_workflow_yaml";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return X(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:Ft(t,"ran",r.length),findings:r}}function MD(e){let t="det_release_claims";if(!e.ok)return X(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?X(t,"ungraded",n.reason??"registry unreachable"):X(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:Ft(t,"ran",r.length),findings:r}}function $D(e){let t="det_agent_doc_prose";if(!e.ok)return X(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?X(t,"ungraded",n.reason??"no base ref to grade against"):X(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:Ft(t,"ran",r.length),findings:r}}function wu(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||pa[e.level]-pa[t.level]||Bb[e.baseline]-Bb[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Kb(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function LD(e){let t=new Map,n=new Map;for(let o of e)if(o.baseline==="introduced"){let i=di(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:bu(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,pa[o.level]<pa[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:bu(o.detector_id),rule_id:o.rule_id,level:o.level,baseline:"pre_existing",evidence_hash:di(o.evidence),count:o.count});return r.sort(wu)}function jD(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function Xe(e){let t={det_number_collisions:AD(e.number),det_spec_drift:ID(e.spec),det_theme_class_drift:ND(e.theme),det_table_acl_lint:OD(e.acl),det_changelog_duplicates:DD(e.changelog),det_workflow_yaml:PD(e.workflow),det_release_claims:MD(e.release),det_agent_doc_prose:$D(e.agentDoc)},n=Ub.map(l=>t[l].summary),r=Ub.flatMap(l=>t[l].findings),o=LD(r),i=[...o].sort((l,d)=>Kb(l)-Kb(d)||wu(l,d)).slice(0,Gb).sort(wu),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:di(l.evidence),title:l.title}));return{findings:i,coverage:jD(n,a),engines:n,local:c,truncated:a}}function jt(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 vu(e){return e instanceof Error?e.message:String(e)}async function sn(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:vu(t)}}}async function xu(e,t={}){let n={...Wb,...t.engines};try{if(!qb(e))return Xe(jt("not a git work tree"));let r=await zb(e,n,t.baseRef),o=await ku(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Xe({...r,number:o})}catch(r){return Xe(jt(`detector adapter failed: ${vu(r)}`))}}async function Su(e,t={}){let n={...Wb,...t.engines};try{if(!qb(e)){let a=Xe(jt("not a git work tree"));return{commit:a,local:a}}let r=await zb(e,n,t.baseRef),o=await ku(e,n,t.baseRef,"commit"),i=await ku(e,n,t.baseRef,"local");return{commit:Xe({...r,number:o}),local:Xe({...r,number:i})}}catch(r){let o=Xe(jt(`detector adapter failed: ${vu(r)}`));return{commit:o,local:o}}}function qb(e){return I(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function zb(e,t,n){let r=n?{baseRef:n}:{};return{spec:await sn(()=>t.spec(e,r)),theme:await sn(()=>t.theme(e,r)),acl:await sn(()=>t.acl(e,r)),changelog:await sn(()=>t.changelog(e,r)),workflow:await sn(()=>t.workflow(e,r)),release:await sn(()=>t.release(e,r)),agentDoc:await sn(()=>t.agentDoc(e,r))}}function ku(e,t,n,r,o){let i=r==="local";return sn(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:i,includeRemoteBranches:i,includeWorktrees:o??i}))}var Gb,Wb,Ub,pa,Bb,Eu=w(()=>{"use strict";Te();Vd();ci();pi();eu();ou();au();ca();da();ua();Gb=64,Wb={number:s((e,t)=>Xn(e,t),"number"),spec:s((e,t)=>Qn(e,t),"spec"),theme:s((e,t)=>tr(e,t),"theme"),acl:s((e,t)=>er(e,t),"acl"),changelog:s((e,t)=>Xd(e,t),"changelog"),workflow:s((e,t)=>su(e,t),"workflow"),release:s((e,t)=>Qd(e,t),"release"),agentDoc:s((e,t)=>ru(e,t),"agentDoc")},Ub=["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(bu,"versionOf");s(Ft,"summary");s(X,"noFindings");s(Vb,"isFindingStatus");s(AD,"adaptNumber");s(ID,"adaptSpec");s(ND,"adaptTheme");s(OD,"adaptAcl");s(DD,"adaptChangelog");s(PD,"adaptWorkflow");s(MD,"adaptRelease");s($D,"adaptAgentDoc");pa={open:0,warn:1,info:2},Bb={introduced:0,pre_existing:1};s(wu,"compareWire");s(Kb,"capPriority");s(LD,"buildWire");s(jD,"deriveCoverage");s(Xe,"adaptDetectorReports");s(jt,"unavailableDetectorReports");s(vu,"errorText");s(sn,"attempt");s(xu,"runRepoHealthDetectors");s(Su,"runRepoHealthDetectorScopes");s(qb,"insideWorkTree");s(zb,"runSharedEngines");s(ku,"runNumberEngine")});var Jb,Ru=w(()=>{"use strict";iu();Jb=[{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:Rb},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function Yb(e){let t=new Set;for(let[n,r]of e.paths)for(let o of Jb){if(t.has(o.flag)||!o.path.test(n)||o.onlyWhenAdded&&r!=="added")continue;if(!o.content){t.add(o.flag);continue}let i=FD(n,e);i!==null&&o.content.test(i)&&t.add(o.flag)}return[...t].sort()}function FD(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
43
- `):t.readUntracked(e)}var Xb=w(()=>{"use strict";Ru();s(Yb,"scanRiskFlags");s(FD,"contentForPath")});var an,Cu,cn,Jr,hi,Yr,Tu,fa,ma,ha,Au,Zb,Xr=w(()=>{"use strict";an="3",Cu=`
39
+ `)}function yu(e){let t=gu(e.tokens),n=[];for(let{path:r,content:o}of e.sources){let i=Hb(o),a=new Set;for(let c of i.matchAll(SD)){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 Mb(e){return`${e.file} ${e.klass}`}function ED(e,t){let n=t===null?null:new Set(t.map(Mb));return e.map(r=>({...r,status:n!==null&&n.has(Mb(r))?"info":"open"}))}function Ub(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function _u(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Lb(e,t){let n=I(e,["ls-files","--",...t]);return n===null?[]:n.split(`
40
+ `).filter(Boolean)}function tr(e,t={}){let n=t.maxFileBytes??RD,r=new Set;for(let u of Lb(e,["*.css"])){let p=fu(pu(e,u),n);if(p!==null)for(let f of hu(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=>$b.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):$b,i=[];for(let u of Lb(e,o)){if(!_u(u))continue;let p=fu(pu(e,u),n);p!==null&&i.push({path:u,content:p})}let a=yu({tokens:r,sources:i}),c=t.includeBaseline===!1?null:CD(e,o,n,t.baseRef),l=ED(a,c?.findings??null),d=Ub(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:gu(r).size,findings:l,scannedFiles:i.length,graded:c!==null,baseRef:c?.mergeBase??null}}function CD(e,t,n,r){let o=r??AD(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}`]):fu(pu(e,p),n),"atBase"),d=new Set;for(let p of jb(e,i,["*.css"])){let f=l(p);if(f!==null)for(let m of hu(f))d.add(m)}if(d.size===0)return{findings:[],mergeBase:i};let u=[];for(let p of jb(e,i,t)){if(!_u(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:yu({tokens:d,sources:u}),mergeBase:i}}function jb(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=>TD(o,i)))}function TD(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 AD(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 fu(e,t){try{let n=vD(e,"utf8");return n.length>t?null:n}catch{return null}}var Fb,xD,SD,$b,RD,ua=w(()=>{"use strict";Te();s(mu,"isThemeClassDriftGraded");Fb=["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"],xD=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,SD=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Fb.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(hu,"extractTokens");s(gu,"deriveNamespaces");s(Hb,"stripCommentLines");s(yu,"evaluateThemeClasses");s(Mb,"findingKey");s(ED,"gradeAgainstBaseline");s(Ub,"deriveThemeClassVerdict");$b=["*.ts","*.tsx","*.js","*.jsx"],RD=15e5;s(_u,"isScannableSource");s(Lb,"listTracked");s(tr,"checkThemeClassDrift");s(CD,"baselineFindings");s(jb,"listTrackedAt");s(TD,"matchesSourcePattern");s(AD,"resolveBaseRef");s(fu,"safeRead")});function bu(e){return li[e].version}function Ft(e,t,n,r){return{detector_id:e,detector_version:bu(e),state:t,finding_count:n,...r?{reason:r}:{}}}function X(e,t,n){return{summary:Ft(e,t,0,n),findings:[]}}function qb(e){return e==="open"||e==="warn"||e==="info"}function ID(e){let t="det_number_collisions";if(!e.ok)return X(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return X(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return X(t,"not_applicable","no numbered namespaces");if(!Md(n))return X(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let o=[];for(let i of r){if(!qb(i.status))continue;let{level:a,baseline:c}=qr(i.status);o.push({detector_id:t,rule_id:Bd,level:a,baseline:c,evidence:[...i.ownPath?[i.ownPath]:[],...i.sightings.map(l=>l.path)],title:i.title})}return{summary:Ft(t,"ran",o.length),findings:o}}function ND(e){let t="det_spec_drift";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return X(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return X(t,"not_applicable",n.reason??"no opinion");if(!Yd(n))return X(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let o of n.findings){if(!qb(o.status))continue;let{level:i,baseline:a}=qr(o.status,{excepted:o.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Wd(o.dimension),level:i,baseline:a,evidence:[o.id],title:o.title})}return{summary:Ft(t,"ran",r.length),findings:r}}function OD(e){let t="det_theme_class_drift";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable","no theme tokens");if(!mu(n))return X(t,"ungraded","no merge-base to grade against");let r=[];for(let o of n.findings){let{level:i,baseline:a}=qr(o.status);r.push({detector_id:t,rule_id:Kd,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:Ft(t,"ran",r.length),findings:r}}function DD(e){let t="det_table_acl_lint";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable","no supabase migrations");if(!uu(n))return X(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}=qr(o.status);r.push({detector_id:t,rule_id:Gd,level:i,baseline:a,evidence:[o.project,o.table,...o.missing],title:o.title})}return{summary:Ft(t,"ran",r.length),findings:r}}function PD(e){let t="det_changelog_duplicates";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return X(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:Ft(t,"ran",r.length),findings:r}}function MD(e){let t="det_workflow_yaml";if(!e.ok)return X(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return X(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return X(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:Ft(t,"ran",r.length),findings:r}}function $D(e){let t="det_release_claims";if(!e.ok)return X(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?X(t,"ungraded",n.reason??"registry unreachable"):X(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:Ft(t,"ran",r.length),findings:r}}function LD(e){let t="det_agent_doc_prose";if(!e.ok)return X(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?X(t,"ungraded",n.reason??"no base ref to grade against"):X(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:Ft(t,"ran",r.length),findings:r}}function wu(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||pa[e.level]-pa[t.level]||Kb[e.baseline]-Kb[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Gb(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function jD(e){let t=new Map,n=new Map;for(let o of e)if(o.baseline==="introduced"){let i=di(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:bu(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,pa[o.level]<pa[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:bu(o.detector_id),rule_id:o.rule_id,level:o.level,baseline:"pre_existing",evidence_hash:di(o.evidence),count:o.count});return r.sort(wu)}function FD(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function Xe(e){let t={det_number_collisions:ID(e.number),det_spec_drift:ND(e.spec),det_theme_class_drift:OD(e.theme),det_table_acl_lint:DD(e.acl),det_changelog_duplicates:PD(e.changelog),det_workflow_yaml:MD(e.workflow),det_release_claims:$D(e.release),det_agent_doc_prose:LD(e.agentDoc)},n=Bb.map(l=>t[l].summary),r=Bb.flatMap(l=>t[l].findings),o=jD(r),i=[...o].sort((l,d)=>Gb(l)-Gb(d)||wu(l,d)).slice(0,Wb).sort(wu),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:di(l.evidence),title:l.title}));return{findings:i,coverage:FD(n,a),engines:n,local:c,truncated:a}}function jt(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 vu(e){return e instanceof Error?e.message:String(e)}async function sn(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:vu(t)}}}async function xu(e,t={}){let n={...Vb,...t.engines};try{if(!zb(e))return Xe(jt("not a git work tree"));let r=await Jb(e,n,t.baseRef),o=await ku(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Xe({...r,number:o})}catch(r){return Xe(jt(`detector adapter failed: ${vu(r)}`))}}async function Su(e,t={}){let n={...Vb,...t.engines};try{if(!zb(e)){let a=Xe(jt("not a git work tree"));return{commit:a,local:a}}let r=await Jb(e,n,t.baseRef),o=await ku(e,n,t.baseRef,"commit"),i=await ku(e,n,t.baseRef,"local");return{commit:Xe({...r,number:o}),local:Xe({...r,number:i})}}catch(r){let o=Xe(jt(`detector adapter failed: ${vu(r)}`));return{commit:o,local:o}}}function zb(e){return I(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function Jb(e,t,n){let r=n?{baseRef:n}:{};return{spec:await sn(()=>t.spec(e,r)),theme:await sn(()=>t.theme(e,r)),acl:await sn(()=>t.acl(e,r)),changelog:await sn(()=>t.changelog(e,r)),workflow:await sn(()=>t.workflow(e,r)),release:await sn(()=>t.release(e,r)),agentDoc:await sn(()=>t.agentDoc(e,r))}}function ku(e,t,n,r,o){let i=r==="local";return sn(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:i,includeRemoteBranches:i,includeWorktrees:o??i}))}var Wb,Vb,Bb,pa,Kb,Eu=w(()=>{"use strict";Te();Vd();ci();pi();eu();ou();au();ca();da();ua();Wb=64,Vb={number:s((e,t)=>Xn(e,t),"number"),spec:s((e,t)=>Qn(e,t),"spec"),theme:s((e,t)=>tr(e,t),"theme"),acl:s((e,t)=>er(e,t),"acl"),changelog:s((e,t)=>Xd(e,t),"changelog"),workflow:s((e,t)=>su(e,t),"workflow"),release:s((e,t)=>Qd(e,t),"release"),agentDoc:s((e,t)=>ru(e,t),"agentDoc")},Bb=["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(bu,"versionOf");s(Ft,"summary");s(X,"noFindings");s(qb,"isFindingStatus");s(ID,"adaptNumber");s(ND,"adaptSpec");s(OD,"adaptTheme");s(DD,"adaptAcl");s(PD,"adaptChangelog");s(MD,"adaptWorkflow");s($D,"adaptRelease");s(LD,"adaptAgentDoc");pa={open:0,warn:1,info:2},Kb={introduced:0,pre_existing:1};s(wu,"compareWire");s(Gb,"capPriority");s(jD,"buildWire");s(FD,"deriveCoverage");s(Xe,"adaptDetectorReports");s(jt,"unavailableDetectorReports");s(vu,"errorText");s(sn,"attempt");s(xu,"runRepoHealthDetectors");s(Su,"runRepoHealthDetectorScopes");s(zb,"insideWorkTree");s(Jb,"runSharedEngines");s(ku,"runNumberEngine")});var Yb,Ru=w(()=>{"use strict";iu();Yb=[{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:Cb},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function Xb(e){let t=new Set;for(let[n,r]of e.paths)for(let o of Yb){if(t.has(o.flag)||!o.path.test(n)||o.onlyWhenAdded&&r!=="added")continue;if(!o.content){t.add(o.flag);continue}let i=HD(n,e);i!==null&&o.content.test(i)&&t.add(o.flag)}return[...t].sort()}function HD(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
43
+ `):t.readUntracked(e)}var Zb=w(()=>{"use strict";Ru();s(Xb,"scanRiskFlags");s(HD,"contentForPath")});var an,Cu,cn,Jr,hi,Yr,Tu,fa,ma,ha,Au,Qb,Xr=w(()=>{"use strict";an="3",Cu=`
44
44
  CREATE TABLE IF NOT EXISTS meta (
45
45
  key TEXT PRIMARY KEY,
46
46
  value TEXT NOT NULL
@@ -128,23 +128,23 @@ CREATE TABLE IF NOT EXISTS embeddings (
128
128
  vec BLOB NOT NULL,
129
129
  content_hash TEXT NOT NULL
130
130
  );
131
- `,cn="schema_version",Jr="last_index_commit",hi="last_indexed_at",Yr="edges_dirty",Tu="resolve_config_fp",fa="embed_recipe_version",ma="embed_model",ha="embed_dim",Au="last_synced_at",Zb="last_synced_commit"});function Iu(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 Qb(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of Iu(e.name))t.add(o);for(let o of Iu(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function ew(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 Iu(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Nu=w(()=>{"use strict";s(Iu,"splitIdentifier");s(Qb,"buildSearchText");s(ew,"toFtsMatchQuery")});import{readFileSync as tw}from"node:fs";import{posix as nw}from"node:path";function rw(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 nr(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function ow(e){return e==="added"?0:e==="modified"?1:2}function HD(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 gi,Ou=w(()=>{"use strict";Xo();Wy();dd();qy();Xy();pd();o_();Te();h_();vd();Od();ci();Eu();pi();Xb();Xr();Nu();gi=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(cn),o=await this.store.countFiles()>0;(t.full||o&&r!==an)&&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=_d(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=l_(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(Yr,"1"))},"markEdgesDirty");for(let b of i)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of a){m++;let k=u_(this.repoRoot,b.path);if(!k){u.filesSkipped++;continue}let v=l.get(b.path);if(v&&v.mtimeMs===k.mtimeMs&&v.size===k.size){u.filesSkipped++;continue}let E=this.readRepoFile(b.path);if(E===null){u.filesSkipped++;continue}let S=Zs(E);if(v&&v.contentHash===S){await this.store.upsertFile({...v,mtimeMs:k.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,Qb(x));let K={path:b.path,language:b.language,contentHash:S,mtimeMs:k.mtimeMs,size:k.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:m,total:a.length})}let g=zy(this.repoRoot),y=await this.store.getMeta(Tu)!==g.fingerprint;if(p||y||await this.store.getMeta(Yr)==="1"){let b=n_(await this.store.getNameIndex()),k=new Kr(g.config,b.files),v=r_(await this.store.getAllFacts(),b,k);await this.store.replaceCrossFileEdges(v),await this.store.setMeta(Tu,g.fingerprint),await this.store.setMeta(Yr,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...ld]),k=await this.store.getEmbeddingContentHashes(),v=[];for(let S of b){let R=Gy(S),P=Zs(`${this.embedder.recipeVersion}\0${R}`);k.get(S.nodeKey)!==P&&v.push({nodeKey:S.nodeKey,text:R,hash:P})}let E=64;for(let S=0;S<v.length;S+=E){let R=v.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,v.length);t.onProgress?.({path:"embedding symbols",done:K,total:v.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(fa,this.embedder.recipeVersion),await this.store.setMeta(ma,this.embedder.model),await this.store.setMeta(ha,String(this.embedder.dim))}await this.store.setMeta(cn,an),await this.store.setMeta(hi,String(n));let _=ni(this.repoRoot);return _&&await this.store.setMeta(Jr,_),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(hi);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(Jr),schemaVersion:await this.store.getMeta(cn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=nr(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({...rw(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=nr(n.limit,20,100),o=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Vy(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({...rw(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=nr(n.maxDepth,3,5),i=nr(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 m of u){let g=await this.store.neighbors(m,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=tw(nw.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(nr(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=_d(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=nr(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=Xs(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(ni(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return k_(this.repoRoot,n,t)}async checkDivergence(t={}){return ii(this.repoRoot,t)}async checkNumberCollisions(t={}){return Xn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Zn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Qn(this.repoRoot,t)}async reviewDetectors(t={}){return xu(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Su(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Xs(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=m_(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",a=Yb({paths:n,hunks:o,readUntracked:s(f=>this.readRepoFileHead(f,f_),"readUntracked")}),c=c_(n.keys()),l=nr(t.limit,64,t.attest?rn:200),d=[],u=0,p=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;u++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),_=g!==null&&y!==null&&Zs(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let b=n.get(f.path)??"modified",k=o.get(f.path);for(let v of m)d.push(HD(v,b,k,_))}return d.sort((f,m)=>ow(f.change)-ow(m.change)||(f.filePath<m.filePath?-1:f.filePath>m.filePath?1:0)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:ni(this.repoRoot),dirty:bd(this.repoRoot),baseSha:t.since?Qs(this.repoRoot,t.since):null,mergeBaseSha:t.since?yd(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 tw(nw.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(rw,"toHit");s(nr,"clampLimit");s(ow,"changeRank");s(HD,"classifyReviewSymbol")});var iw=w(()=>{"use strict";Te()});var UD,gY,sw=w(()=>{"use strict";Te();UD=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],gY=new RegExp(UD.join("|"),"g")});import{existsSync as Du,readdirSync as BD,readFileSync as KD}from"node:fs";import{spawnSync as GD}from"node:child_process";import{dirname as WD,join as ga,posix as Pu}from"node:path";function cw(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 ${Mu} 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 ${Mu} 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(Mt);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(Mt),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(Mt),m=e.remote.versions.filter(g=>!i.has(g)).sort(Mt);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function lw(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function uw(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 aw(e,t,n){let r=e(t,VD,n);return r.ok===!1?uw(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
133
- `).map(o=>o.trim()).filter(Boolean)}}function pw(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 qD(e){let t=I(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=WD(t);return n===e?null:n}function zD(e,t,n){let r=Pu.dirname(t),i=[{path:ga(e,r,"config.toml"),source:"worktree"}],a=qD(e);a&&i.push({path:ga(a,r,"config.toml"),source:"main_worktree"});for(let c of i)if(Du(c.path))try{let l=pw(KD(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 JD(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||!Du(a))continue;let c=ga(a,t);if(Du(c))try{for(let l of BD(c)){let d=Wr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function $u(e,t={}){let n=t.runPsql??dw,r=t.timeoutMs??15e3,o=[],i=Jn(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=zD(e,p.dir,o),m=f.source==="missing"?null:aw(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?aw(n,t.remoteDbUrl,r):null,y=cw({dir:p.dir,projectRoot:ga(e,Pu.dirname(Pu.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:JD(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=lw(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 Mu,dw,VD,fw=w(()=>{"use strict";Te();oi();Mu=54322;s(cw,"evaluateLedgerProject");s(lw,"deriveLedgerVerdict");dw=s((e,t,n)=>{let r=GD("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"),VD="select version from supabase_migrations.schema_migrations order by version";s(uw,"classifyLedgerError");s(aw,"readLedger");s(pw,"parseDbPort");s(qD,"mainWorktreeRoot");s(zD,"resolveConfig");s(JD,"gatherSiblingVersions");s($u,"checkMigrationLedgerDrift")});function Ze(e){return typeof e=="string"?e:String(e??"")}function yi(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function Lu(e){return{nodeKey:Ze(e.node_key),kind:Ze(e.kind),name:Ze(e.name),qualifiedName:Ze(e.qualified_name),filePath:Ze(e.file_path),startLine:yi(e.start_line),endLine:yi(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function gw(e){return{path:Ze(e.path),language:Ze(e.language),contentHash:Ze(e.content_hash),mtimeMs:yi(e.mtime_ms),size:yi(e.size),indexedAt:yi(e.indexed_at)}}function ju(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(ln.meta).get(o);return i===void 0?null:Ze(i.value)},"metaValue");return{meta(){let o=r(cn),i=r(hi);return{schemaVersion:o,schemaCurrent:o===an,edgesDirty:r(Yr)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n(ln.file).get(o);return i===void 0?null:gw(i)},files(o){let i=new Map;for(let a of new Set(o)){let c=n(ln.file).get(a);c!==void 0&&i.set(a,gw(c))}return i},symbolsInFile(o,i=YD){return n(ln.symbolsInFile).all(o,i).map(Lu)},symbolsNamed(o,i=XD){let a=new Map;for(let c of new Set(o)){let l=n(ln.symbolsNamed).all(c,i);l.length>0&&a.set(c,l.map(Lu))}return a},callersOfFile(o,i=ZD){return n(ln.callersOfFile).all(o,o,i).map(c=>({calleeKey:Ze(c.callee_key),kind:Ze(c.edge_kind),caller:Lu(c)}))},importersOf(o,i=QD){let a=n(ln.importersOf).all(wt(o),i),c=[];for(let l of a){let d=Ze(l.src_key),u=d.endsWith(hw)?d.slice(0,-hw.length):d;u!==o&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function _i(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var mw,ln,YD,XD,ZD,QD,hw,Fu=w(()=>{"use strict";zn();Xr();mw="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",ln={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 ${mw} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${mw} 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 ?"},YD=400,XD=8,ZD=600,QD=200,hw="#<module>";s(Ze,"str");s(yi,"num");s(Lu,"toSymbol");s(gw,"toFileRow");s(ju,"createIndexReader");s(_i,"isFileCurrent")});var Hu,Uu=w(()=>{"use strict";Hu="0.2.0"});function Bu(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:rn,attest:!0}}function Ku(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>ya||a!==void 0&&a.length>_a){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=_w?{kind:i.kind}:{},...i.language&&i.language.length<=bw?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),ww)})}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:Hu},dropped:n}}function Gu(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 Wu(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 ${rn} (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 Vu(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===yw&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===yw?{kind:"invalid_params",code:n,detail:r,issues:eP(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function eP(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 qu(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 ya,_a,_w,bw,ww,yw,tP,kw=w(()=>{"use strict";Xo();Uu();ya=200,_a=512,_w=64,bw=32,ww=1e4;s(Bu,"attestReviewOptions");s(Ku,"buildAttestPayload");s(Gu,"attestPersistDecision");s(Wu,"attestCoverageNote");yw=-32602;s(Vu,"classifyMcpErrorText");s(eP,"parseIssues");s(qu,"isLegacyAttestRejection");tP=`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 dn=w(()=>{"use strict";Lh();Ou();vd();Ru();Te();ca();au();eu();ou();Od();iw();sw();Rd();ci();ua();pi();oi();da();fw();Vd();Eu();ci();pi();ua();da();Vs();dd();Xr();Fu();zs();Uu();kw()});import{execFileSync as nP}from"node:child_process";import{createHash as rP}from"node:crypto";import{mkdirSync as oP,readFileSync as iP,renameSync as sP,writeFileSync as aP}from"node:fs";import{dirname as vw,join as xw}from"node:path";function lt(e=process.cwd()){try{let t=nP("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 Zr(e){return rP("sha256").update(e).digest("hex").slice(0,16)}function ba(e){return xw(e,cP)}function Sw(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Ew(e,t,n,r=new Date().toISOString()){try{if(!Sw(n))return;let o={version:zu,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=ba(e);oP(vw(i),{recursive:!0}),ti(vw(i));let a=`${i}.${process.pid}.tmp`;aP(a,JSON.stringify(o,null,2),"utf8"),sP(a,i)}catch{}}function wa(e,t){try{let n=iP(ba(e),"utf8"),r=JSON.parse(n);return r.version!==zu||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Sw(r.result)?null:{version:zu,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Rw(e,t,n=new Date){let r=lP(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 lP(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${dP(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function dP(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 zu,cP,Ht=w(()=>{"use strict";dn();zu=1,cP=xw(".maind","conventions-cache.json");s(lt,"resolveRepoRoot");s(Zr,"keyFingerprint");s(ba,"cachePath");s(Sw,"hasInstructions");s(Ew,"writeConventionsCache");s(wa,"readConventionsCache");s(Rw,"buildCachedInitializeResponse");s(lP,"fallbackMarker");s(dP,"relativeAge")});import{existsSync as Sa,mkdirSync as kP,readFileSync as Aw,writeFileSync as Qu,chmodSync as Iw}from"node:fs";import{homedir as vP,hostname as xP,platform as Zu,release as SP}from"node:os";import{randomUUID as EP}from"node:crypto";import{join as rr}from"node:path";function dt(){let e=vP(),t=process.env;if(Zu()==="darwin")return rr(e,"Library","Application Support","maind");if(Zu()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:rr(e,"AppData","Roaming");return rr(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:rr(e,".config");return rr(n,"maind")}function Nw(e){Sa(e)||kP(e,{recursive:!0,mode:448})}function ce(){let e=dt();Nw(e);let t=rr(e,RP);if(Sa(t)){let r=Aw(t,"utf8").trim();if(AP(r))return r}let n=EP();Qu(t,n+`
137
- `,{encoding:"utf8",mode:384});try{Iw(t,384)}catch{}return n}function AP(e){return TP.test(e)}function ep(){return rr(dt(),CP)}function or(e){let t=dt();Nw(t);let n=ep();Qu(n,e+`
138
- `,{encoding:"utf8",mode:384});try{Iw(n,384)}catch{}}function z(){let e=ep();if(!Sa(e))return null;let t=Aw(e,"utf8").trim();return t.length>0?t:null}function wi(){let e=ep();Sa(e)&&Qu(e,"",{encoding:"utf8",mode:384})}function Ow(){try{return`mcp-bridge-${xP()}`}catch{return"mcp-bridge"}}function Ea(e){return{os:`${Zu()} ${SP()}`,ide:"mcp-bridge",ext_version:e,device_id:ce()}}var RP,CP,TP,oe=w(()=>{"use strict";s(dt,"configDir");s(Nw,"ensureDir");RP="device-id",CP="api-key";s(ce,"ensureDeviceId");TP=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(AP,"isUuid");s(ep,"apiKeyPath");s(or,"writeApiKey");s(z,"readApiKey");s(wi,"clearApiKey");s(Ow,"bridgeLabel");s(Ea,"clientMeta")});function ki(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:IP}function eo(e){return`${ki()}/${e.replace(/^\/+/,"")}`}var IP,to=w(()=>{"use strict";IP="https://fn.maind.dev/functions/v1";s(ki,"functionsOrigin");s(eo,"functionsUrl")});import{spawn as NP}from"node:child_process";import{platform as OP}from"node:os";async function no(e,t=process.stderr){let n=ki(),r=`${n}/device-authorization-start`,o=`${n}/device-authorization-poll`,i=Ea(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 $P(l.verification_uri_complete).catch(()=>{}),MP(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await PP(u);let p=await DP(o,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
131
+ `,cn="schema_version",Jr="last_index_commit",hi="last_indexed_at",Yr="edges_dirty",Tu="resolve_config_fp",fa="embed_recipe_version",ma="embed_model",ha="embed_dim",Au="last_synced_at",Qb="last_synced_commit"});function Iu(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 ew(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of Iu(e.name))t.add(o);for(let o of Iu(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function tw(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 Iu(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Nu=w(()=>{"use strict";s(Iu,"splitIdentifier");s(ew,"buildSearchText");s(tw,"toFtsMatchQuery")});import{readFileSync as nw}from"node:fs";import{posix as rw}from"node:path";function ow(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 nr(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function iw(e){return e==="added"?0:e==="modified"?1:2}function UD(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 gi,Ou=w(()=>{"use strict";Xo();Vy();dd();zy();Zy();pd();i_();Te();g_();vd();Od();ci();Eu();pi();Zb();Xr();Nu();gi=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(cn),o=await this.store.countFiles()>0;(t.full||o&&r!==an)&&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=_d(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=d_(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(Yr,"1"))},"markEdgesDirty");for(let b of i)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of a){m++;let k=p_(this.repoRoot,b.path);if(!k){u.filesSkipped++;continue}let v=l.get(b.path);if(v&&v.mtimeMs===k.mtimeMs&&v.size===k.size){u.filesSkipped++;continue}let E=this.readRepoFile(b.path);if(E===null){u.filesSkipped++;continue}let S=Zs(E);if(v&&v.contentHash===S){await this.store.upsertFile({...v,mtimeMs:k.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,ew(x));let K={path:b.path,language:b.language,contentHash:S,mtimeMs:k.mtimeMs,size:k.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:m,total:a.length})}let g=Jy(this.repoRoot),y=await this.store.getMeta(Tu)!==g.fingerprint;if(p||y||await this.store.getMeta(Yr)==="1"){let b=r_(await this.store.getNameIndex()),k=new Kr(g.config,b.files),v=o_(await this.store.getAllFacts(),b,k);await this.store.replaceCrossFileEdges(v),await this.store.setMeta(Tu,g.fingerprint),await this.store.setMeta(Yr,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...ld]),k=await this.store.getEmbeddingContentHashes(),v=[];for(let S of b){let R=Wy(S),P=Zs(`${this.embedder.recipeVersion}\0${R}`);k.get(S.nodeKey)!==P&&v.push({nodeKey:S.nodeKey,text:R,hash:P})}let E=64;for(let S=0;S<v.length;S+=E){let R=v.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,v.length);t.onProgress?.({path:"embedding symbols",done:K,total:v.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(fa,this.embedder.recipeVersion),await this.store.setMeta(ma,this.embedder.model),await this.store.setMeta(ha,String(this.embedder.dim))}await this.store.setMeta(cn,an),await this.store.setMeta(hi,String(n));let _=ni(this.repoRoot);return _&&await this.store.setMeta(Jr,_),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(hi);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(Jr),schemaVersion:await this.store.getMeta(cn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=nr(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({...ow(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=nr(n.limit,20,100),o=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:qy(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({...ow(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=nr(n.maxDepth,3,5),i=nr(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 m of u){let g=await this.store.neighbors(m,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=nw(rw.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(nr(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=_d(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=nr(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=Xs(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(ni(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return v_(this.repoRoot,n,t)}async checkDivergence(t={}){return ii(this.repoRoot,t)}async checkNumberCollisions(t={}){return Xn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Zn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Qn(this.repoRoot,t)}async reviewDetectors(t={}){return xu(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Su(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Xs(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=h_(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",a=Xb({paths:n,hunks:o,readUntracked:s(f=>this.readRepoFileHead(f,m_),"readUntracked")}),c=l_(n.keys()),l=nr(t.limit,64,t.attest?rn:200),d=[],u=0,p=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;u++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),_=g!==null&&y!==null&&Zs(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let b=n.get(f.path)??"modified",k=o.get(f.path);for(let v of m)d.push(UD(v,b,k,_))}return d.sort((f,m)=>iw(f.change)-iw(m.change)||(f.filePath<m.filePath?-1:f.filePath>m.filePath?1:0)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:ni(this.repoRoot),dirty:bd(this.repoRoot),baseSha:t.since?Qs(this.repoRoot,t.since):null,mergeBaseSha:t.since?yd(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 nw(rw.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(ow,"toHit");s(nr,"clampLimit");s(iw,"changeRank");s(UD,"classifyReviewSymbol")});var sw=w(()=>{"use strict";Te()});var BD,_Y,aw=w(()=>{"use strict";Te();BD=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],_Y=new RegExp(BD.join("|"),"g")});import{existsSync as Du,readdirSync as KD,readFileSync as GD}from"node:fs";import{spawnSync as WD}from"node:child_process";import{dirname as VD,join as ga,posix as Pu}from"node:path";function lw(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 ${Mu} 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 ${Mu} 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(Mt);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(Mt),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(Mt),m=e.remote.versions.filter(g=>!i.has(g)).sort(Mt);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function dw(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function pw(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 cw(e,t,n){let r=e(t,qD,n);return r.ok===!1?pw(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
133
+ `).map(o=>o.trim()).filter(Boolean)}}function fw(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 zD(e){let t=I(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=VD(t);return n===e?null:n}function JD(e,t,n){let r=Pu.dirname(t),i=[{path:ga(e,r,"config.toml"),source:"worktree"}],a=zD(e);a&&i.push({path:ga(a,r,"config.toml"),source:"main_worktree"});for(let c of i)if(Du(c.path))try{let l=fw(GD(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 YD(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||!Du(a))continue;let c=ga(a,t);if(Du(c))try{for(let l of KD(c)){let d=Wr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function $u(e,t={}){let n=t.runPsql??uw,r=t.timeoutMs??15e3,o=[],i=Jn(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=JD(e,p.dir,o),m=f.source==="missing"?null:cw(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?cw(n,t.remoteDbUrl,r):null,y=lw({dir:p.dir,projectRoot:ga(e,Pu.dirname(Pu.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:YD(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=dw(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 Mu,uw,qD,mw=w(()=>{"use strict";Te();oi();Mu=54322;s(lw,"evaluateLedgerProject");s(dw,"deriveLedgerVerdict");uw=s((e,t,n)=>{let r=WD("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"),qD="select version from supabase_migrations.schema_migrations order by version";s(pw,"classifyLedgerError");s(cw,"readLedger");s(fw,"parseDbPort");s(zD,"mainWorktreeRoot");s(JD,"resolveConfig");s(YD,"gatherSiblingVersions");s($u,"checkMigrationLedgerDrift")});function Ze(e){return typeof e=="string"?e:String(e??"")}function yi(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function Lu(e){return{nodeKey:Ze(e.node_key),kind:Ze(e.kind),name:Ze(e.name),qualifiedName:Ze(e.qualified_name),filePath:Ze(e.file_path),startLine:yi(e.start_line),endLine:yi(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function yw(e){return{path:Ze(e.path),language:Ze(e.language),contentHash:Ze(e.content_hash),mtimeMs:yi(e.mtime_ms),size:yi(e.size),indexedAt:yi(e.indexed_at)}}function ju(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(ln.meta).get(o);return i===void 0?null:Ze(i.value)},"metaValue");return{meta(){let o=r(cn),i=r(hi);return{schemaVersion:o,schemaCurrent:o===an,edgesDirty:r(Yr)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n(ln.file).get(o);return i===void 0?null:yw(i)},files(o){let i=new Map;for(let a of new Set(o)){let c=n(ln.file).get(a);c!==void 0&&i.set(a,yw(c))}return i},symbolsInFile(o,i=XD){return n(ln.symbolsInFile).all(o,i).map(Lu)},symbolsNamed(o,i=ZD){let a=new Map;for(let c of new Set(o)){let l=n(ln.symbolsNamed).all(c,i);l.length>0&&a.set(c,l.map(Lu))}return a},callersOfFile(o,i=QD){return n(ln.callersOfFile).all(o,o,i).map(c=>({calleeKey:Ze(c.callee_key),kind:Ze(c.edge_kind),caller:Lu(c)}))},importersOf(o,i=eP){let a=n(ln.importersOf).all(wt(o),i),c=[];for(let l of a){let d=Ze(l.src_key),u=d.endsWith(gw)?d.slice(0,-gw.length):d;u!==o&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function _i(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var hw,ln,XD,ZD,QD,eP,gw,Fu=w(()=>{"use strict";zn();Xr();hw="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",ln={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 ${hw} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${hw} 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 ?"},XD=400,ZD=8,QD=600,eP=200,gw="#<module>";s(Ze,"str");s(yi,"num");s(Lu,"toSymbol");s(yw,"toFileRow");s(ju,"createIndexReader");s(_i,"isFileCurrent")});var Hu,Uu=w(()=>{"use strict";Hu="0.2.0"});function Bu(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:rn,attest:!0}}function Ku(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>ya||a!==void 0&&a.length>_a){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=bw?{kind:i.kind}:{},...i.language&&i.language.length<=ww?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),kw)})}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:Hu},dropped:n}}function Gu(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 Wu(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 ${rn} (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 Vu(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===_w&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===_w?{kind:"invalid_params",code:n,detail:r,issues:tP(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function tP(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 qu(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 ya,_a,bw,ww,kw,_w,nP,vw=w(()=>{"use strict";Xo();Uu();ya=200,_a=512,bw=64,ww=32,kw=1e4;s(Bu,"attestReviewOptions");s(Ku,"buildAttestPayload");s(Gu,"attestPersistDecision");s(Wu,"attestCoverageNote");_w=-32602;s(Vu,"classifyMcpErrorText");s(tP,"parseIssues");s(qu,"isLegacyAttestRejection");nP=`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 dn=w(()=>{"use strict";jh();Ou();vd();Ru();Te();ca();au();eu();ou();Od();sw();aw();Rd();ci();ua();pi();oi();da();mw();Vd();Eu();ci();pi();ua();da();Vs();dd();Xr();Fu();zs();Uu();vw()});import{execFileSync as rP}from"node:child_process";import{createHash as oP}from"node:crypto";import{mkdirSync as iP,readFileSync as sP,renameSync as aP,writeFileSync as cP}from"node:fs";import{dirname as xw,join as Sw}from"node:path";function lt(e=process.cwd()){try{let t=rP("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 Zr(e){return oP("sha256").update(e).digest("hex").slice(0,16)}function ba(e){return Sw(e,lP)}function Ew(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Rw(e,t,n,r=new Date().toISOString()){try{if(!Ew(n))return;let o={version:zu,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=ba(e);iP(xw(i),{recursive:!0}),ti(xw(i));let a=`${i}.${process.pid}.tmp`;cP(a,JSON.stringify(o,null,2),"utf8"),aP(a,i)}catch{}}function wa(e,t){try{let n=sP(ba(e),"utf8"),r=JSON.parse(n);return r.version!==zu||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Ew(r.result)?null:{version:zu,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Cw(e,t,n=new Date){let r=dP(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 dP(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${uP(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function uP(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 zu,lP,Ht=w(()=>{"use strict";dn();zu=1,lP=Sw(".maind","conventions-cache.json");s(lt,"resolveRepoRoot");s(Zr,"keyFingerprint");s(ba,"cachePath");s(Ew,"hasInstructions");s(Rw,"writeConventionsCache");s(wa,"readConventionsCache");s(Cw,"buildCachedInitializeResponse");s(dP,"fallbackMarker");s(uP,"relativeAge")});import{existsSync as Sa,mkdirSync as vP,readFileSync as Iw,writeFileSync as Qu,chmodSync as Nw}from"node:fs";import{homedir as xP,hostname as SP,platform as Zu,release as EP}from"node:os";import{randomUUID as RP}from"node:crypto";import{join as rr}from"node:path";function dt(){let e=xP(),t=process.env;if(Zu()==="darwin")return rr(e,"Library","Application Support","maind");if(Zu()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:rr(e,"AppData","Roaming");return rr(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:rr(e,".config");return rr(n,"maind")}function Ow(e){Sa(e)||vP(e,{recursive:!0,mode:448})}function le(){let e=dt();Ow(e);let t=rr(e,CP);if(Sa(t)){let r=Iw(t,"utf8").trim();if(IP(r))return r}let n=RP();Qu(t,n+`
137
+ `,{encoding:"utf8",mode:384});try{Nw(t,384)}catch{}return n}function IP(e){return AP.test(e)}function ep(){return rr(dt(),TP)}function or(e){let t=dt();Ow(t);let n=ep();Qu(n,e+`
138
+ `,{encoding:"utf8",mode:384});try{Nw(n,384)}catch{}}function z(){let e=ep();if(!Sa(e))return null;let t=Iw(e,"utf8").trim();return t.length>0?t:null}function wi(){let e=ep();Sa(e)&&Qu(e,"",{encoding:"utf8",mode:384})}function Dw(){try{return`mcp-bridge-${SP()}`}catch{return"mcp-bridge"}}function Ea(e){return{os:`${Zu()} ${EP()}`,ide:"mcp-bridge",ext_version:e,device_id:le()}}var CP,TP,AP,ie=w(()=>{"use strict";s(dt,"configDir");s(Ow,"ensureDir");CP="device-id",TP="api-key";s(le,"ensureDeviceId");AP=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(IP,"isUuid");s(ep,"apiKeyPath");s(or,"writeApiKey");s(z,"readApiKey");s(wi,"clearApiKey");s(Dw,"bridgeLabel");s(Ea,"clientMeta")});function ki(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:NP}function eo(e){return`${ki()}/${e.replace(/^\/+/,"")}`}var NP,to=w(()=>{"use strict";NP="https://fn.maind.dev/functions/v1";s(ki,"functionsOrigin");s(eo,"functionsUrl")});import{spawn as OP}from"node:child_process";import{platform as DP}from"node:os";async function no(e,t=process.stderr){let n=ki(),r=`${n}/device-authorization-start`,o=`${n}/device-authorization-poll`,i=Ea(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 LP(l.verification_uri_complete).catch(()=>{}),$P(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await MP(u);let p=await PP(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 or(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 DP(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 PP(e){return new Promise(t=>setTimeout(t,e))}function MP(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: ${Dw(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Dw(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 PP(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 MP(e){return new Promise(t=>setTimeout(t,e))}function $P(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: ${Pw(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Pw(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 Dw(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}async function $P(e){let t,n;switch(OP()){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=NP(t,n,{stdio:"ignore",detached:!0});i.on("error",o),i.unref(),r()}catch(i){o(i)}})}var tp=w(()=>{"use strict";oe();to();s(no,"runDeviceFlow");s(DP,"pollOnce");s(PP,"sleep");s(MP,"printAuthInstructions");s(Dw,"pad");s($P,"openExternalBrowser")});import{mkdirSync as LP,readFileSync as jP,renameSync as FP,writeFileSync as HP}from"node:fs";import{join as UP}from"node:path";function Pw(e=dt()){return UP(e,KP)}function WP(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,GP)}function ir(e,t,n){try{let r=n.dir??dt();LP(r,{recursive:!0,mode:448});let o={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:WP(t),bridge_version:n.version},i=Pw(r),a=`${i}.${process.pid}.tmp`;HP(a,JSON.stringify(o)+`
146
- `,{encoding:"utf8",mode:384}),FP(a,i)}catch{}}function Mw(e=dt()){try{let t=JSON.parse(jP(Pw(e),"utf8"));return t.v!==1||typeof t.at!="string"||!BP.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 BP,KP,GP,np=w(()=>{"use strict";oe();BP=["ok","paired","auth_failed","not_paired"],KP="connection-state.json",GP=200;s(Pw,"connectionStatePath");s(WP,"redactDetail");s(ir,"writeConnectionState");s(Mw,"readConnectionState")});var H,Ue=w(()=>{"use strict";H="0.102.0"});import{execFileSync as $w}from"node:child_process";import{createHash as VP}from"node:crypto";function rp(e){return VP("sha256").update(e).digest("hex")}function op(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 un(e){let t=op(e);return t?rp(t):null}function re(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&qP.test(e))return e;let t;try{t=$w("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?un(t):null}function xt(e){let t;try{t=$w("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?un(t):null}var qP,me=w(()=>{"use strict";s(rp,"sha256Hex");s(op,"normalizeRemoteUrl");s(un,"projectKeyFromRemote");qP=/^[a-f0-9]{64}$/;s(re,"computeProjectKey");s(xt,"projectKeyForRepo")});import zP from"node:path";import{fileURLToPath as JP}from"node:url";function YP(e,t=zP.sep){return e.split(t).includes("_npx")}function ve(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",jw,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):YP(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 ie(){try{let e=JP(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Qe(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Lw(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Lw(n)).join(" ")}function pn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(jw)}function Ra(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Lw(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var jw,St=w(()=>{"use strict";jw="@maind-dev/mcp-bridge";s(YP,"isEphemeralEntry");s(ve,"resolveBridgeLaunch");s(ie,"currentBridgeEntry");s(Qe,"launchToShellCommand");s(pn,"isNpxForm");s(Ra,"isLegacyHookForm");s(Lw,"shellQuote")});import{readFileSync as XP}from"node:fs";import*as $ from"node:path";function Uw(e){let t=e.launch??ve({entryPath:ie(),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 Kw(e){return Ia(e,"Claude")}function QP(e){return $.join(Kw(e),Bw)}function Ia(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 eM(e){return $.join(Ia(e,"Code"),"User")}function Ta(e,t,n=[]){return{kind:"foreign-entries",dir:Ia(e,t),ours:["User",...n]}}function Fw(e){return e.localAppData??$.join(e.homeDir,"AppData","Local")}function nM(e){let t=[{kind:"foreign-entries",dir:Kw(e),ours:[Bw]}];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(Fw(e),"AnthropicClaude")},{kind:"dir",path:$.join(Fw(e),"Packages",tM)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Ut(e){return{evidence:[Ta(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 Gw(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 rM(e){return $.join(Gw(e),"mcp_config.json")}function Ww(e){return $.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function Aa(e){let t=[Ta(e,"Devin",["mcp_config.json"]),{kind:"dir",path:$.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:Gw(e),ours:["mcp_config.json"]}),t.push(Ta(e,"Windsurf"),{kind:"foreign-entries",dir:$.dirname(Ww(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 cM(e){return e===null?null:aM.exec(e)?.[1]??null}function qw(e,t){let n=Vw.map(r=>$.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push($.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of sM)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 zw(e){return e.clineDataDir?e.clineDataDir:$.join(e.clineDir??$.join(e.homeDir,".cline"),"data")}function lM(e){return e.clineMcpSettingsPath??$.join(zw(e),"settings","cline_mcp_settings.json")}function ip(e){return{evidence:[{kind:"foreign-entries",dir:zw(e),ours:["settings"]},...oM.map(t=>({kind:"dir",path:$.join(Ia(e,t),"User","globalStorage",Hw)})),...qw(e,Hw)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function Na(e){return e.continueGlobalDir??$.join(e.homeDir,".continue")}function dM(e){return $.join(Na(e),"mcpServers","maind.json")}function sp(e){return{evidence:[{kind:"foreign-entries",dir:Na(e),ours:["mcpServers","rules"]},...qw(e,iM)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function ro(e){return e.codexHome??$.join(e.homeDir,".codex")}function xi(e){return $.join(ro(e),"config.toml")}function oo(e){let t=ro(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 ap(e){return{evidence:[Ta(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function uM(e){return $.join(eM(e),"mcp.json")}function Si(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:QP(e),kind:"json",presence:nM(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:$.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Ut(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:rM(e),kind:"json",presence:Aa(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:Ww(e),kind:"json",presence:Aa(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:uM(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:ap(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:lM(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:ip(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:dM(e),kind:"json",presence:sp(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:xi(e),kind:"toml",presence:oo(e)}]}function Jw(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Yw(e){return e.jsonShape??ZP}function Xw(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:Zw(a,t);return c!==null&&c!==o?[c,o]:[o]}function Zw(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 Bt(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Ca(e.env.XDG_CONFIG_HOME),appData:Ca(e.env.APPDATA),localAppData:Ca(e.env.LOCALAPPDATA),clineDir:vi(e.env.CLINE_DIR),clineDataDir:vi(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:vi(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:vi(e.env.CONTINUE_GLOBAL_DIR),codexHome:vi(e.env.CODEX_HOME),bundleAppRoot:cM(e.bridgeEntry??null),documentsDirs:Xw({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return XP(t,"utf8")}catch{return null}},"readText")})}}function Ca(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function vi(e){let t=Ca(e);return t!==null&&$.isAbsolute(t)?t:null}var ZP,Bw,tM,Vw,oM,Hw,iM,sM,aM,cp,et=w(()=>{"use strict";St();ZP={serversKey:"mcpServers"};s(Uw,"buildMaindServerEntry");Bw="claude_desktop_config.json";s(Kw,"claudeDesktopAppDataDir");s(QP,"claudeDesktopConfigPath");s(Ia,"editorAppDataDir");s(eM,"vsCodeUserDir");s(Ta,"editorRan");s(Fw,"localAppDataDir");tM="Claude_pzs8sxrjxfjjc";s(nM,"claudeDesktopPresence");s(Ut,"cursorPresence");s(Gw,"devinConfigDir");s(rM,"devinMcpConfigPath");s(Ww,"windsurfLegacyMcpConfigPath");s(Aa,"devinDesktopPresence");Vw=[{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"}],oM=Vw.map(e=>e.appData),Hw="saoudrizwan.claude-dev",iM="continue.continue",sM=["AgentComposer"],aM=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(cM,"bundleAppRootOf");s(qw,"agentExtensionEvidence");s(zw,"clineDataDir");s(lM,"clineMcpSettingsPath");s(ip,"clinePresence");s(Na,"continueGlobalDir");s(dM,"continueMcpConfigPath");s(sp,"continuePresence");s(ro,"codexHomeDir");s(xi,"codexConfigPath");s(oo,"codexPresence");s(ap,"vsCodePresence");s(uM,"vsCodeUserMcpPath");s(Si,"getClientTargets");s(Jw,"filterTargetsByFamily");s(Yw,"jsonShapeOf");cp=[...new Set(Si({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(Xw,"documentsDirCandidates");s(Zw,"parseXdgDocumentsDir");s(Bt,"makeDefaultContext");s(Ca,"nonEmpty");s(vi,"absoluteOrNull")});function lp(){return cp.map(e=>{let t=Object.keys(Oa).filter(n=>Oa[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function Qw(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(pM),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 tt("--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 tt("--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 tt("--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 tt("--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 tt(`--client requires a family argument (${lp()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(Oa,i)?Oa[i]:i;if(!cp.includes(a))throw new tt(`--client "${o}" is not a known client family. Known: ${lp()}`);t.client=a,n++;break}default:throw new tt(`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 tt(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function ek(){process.stdout.write(fM())}function fM(){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:",` ${lp()}`," (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 Oa,pM,tt,tk=w(()=>{"use strict";et();Oa={devin:"windsurf"};s(lp,"familyChoices");pM="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(Qw,"parseInstallFlags");tt=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};s(ek,"printInstallHelp");s(fM,"installHelpText")});var Ei,nk=w(()=>{"use strict";Ei=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 Pw(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}async function LP(e){let t,n;switch(DP()){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=OP(t,n,{stdio:"ignore",detached:!0});i.on("error",o),i.unref(),r()}catch(i){o(i)}})}var tp=w(()=>{"use strict";ie();to();s(no,"runDeviceFlow");s(PP,"pollOnce");s(MP,"sleep");s($P,"printAuthInstructions");s(Pw,"pad");s(LP,"openExternalBrowser")});import{mkdirSync as jP,readFileSync as FP,renameSync as HP,writeFileSync as UP}from"node:fs";import{join as BP}from"node:path";function Mw(e=dt()){return BP(e,GP)}function VP(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,WP)}function ir(e,t,n){try{let r=n.dir??dt();jP(r,{recursive:!0,mode:448});let o={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:VP(t),bridge_version:n.version},i=Mw(r),a=`${i}.${process.pid}.tmp`;UP(a,JSON.stringify(o)+`
146
+ `,{encoding:"utf8",mode:384}),HP(a,i)}catch{}}function $w(e=dt()){try{let t=JSON.parse(FP(Mw(e),"utf8"));return t.v!==1||typeof t.at!="string"||!KP.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 KP,GP,WP,np=w(()=>{"use strict";ie();KP=["ok","paired","auth_failed","not_paired"],GP="connection-state.json",WP=200;s(Mw,"connectionStatePath");s(VP,"redactDetail");s(ir,"writeConnectionState");s($w,"readConnectionState")});var H,Ue=w(()=>{"use strict";H="0.103.0"});import{execFileSync as Lw}from"node:child_process";import{createHash as qP}from"node:crypto";function rp(e){return qP("sha256").update(e).digest("hex")}function op(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 un(e){let t=op(e);return t?rp(t):null}function oe(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&zP.test(e))return e;let t;try{t=Lw("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?un(t):null}function xt(e){let t;try{t=Lw("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?un(t):null}var zP,me=w(()=>{"use strict";s(rp,"sha256Hex");s(op,"normalizeRemoteUrl");s(un,"projectKeyFromRemote");zP=/^[a-f0-9]{64}$/;s(oe,"computeProjectKey");s(xt,"projectKeyForRepo")});import JP from"node:path";import{fileURLToPath as YP}from"node:url";function XP(e,t=JP.sep){return e.split(t).includes("_npx")}function ve(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Fw,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):XP(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 se(){try{let e=YP(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Qe(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${jw(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:jw(n)).join(" ")}function pn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Fw)}function Ra(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function jw(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Fw,St=w(()=>{"use strict";Fw="@maind-dev/mcp-bridge";s(XP,"isEphemeralEntry");s(ve,"resolveBridgeLaunch");s(se,"currentBridgeEntry");s(Qe,"launchToShellCommand");s(pn,"isNpxForm");s(Ra,"isLegacyHookForm");s(jw,"shellQuote")});import{readFileSync as ZP}from"node:fs";import*as $ from"node:path";function Bw(e){let t=e.launch??ve({entryPath:se(),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 Gw(e){return Ia(e,"Claude")}function eM(e){return $.join(Gw(e),Kw)}function Ia(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 tM(e){return $.join(Ia(e,"Code"),"User")}function Ta(e,t,n=[]){return{kind:"foreign-entries",dir:Ia(e,t),ours:["User",...n]}}function Hw(e){return e.localAppData??$.join(e.homeDir,"AppData","Local")}function rM(e){let t=[{kind:"foreign-entries",dir:Gw(e),ours:[Kw]}];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(Hw(e),"AnthropicClaude")},{kind:"dir",path:$.join(Hw(e),"Packages",nM)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Ut(e){return{evidence:[Ta(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 Ww(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 oM(e){return $.join(Ww(e),"mcp_config.json")}function Vw(e){return $.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function Aa(e){let t=[Ta(e,"Devin",["mcp_config.json"]),{kind:"dir",path:$.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:Ww(e),ours:["mcp_config.json"]}),t.push(Ta(e,"Windsurf"),{kind:"foreign-entries",dir:$.dirname(Vw(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 lM(e){return e===null?null:cM.exec(e)?.[1]??null}function zw(e,t){let n=qw.map(r=>$.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push($.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of aM)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 Jw(e){return e.clineDataDir?e.clineDataDir:$.join(e.clineDir??$.join(e.homeDir,".cline"),"data")}function dM(e){return e.clineMcpSettingsPath??$.join(Jw(e),"settings","cline_mcp_settings.json")}function ip(e){return{evidence:[{kind:"foreign-entries",dir:Jw(e),ours:["settings"]},...iM.map(t=>({kind:"dir",path:$.join(Ia(e,t),"User","globalStorage",Uw)})),...zw(e,Uw)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function Na(e){return e.continueGlobalDir??$.join(e.homeDir,".continue")}function uM(e){return $.join(Na(e),"mcpServers","maind.json")}function sp(e){return{evidence:[{kind:"foreign-entries",dir:Na(e),ours:["mcpServers","rules"]},...zw(e,sM)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function ro(e){return e.codexHome??$.join(e.homeDir,".codex")}function xi(e){return $.join(ro(e),"config.toml")}function oo(e){let t=ro(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 ap(e){return{evidence:[Ta(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function pM(e){return $.join(tM(e),"mcp.json")}function Si(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:eM(e),kind:"json",presence:rM(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:$.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Ut(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:oM(e),kind:"json",presence:Aa(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:Vw(e),kind:"json",presence:Aa(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:pM(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:ap(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:dM(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:ip(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:uM(e),kind:"json",presence:sp(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:xi(e),kind:"toml",presence:oo(e)}]}function Yw(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Xw(e){return e.jsonShape??QP}function Zw(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:Qw(a,t);return c!==null&&c!==o?[c,o]:[o]}function Qw(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 Bt(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Ca(e.env.XDG_CONFIG_HOME),appData:Ca(e.env.APPDATA),localAppData:Ca(e.env.LOCALAPPDATA),clineDir:vi(e.env.CLINE_DIR),clineDataDir:vi(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:vi(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:vi(e.env.CONTINUE_GLOBAL_DIR),codexHome:vi(e.env.CODEX_HOME),bundleAppRoot:lM(e.bridgeEntry??null),documentsDirs:Zw({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return ZP(t,"utf8")}catch{return null}},"readText")})}}function Ca(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function vi(e){let t=Ca(e);return t!==null&&$.isAbsolute(t)?t:null}var QP,Kw,nM,qw,iM,Uw,sM,aM,cM,cp,et=w(()=>{"use strict";St();QP={serversKey:"mcpServers"};s(Bw,"buildMaindServerEntry");Kw="claude_desktop_config.json";s(Gw,"claudeDesktopAppDataDir");s(eM,"claudeDesktopConfigPath");s(Ia,"editorAppDataDir");s(tM,"vsCodeUserDir");s(Ta,"editorRan");s(Hw,"localAppDataDir");nM="Claude_pzs8sxrjxfjjc";s(rM,"claudeDesktopPresence");s(Ut,"cursorPresence");s(Ww,"devinConfigDir");s(oM,"devinMcpConfigPath");s(Vw,"windsurfLegacyMcpConfigPath");s(Aa,"devinDesktopPresence");qw=[{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"}],iM=qw.map(e=>e.appData),Uw="saoudrizwan.claude-dev",sM="continue.continue",aM=["AgentComposer"],cM=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(lM,"bundleAppRootOf");s(zw,"agentExtensionEvidence");s(Jw,"clineDataDir");s(dM,"clineMcpSettingsPath");s(ip,"clinePresence");s(Na,"continueGlobalDir");s(uM,"continueMcpConfigPath");s(sp,"continuePresence");s(ro,"codexHomeDir");s(xi,"codexConfigPath");s(oo,"codexPresence");s(ap,"vsCodePresence");s(pM,"vsCodeUserMcpPath");s(Si,"getClientTargets");s(Yw,"filterTargetsByFamily");s(Xw,"jsonShapeOf");cp=[...new Set(Si({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(Zw,"documentsDirCandidates");s(Qw,"parseXdgDocumentsDir");s(Bt,"makeDefaultContext");s(Ca,"nonEmpty");s(vi,"absoluteOrNull")});function lp(){return cp.map(e=>{let t=Object.keys(Oa).filter(n=>Oa[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function ek(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(fM),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 tt("--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 tt("--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 tt("--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 tt("--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 tt(`--client requires a family argument (${lp()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(Oa,i)?Oa[i]:i;if(!cp.includes(a))throw new tt(`--client "${o}" is not a known client family. Known: ${lp()}`);t.client=a,n++;break}default:throw new tt(`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 tt(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function tk(){process.stdout.write(mM())}function mM(){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:",` ${lp()}`," (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 Oa,fM,tt,nk=w(()=>{"use strict";et();Oa={devin:"windsurf"};s(lp,"familyChoices");fM="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(ek,"parseInstallFlags");tt=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};s(tk,"printInstallHelp");s(mM,"installHelpText")});var Ei,rk=w(()=>{"use strict";Ei=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(`
@@ -152,38 +152,38 @@ ${o}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function lP(e,t){ret
152
152
  Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
153
153
  `),t.write(this.manualSteps())}manualSteps(){let t=this.results.filter(r=>r.manual!==void 0&&r.manual.length>0);if(t.length===0)return"";let n=["","Left untouched \u2014 to do by hand:"];for(let r of t){n.push("",` ${r.target}: ${r.detail??""}`);for(let o of r.manual??[])n.push(o===""?"":` ${o}`)}return n.join(`
154
154
  `)+`
155
- `}toJson(){return{steps:[...this.results],summary:this.summary()}}}});import*as rk from"node:fs/promises";import*as fn from"node:path";import*as ok from"node:readline";async function ik(e){let t=fn.resolve(e),n=t;for(;;){if(await sk(n))return n;let r=fn.dirname(n);if(r===n)return t;n=r}}async function Da(e){let n=fn.resolve(e),r=[];for(;;){await sk(n)&&r.push(n);let o=fn.dirname(n);if(o===n)break;n=o}return r}async function sk(e){for(let t of mM)try{return await rk.access(fn.join(e,t)),!0}catch{}return!1}async function ak(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
155
+ `}toJson(){return{steps:[...this.results],summary:this.summary()}}}});import*as ok from"node:fs/promises";import*as fn from"node:path";import*as ik from"node:readline";async function sk(e){let t=fn.resolve(e),n=t;for(;;){if(await ak(n))return n;let r=fn.dirname(n);if(r===n)return t;n=r}}async function Da(e){let n=fn.resolve(e),r=[];for(;;){await ak(n)&&r.push(n);let o=fn.dirname(n);if(o===n)break;n=o}return r}async function ak(e){for(let t of hM)try{return await ok.access(fn.join(e,t)),!0}catch{}return!1}async function ck(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
156
156
  Multiple project roots found between cwd and the filesystem root:
157
157
  `),e.forEach((i,a)=>{process.stdout.write(` [${a+1}] ${i}
158
158
  `)}),process.stdout.write(`
159
- Which one should install --team write AGENTS.md and .mcp.json into? [1-${e.length}, default 1]: `);let n=ok.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>.
160
- `),null):e[o-1]}var mM,dp=w(()=>{"use strict";mM=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];s(ik,"detectProjectRoot");s(Da,"findAllProjectRoots");s(sk,"hasAnyMarker");s(ak,"disambiguateProjectRoot")});import{existsSync as hM,readdirSync as gM}from"node:fs";import*as le from"node:fs/promises";import*as Pa from"node:path";async function q(e){try{return await le.readFile(e,"utf8")}catch(t){if(_M(t))return null;throw t}}async function yM(e){await le.mkdir(e,{recursive:!0})}async function B(e,t,n){let r=Pa.dirname(e);await yM(r);let o=Pa.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await le.writeFile(o,t,{encoding:"utf8",mode:n});try{await le.rename(o,e)}catch(i){if(bM(i))try{await le.copyFile(o,e),await le.unlink(o).catch(()=>{}),n!==void 0&&await le.chmod(e,n).catch(()=>{});return}catch(a){throw await le.unlink(o).catch(()=>{}),a}throw await le.unlink(o).catch(()=>{}),i}}async function Ma(e,t,n){if(await q(e)!==t)return!1;let r;if(t!==null)try{r=(await le.stat(e)).mode&511}catch{r=void 0}return await B(e,n,r),!0}async function ck(e,t){let n=await q(e);return n===null?!1:n.split(/\r?\n/).some(o=>o.startsWith(t))}function _M(e){return lk(e)&&e.code==="ENOENT"}function bM(e){return!lk(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function lk(e){return typeof e=="object"&&e!==null&&"code"in e}var de,se=w(()=>{"use strict";de={exists:s(e=>hM(e),"exists"),readdir:s(e=>{try{return gM(e)}catch{return null}},"readdir")};s(q,"readFileSafe");s(yM,"ensureDir");s(B,"atomicWriteFile");s(Ma,"writeIfUnchanged");s(ck,"hasLinePrefix");s(_M,"isNoEnt");s(bM,"isWindowsRenameFailure");s(lk,"isNodeError")});function wM(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function kM(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(`${r}-`)}function vM(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=>kM(r,e.id)):n.some(r=>!wM(r)&&!e.ours.includes(r))}function De(e,t){return e.evidence.some(n=>vM(n,t))}function dk(e,t){return De(Ut(e),t)}function uk(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||De(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 io=w(()=>{"use strict";et();s(wM,"isNoise");s(kM,"isExtensionFolder");s(vM,"evidenceHolds");s(De,"clientPresent");s(dk,"cursorInstalled");s(uk,"presenceSkipRow")});import{applyEdits as xM,modify as SM,parse as EM,printParseErrorCode as RM}from"jsonc-parser";async function hk(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=Yw(e),o=r.serversKey==="servers",i;try{i=await q(e.path)}catch(m){return up(e,"read",m)}let a,c="create";if(i===null||i.trim().length===0)a={};else{c="merge";try{a=o?CM(i):JSON.parse(i)}catch(m){return e.refreshOnly!==void 0?mk(e,`not valid JSON: ${m instanceof Error?m.message:String(m)}`):up(e,"parse",m)}}if(!mn(a))return e.refreshOnly!==void 0?mk(e,"not a JSON object at root"):{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};if(e.refreshOnly!==void 0){let m=a[r.serversKey];if(i===null||!mn(m)||!(sr in m))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&AM(a),d,u,p=!1;if(l){let m=a[sr];p=fk(m,t,r),u=pk(m,t,r),d={...a,[sr]:u}}else{let m=a[r.serversKey],g=mn(m)?m:{},y=g[sr];p=fk(y,t,r),u=pk(y,t,r),d={...a,[r.serversKey]:{...g,[sr]:u}}}if(p&&i!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=o&&!l?TM(i??"",[r.serversKey,sr],u):JSON.stringify(d,null,2)+`
161
- `;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await B(e.path,f)}catch(m){return up(e,"write",m)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}function pk(e,t,n){let r=mn(e)&&mn(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(mn(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 CM(e){let t=[],n=EM(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${RM(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}function TM(e,t,n){let r=SM(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
162
- `}}),o=xM(e,r);return o.endsWith(`
159
+ Which one should install --team write AGENTS.md and .mcp.json into? [1-${e.length}, default 1]: `);let n=ik.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>.
160
+ `),null):e[o-1]}var hM,dp=w(()=>{"use strict";hM=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];s(sk,"detectProjectRoot");s(Da,"findAllProjectRoots");s(ak,"hasAnyMarker");s(ck,"disambiguateProjectRoot")});import{existsSync as gM,readdirSync as yM}from"node:fs";import*as Q from"node:fs/promises";import*as Pa from"node:path";async function q(e){try{return await Q.readFile(e,"utf8")}catch(t){if(dk(t))return null;throw t}}async function _M(e){await Q.mkdir(e,{recursive:!0})}async function B(e,t,n){let r=await bM(e),o=Pa.dirname(r);await _M(o);let i=n??await wM(r),a=Pa.join(o,`.maind-install-${process.pid}-${Date.now()}.tmp`);await Q.writeFile(a,t,{encoding:"utf8",mode:i}),i!==void 0&&await Q.chmod(a,i).catch(()=>{});try{await Q.rename(a,r)}catch(c){if(kM(c))try{await Q.copyFile(a,r),await Q.unlink(a).catch(()=>{}),i!==void 0&&await Q.chmod(r,i).catch(()=>{});return}catch(l){throw await Q.unlink(a).catch(()=>{}),l}throw await Q.unlink(a).catch(()=>{}),c}}async function bM(e){let t;try{t=await Q.lstat(e)}catch(n){if(dk(n))return e;throw n}if(!t.isSymbolicLink())return e;try{return await Q.realpath(e)}catch(n){let r=up(n)&&n.code?n.code:"unresolvable";throw new Error(`${e} is a symbolic link that resolves nowhere (${r}) \u2014 left untouched; fix or remove the link, then run install again`)}}async function wM(e){try{return(await Q.stat(e)).mode&511}catch{return}}async function Ma(e,t,n){if(await q(e)!==t)return!1;let r;if(t!==null)try{r=(await Q.stat(e)).mode&511}catch{r=void 0}return await B(e,n,r),!0}async function lk(e,t){let n=await q(e);return n===null?!1:n.split(/\r?\n/).some(o=>o.startsWith(t))}function dk(e){return up(e)&&e.code==="ENOENT"}function kM(e){return!up(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function up(e){return typeof e=="object"&&e!==null&&"code"in e}var de,ae=w(()=>{"use strict";de={exists:s(e=>gM(e),"exists"),readdir:s(e=>{try{return yM(e)}catch{return null}},"readdir")};s(q,"readFileSafe");s(_M,"ensureDir");s(B,"atomicWriteFile");s(bM,"resolveWriteTarget");s(wM,"existingMode");s(Ma,"writeIfUnchanged");s(lk,"hasLinePrefix");s(dk,"isNoEnt");s(kM,"isWindowsRenameFailure");s(up,"isNodeError")});function vM(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function xM(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(`${r}-`)}function SM(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=>xM(r,e.id)):n.some(r=>!vM(r)&&!e.ours.includes(r))}function De(e,t){return e.evidence.some(n=>SM(n,t))}function uk(e,t){return De(Ut(e),t)}function pk(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||De(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 io=w(()=>{"use strict";et();s(vM,"isNoise");s(xM,"isExtensionFolder");s(SM,"evidenceHolds");s(De,"clientPresent");s(uk,"cursorInstalled");s(pk,"presenceSkipRow")});import{applyEdits as EM,modify as RM,parse as CM,printParseErrorCode as TM}from"jsonc-parser";async function gk(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=Xw(e),o=r.serversKey==="servers",i;try{i=await q(e.path)}catch(m){return pp(e,"read",m)}let a,c="create";if(i===null||i.trim().length===0)a={};else{c="merge";try{a=o?AM(i):JSON.parse(i)}catch(m){return e.refreshOnly!==void 0?hk(e,`not valid JSON: ${m instanceof Error?m.message:String(m)}`):pp(e,"parse",m)}}if(!mn(a))return e.refreshOnly!==void 0?hk(e,"not a JSON object at root"):{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};if(e.refreshOnly!==void 0){let m=a[r.serversKey];if(i===null||!mn(m)||!(sr in m))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&NM(a),d,u,p=!1;if(l){let m=a[sr];p=mk(m,t,r),u=fk(m,t,r),d={...a,[sr]:u}}else{let m=a[r.serversKey],g=mn(m)?m:{},y=g[sr];p=mk(y,t,r),u=fk(y,t,r),d={...a,[r.serversKey]:{...g,[sr]:u}}}if(p&&i!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=o&&!l?IM(i??"",[r.serversKey,sr],u):JSON.stringify(d,null,2)+`
161
+ `;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await B(e.path,f)}catch(m){return pp(e,"write",m)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}function fk(e,t,n){let r=mn(e)&&mn(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(mn(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 AM(e){let t=[],n=CM(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${TM(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}function IM(e,t,n){let r=RM(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
162
+ `}}),o=EM(e,r);return o.endsWith(`
163
163
  `)?o:o+`
164
- `}function AM(e){return!("mcpServers"in e||!(sr in e))}function fk(e,t,n){if(!mn(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||!IM(e.args,t.args)||!mn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}function IM(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 mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mk(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}function up(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var sr,gk=w(()=>{"use strict";se();et();sr="maind";s(hk,"mergeJsonConfig");s(pk,"mergeEntry");s(CM,"parseJsoncStrict");s(TM,"editInPlace");s(AM,"hasRootShape");s(fk,"serverEntriesEqual");s(IM,"arrayEquals");s(mn,"isObject");s(mk,"leftAlone");s(up,"failed")});function fp(e){let t=e.indexOf(`
164
+ `}function NM(e){return!("mcpServers"in e||!(sr in e))}function mk(e,t,n){if(!mn(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||!OM(e.args,t.args)||!mn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}function OM(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 mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hk(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}function pp(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var sr,yk=w(()=>{"use strict";ae();et();sr="maind";s(gk,"mergeJsonConfig");s(fk,"mergeEntry");s(AM,"parseJsoncStrict");s(IM,"editInPlace");s(NM,"hasRootShape");s(mk,"serverEntriesEqual");s(OM,"arrayEquals");s(mn,"isObject");s(hk,"leftAlone");s(pp,"failed")});function mp(e){let t=e.indexOf(`
165
165
  `);return t>0&&e[t-1]==="\r"?`\r
166
166
  `:`
167
- `}function Ri(e){let t;try{t=new pp(e).statements()}catch(l){if(l instanceof xe)return null;throw l}let n=[],r=[],o=[],i=new Map,a=[],c=-1;return t.forEach((l,d)=>{l.kind==="header"?(a=NM(l.key.parts,l.array,i),c=d,n.push(a)):l.kind==="keyval"?n.push([...a,...l.key.parts]):n.push(null),r.push(a),o.push(c)}),{raw:e,eol:fp(e),statements:t,paths:n,tables:r,sections:o}}function NM(e,t,n){let r=[];return e.forEach((o,i)=>{r.push(o);let a=JSON.stringify(r);if(t&&i===e.length-1){let c=(n.get(a)??0)+1;n.set(a,c),r.push(c-1)}else{let c=n.get(a);c!==void 0&&r.push(c-1)}}),r}function mp(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function hn(e,t){return t.length<=e.length&&t.every((n,r)=>n===e[r])}function _k(e){let t=[],n=s((r,o,i,a)=>{t.push({node:r,path:o,stmt:i,parent:a}),r.kind==="inline"?r.entries.forEach((c,l)=>n(c.value,[...o,...c.key.parts],i,{kind:"entry",inline:r,index:l})):r.kind==="array"&&r.items.forEach((c,l)=>n(c.value,[...o,l],i,{kind:"item",array:r,index:l}))},"walk");return e.statements.forEach((r,o)=>{let i=e.paths[o];r.kind==="keyval"&&i!==null&&n(r.value,i,o,{kind:"keyval"})}),t}function Kt(e,t){return _k(e).find(n=>mp(n.path,t))}function hp(e,t){return e.statements.findIndex((n,r)=>n.kind==="header"&&mp(e.paths[r]??[],t))}function $a(e,t){let n=null;return e.statements.forEach((r,o)=>{r.kind==="keyval"&&e.sections[o]===t&&(n=o)}),n}function Ci(e,t){let n=_k(e),r=n.find(c=>mp(c.path,t));if(r!==void 0)return r.node.kind==="inline"?{kind:"inline",ref:r}:{kind:"conflict"};if(n.some(c=>c.path.length<t.length&&hn(t,c.path)))return{kind:"conflict"};if(t.length===0)return{kind:"section",header:-1};let o=hp(e,t);if(o>=0)return{kind:"section",header:o};let i=null;return e.statements.forEach((c,l)=>{let d=e.paths[l],u=e.tables[l];if(!(c.kind!=="keyval"||d===null)&&d.length>t.length&&hn(d,t)&&u.length<t.length&&hn(t,u)){let p=t.slice(u.length);p.every(f=>typeof f=="string")&&(i={kind:"dotted",section:e.sections[l],prefix:p,last:l})}}),i!==null?i:e.statements.some((c,l)=>c.kind==="header"&&(e.paths[l]??[]).length>t.length&&hn(e.paths[l]??[],t))?{kind:"implicit"}:{kind:"absent"}}function gp(e,t){return t.kind!=="keyval"&&t.kind!=="header"||t.comment===null?null:e.raw.slice(t.comment.start,t.comment.end).trim()}var xe,yk,OM,DM,PM,pp,La=w(()=>{"use strict";xe=class extends Error{static{s(this,"ScanError")}};s(fp,"detectEol");s(Ri,"scanToml");s(NM,"resolveHeader");s(mp,"samePath");s(hn,"startsWith");s(_k,"valueRefs");s(Kt,"valueAt");s(hp,"headerAt");s($a,"lastKeyvalIn");s(Ci,"tableDef");s(gp,"trailingComment");yk=/[A-Za-z0-9_-]+/y,OM=/^\d{4}-\d{2}-\d{2}$/,DM=/^\d{2}:\d{2}/,PM=new Set([" "," ",",","]","}","#","\r",`
168
- `]),pp=class{constructor(t){this.raw=t}static{s(this,"Scanner")}i=0;statements(){let t=[],n=this.raw;for(;this.i<n.length;){let r=this.i;if(this.skipWs(),this.i>=n.length||this.atEol()){this.eatEol(),t.push({kind:"blank",line:{start:r,end:this.i}});continue}let o=n[this.i];if(o==="#"){this.skipComment(),this.eatEol(),t.push({kind:"comment",line:{start:r,end:this.i}});continue}if(o==="["){let d=n[this.i+1]==="[";this.i+=d?2:1,this.skipWs();let u=this.key();this.skipWs(),this.expect(d?"]]":"]");let p=this.lineEnd();t.push({kind:"header",line:{start:r,end:this.i},array:d,key:u,comment:p});continue}let i=n.slice(r,this.i),a=this.key();this.skipWs(),this.expect("="),this.skipWs();let c=this.value(),l=this.lineEnd();t.push({kind:"keyval",line:{start:r,end:this.i},key:a,value:c,comment:l,indent:i})}return t}key(){let t=[],n=[];for(;;){let r=this.i;t.push(this.simpleKey()),n.push({start:r,end:this.i});let o=this.i;if(this.skipWs(),this.raw[this.i]==="."){this.i++,this.skipWs();continue}return this.i=o,{parts:t,partSpans:n,span:{start:n[0].start,end:this.i}}}}simpleKey(){let t=this.raw[this.i];if(t==='"')return this.basicString();if(t==="'")return this.literalString();yk.lastIndex=this.i;let n=yk.exec(this.raw);if(n===null)throw new xe("key");return this.i+=n[0].length,n[0]}value(){let t=this.raw,n=this.i;if(t.startsWith('"""',n))return this.multiline('"'),{kind:"string",span:{start:n,end:this.i},style:"ml-basic"};if(t.startsWith("'''",n))return this.multiline("'"),{kind:"string",span:{start:n,end:this.i},style:"ml-literal"};let r=t[n];return r==='"'?(this.basicString(),{kind:"string",span:{start:n,end:this.i},style:"basic"}):r==="'"?(this.literalString(),{kind:"string",span:{start:n,end:this.i},style:"literal"}):r==="["?this.array():r==="{"?this.inline():this.scalar()}array(){let t=this.i++,n=[];for(;;){if(this.skipBlank(),this.raw[this.i]==="]"){this.i++;break}let r={value:this.value(),comma:null};if(n.push(r),this.skipBlank(),this.raw[this.i]===","){r.comma=this.i++;continue}this.expect("]");break}return{kind:"array",span:{start:t,end:this.i},items:n}}inline(){let t=this.i++,n=[];for(;;){if(this.skipBlank(),this.raw[this.i]==="}"){this.i++;break}let r=this.key();this.skipWs(),this.expect("="),this.skipWs();let o={key:r,value:this.value(),comma:null};if(n.push(o),this.skipBlank(),this.raw[this.i]===","){o.comma=this.i++;continue}this.expect("}");break}return{kind:"inline",span:{start:t,end:this.i},entries:n}}scalar(){let t=this.raw,n=this.i,r=s(()=>{for(;this.i<t.length&&!PM.has(t[this.i]);)this.i++},"run");if(r(),this.i===n)throw new xe("value");return OM.test(t.slice(n,this.i))&&t[this.i]===" "&&DM.test(t.slice(this.i+1,this.i+6))&&(this.i++,r()),{kind:"scalar",span:{start:n,end:this.i}}}basicString(){let t=this.raw;this.i++;let n="";for(;;){if(this.i>=t.length)throw new xe("string");let r=t[this.i];if(r==='"')return this.i++,n;if(r===`
167
+ `}function Ri(e){let t;try{t=new fp(e).statements()}catch(l){if(l instanceof xe)return null;throw l}let n=[],r=[],o=[],i=new Map,a=[],c=-1;return t.forEach((l,d)=>{l.kind==="header"?(a=DM(l.key.parts,l.array,i),c=d,n.push(a)):l.kind==="keyval"?n.push([...a,...l.key.parts]):n.push(null),r.push(a),o.push(c)}),{raw:e,eol:mp(e),statements:t,paths:n,tables:r,sections:o}}function DM(e,t,n){let r=[];return e.forEach((o,i)=>{r.push(o);let a=JSON.stringify(r);if(t&&i===e.length-1){let c=(n.get(a)??0)+1;n.set(a,c),r.push(c-1)}else{let c=n.get(a);c!==void 0&&r.push(c-1)}}),r}function hp(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function hn(e,t){return t.length<=e.length&&t.every((n,r)=>n===e[r])}function bk(e){let t=[],n=s((r,o,i,a)=>{t.push({node:r,path:o,stmt:i,parent:a}),r.kind==="inline"?r.entries.forEach((c,l)=>n(c.value,[...o,...c.key.parts],i,{kind:"entry",inline:r,index:l})):r.kind==="array"&&r.items.forEach((c,l)=>n(c.value,[...o,l],i,{kind:"item",array:r,index:l}))},"walk");return e.statements.forEach((r,o)=>{let i=e.paths[o];r.kind==="keyval"&&i!==null&&n(r.value,i,o,{kind:"keyval"})}),t}function Kt(e,t){return bk(e).find(n=>hp(n.path,t))}function gp(e,t){return e.statements.findIndex((n,r)=>n.kind==="header"&&hp(e.paths[r]??[],t))}function $a(e,t){let n=null;return e.statements.forEach((r,o)=>{r.kind==="keyval"&&e.sections[o]===t&&(n=o)}),n}function Ci(e,t){let n=bk(e),r=n.find(c=>hp(c.path,t));if(r!==void 0)return r.node.kind==="inline"?{kind:"inline",ref:r}:{kind:"conflict"};if(n.some(c=>c.path.length<t.length&&hn(t,c.path)))return{kind:"conflict"};if(t.length===0)return{kind:"section",header:-1};let o=gp(e,t);if(o>=0)return{kind:"section",header:o};let i=null;return e.statements.forEach((c,l)=>{let d=e.paths[l],u=e.tables[l];if(!(c.kind!=="keyval"||d===null)&&d.length>t.length&&hn(d,t)&&u.length<t.length&&hn(t,u)){let p=t.slice(u.length);p.every(f=>typeof f=="string")&&(i={kind:"dotted",section:e.sections[l],prefix:p,last:l})}}),i!==null?i:e.statements.some((c,l)=>c.kind==="header"&&(e.paths[l]??[]).length>t.length&&hn(e.paths[l]??[],t))?{kind:"implicit"}:{kind:"absent"}}function yp(e,t){return t.kind!=="keyval"&&t.kind!=="header"||t.comment===null?null:e.raw.slice(t.comment.start,t.comment.end).trim()}var xe,_k,PM,MM,$M,fp,La=w(()=>{"use strict";xe=class extends Error{static{s(this,"ScanError")}};s(mp,"detectEol");s(Ri,"scanToml");s(DM,"resolveHeader");s(hp,"samePath");s(hn,"startsWith");s(bk,"valueRefs");s(Kt,"valueAt");s(gp,"headerAt");s($a,"lastKeyvalIn");s(Ci,"tableDef");s(yp,"trailingComment");_k=/[A-Za-z0-9_-]+/y,PM=/^\d{4}-\d{2}-\d{2}$/,MM=/^\d{2}:\d{2}/,$M=new Set([" "," ",",","]","}","#","\r",`
168
+ `]),fp=class{constructor(t){this.raw=t}static{s(this,"Scanner")}i=0;statements(){let t=[],n=this.raw;for(;this.i<n.length;){let r=this.i;if(this.skipWs(),this.i>=n.length||this.atEol()){this.eatEol(),t.push({kind:"blank",line:{start:r,end:this.i}});continue}let o=n[this.i];if(o==="#"){this.skipComment(),this.eatEol(),t.push({kind:"comment",line:{start:r,end:this.i}});continue}if(o==="["){let d=n[this.i+1]==="[";this.i+=d?2:1,this.skipWs();let u=this.key();this.skipWs(),this.expect(d?"]]":"]");let p=this.lineEnd();t.push({kind:"header",line:{start:r,end:this.i},array:d,key:u,comment:p});continue}let i=n.slice(r,this.i),a=this.key();this.skipWs(),this.expect("="),this.skipWs();let c=this.value(),l=this.lineEnd();t.push({kind:"keyval",line:{start:r,end:this.i},key:a,value:c,comment:l,indent:i})}return t}key(){let t=[],n=[];for(;;){let r=this.i;t.push(this.simpleKey()),n.push({start:r,end:this.i});let o=this.i;if(this.skipWs(),this.raw[this.i]==="."){this.i++,this.skipWs();continue}return this.i=o,{parts:t,partSpans:n,span:{start:n[0].start,end:this.i}}}}simpleKey(){let t=this.raw[this.i];if(t==='"')return this.basicString();if(t==="'")return this.literalString();_k.lastIndex=this.i;let n=_k.exec(this.raw);if(n===null)throw new xe("key");return this.i+=n[0].length,n[0]}value(){let t=this.raw,n=this.i;if(t.startsWith('"""',n))return this.multiline('"'),{kind:"string",span:{start:n,end:this.i},style:"ml-basic"};if(t.startsWith("'''",n))return this.multiline("'"),{kind:"string",span:{start:n,end:this.i},style:"ml-literal"};let r=t[n];return r==='"'?(this.basicString(),{kind:"string",span:{start:n,end:this.i},style:"basic"}):r==="'"?(this.literalString(),{kind:"string",span:{start:n,end:this.i},style:"literal"}):r==="["?this.array():r==="{"?this.inline():this.scalar()}array(){let t=this.i++,n=[];for(;;){if(this.skipBlank(),this.raw[this.i]==="]"){this.i++;break}let r={value:this.value(),comma:null};if(n.push(r),this.skipBlank(),this.raw[this.i]===","){r.comma=this.i++;continue}this.expect("]");break}return{kind:"array",span:{start:t,end:this.i},items:n}}inline(){let t=this.i++,n=[];for(;;){if(this.skipBlank(),this.raw[this.i]==="}"){this.i++;break}let r=this.key();this.skipWs(),this.expect("="),this.skipWs();let o={key:r,value:this.value(),comma:null};if(n.push(o),this.skipBlank(),this.raw[this.i]===","){o.comma=this.i++;continue}this.expect("}");break}return{kind:"inline",span:{start:t,end:this.i},entries:n}}scalar(){let t=this.raw,n=this.i,r=s(()=>{for(;this.i<t.length&&!$M.has(t[this.i]);)this.i++},"run");if(r(),this.i===n)throw new xe("value");return PM.test(t.slice(n,this.i))&&t[this.i]===" "&&MM.test(t.slice(this.i+1,this.i+6))&&(this.i++,r()),{kind:"scalar",span:{start:n,end:this.i}}}basicString(){let t=this.raw;this.i++;let n="";for(;;){if(this.i>=t.length)throw new xe("string");let r=t[this.i];if(r==='"')return this.i++,n;if(r===`
169
169
  `||r==="\r")throw new xe("string");if(r==="\\"){n+=this.escape();continue}n+=r,this.i++}}escape(){let t=this.raw,n=t[this.i+1],r={b:"\b",t:" ",n:`
170
170
  `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};if(n!==void 0&&n in r)return this.i+=2,r[n];let o=n==="u"?4:n==="U"?8:n==="x"?2:0,i=t.slice(this.i+2,this.i+2+o);if(o===0||!/^[0-9A-Fa-f]+$/.test(i)||i.length!==o)throw new xe("escape");let a=Number.parseInt(i,16);if(a>1114111||a>=55296&&a<=57343)throw new xe("escape");return this.i+=2+o,String.fromCodePoint(a)}literalString(){let t=this.raw,n=++this.i;for(;;){if(this.i>=t.length)throw new xe("string");let r=t[this.i];if(r==="'")return this.i++,t.slice(n,this.i-1);if(r===`
171
171
  `||r==="\r")throw new xe("string");this.i++}}multiline(t){let n=this.raw,r=t.repeat(3);for(this.i+=3;;){if(this.i>=n.length)throw new xe("string");if(t==='"'&&n[this.i]==="\\"){this.i+=2;continue}if(n.startsWith(r,this.i)){let o=3;for(;n[this.i+o]===t;)o++;if(o>5)throw new xe("string");this.i+=o;return}this.i++}}skipWs(){for(;this.raw[this.i]===" "||this.raw[this.i]===" ";)this.i++}skipBlank(){for(;;)if(this.skipWs(),this.atEol())this.eatEol();else if(this.raw[this.i]==="#")this.skipComment();else return}skipComment(){for(;this.i<this.raw.length&&!this.atEol();){if(this.raw[this.i]==="\r")throw new xe("cr");this.i++}}atEol(){return this.raw[this.i]===`
172
172
  `||this.raw[this.i]==="\r"&&this.raw[this.i+1]===`
173
173
  `}eatEol(){if(!(this.i>=this.raw.length))if(this.raw[this.i]===`
174
174
  `)this.i++;else if(this.raw.startsWith(`\r
175
- `,this.i))this.i+=2;else throw new xe("eol")}lineEnd(){this.skipWs();let t=null;if(this.raw[this.i]==="#"){let n=this.i;this.skipComment(),t={start:n,end:this.i}}return this.eatEol(),t}expect(t){if(!this.raw.startsWith(t,this.i))throw new xe(`expected ${t}`);this.i+=t.length}}});function wk(e,t){let n=t.map((i,a)=>({...i,seq:a})).sort((i,a)=>i.start-a.start||i.seq-a.seq),r="",o=0;for(let i of n){if(i.start<o||i.end<i.start||i.end>e.length)return null;r+=e.slice(o,i.start)+i.text,o=i.end}return r+e.slice(o)}function Ha(e){return MM.test(e)?e:Ke(e)}function ja(e){return e.map(Ha).join(".")}function Ke(e,t="basic"){if((t==="literal"||t==="ml-literal")&&!/['\u0000-\u0008\u000a-\u001f\u007f]/.test(e))return`'${e}'`;let n='"';for(let r of e){let o=r.codePointAt(0)??0;r==='"'?n+='\\"':r==="\\"?n+="\\\\":r==="\b"?n+="\\b":r===" "?n+="\\t":r===`
176
- `?n+="\\n":r==="\f"?n+="\\f":r==="\r"?n+="\\r":o<32||o===127?n+=`\\u${o.toString(16).padStart(4,"0").toUpperCase()}`:n+=r}return n+'"'}function Ai(e){return`[${e.map(t=>Ke(t)).join(", ")}]`}function Ua(e){return e.length===0?"{}":`{ ${e.map(([t,n])=>`${Ha(t)} = ${n}`).join(", ")} }`}function Ba(e,t){return{start:e.span.start,end:e.span.end,text:t}}function Ii(e,t,n,r,o){let i=Ci(e,t),a=s((c,l)=>`${c}${l} = ${r}${o!==void 0?` ${o}`:""}${e.eol}`,"line");switch(i.kind){case"section":{let c=$a(e,i.header);if(c!==null){let l=e.statements[c];return[Be(l.line.end,a(l.indent,ja(n)))]}return i.header<0?null:[Be(e.statements[i.header].line.end,a("",ja(n)))]}case"dotted":{let c=e.statements[i.last],l=e.raw.slice(c.key.partSpans[0].start,c.key.partSpans[i.prefix.length-1].end);return[Be(c.line.end,a(c.indent,`${l}.${ja(n)}`))]}case"inline":return Ka(e,i.ref.node,`${ja(n)} = ${r}`);default:return null}}function Ka(e,t,n){let r=t.entries.at(-1);if(r===void 0){let o={start:t.span.start+1,end:t.span.end-1};return/^[ \t]*$/.test(e.raw.slice(o.start,o.end))?[{...o,text:` ${n} `}]:[Be(o.start,` ${n}`)]}return[Be(r.value.span.end,`, ${n}`)]}function kk(e,t,n){let r=e.raw,o=t.span.end-1,i=t.items.at(-1);if(i===void 0){let p={start:t.span.start+1,end:o};return/^[ \t]*$/.test(r.slice(p.start,p.end))?[{...p,text:n}]:[Be(p.start,n)]}let a=i.comma!==null?i.comma+1:i.value.span.end,c=r.lastIndexOf(`
175
+ `,this.i))this.i+=2;else throw new xe("eol")}lineEnd(){this.skipWs();let t=null;if(this.raw[this.i]==="#"){let n=this.i;this.skipComment(),t={start:n,end:this.i}}return this.eatEol(),t}expect(t){if(!this.raw.startsWith(t,this.i))throw new xe(`expected ${t}`);this.i+=t.length}}});function kk(e,t){let n=t.map((i,a)=>({...i,seq:a})).sort((i,a)=>i.start-a.start||i.seq-a.seq),r="",o=0;for(let i of n){if(i.start<o||i.end<i.start||i.end>e.length)return null;r+=e.slice(o,i.start)+i.text,o=i.end}return r+e.slice(o)}function Ha(e){return LM.test(e)?e:Ke(e)}function ja(e){return e.map(Ha).join(".")}function Ke(e,t="basic"){if((t==="literal"||t==="ml-literal")&&!/['\u0000-\u0008\u000a-\u001f\u007f]/.test(e))return`'${e}'`;let n='"';for(let r of e){let o=r.codePointAt(0)??0;r==='"'?n+='\\"':r==="\\"?n+="\\\\":r==="\b"?n+="\\b":r===" "?n+="\\t":r===`
176
+ `?n+="\\n":r==="\f"?n+="\\f":r==="\r"?n+="\\r":o<32||o===127?n+=`\\u${o.toString(16).padStart(4,"0").toUpperCase()}`:n+=r}return n+'"'}function Ai(e){return`[${e.map(t=>Ke(t)).join(", ")}]`}function Ua(e){return e.length===0?"{}":`{ ${e.map(([t,n])=>`${Ha(t)} = ${n}`).join(", ")} }`}function Ba(e,t){return{start:e.span.start,end:e.span.end,text:t}}function Ii(e,t,n,r,o){let i=Ci(e,t),a=s((c,l)=>`${c}${l} = ${r}${o!==void 0?` ${o}`:""}${e.eol}`,"line");switch(i.kind){case"section":{let c=$a(e,i.header);if(c!==null){let l=e.statements[c];return[Be(l.line.end,a(l.indent,ja(n)))]}return i.header<0?null:[Be(e.statements[i.header].line.end,a("",ja(n)))]}case"dotted":{let c=e.statements[i.last],l=e.raw.slice(c.key.partSpans[0].start,c.key.partSpans[i.prefix.length-1].end);return[Be(c.line.end,a(c.indent,`${l}.${ja(n)}`))]}case"inline":return Ka(e,i.ref.node,`${ja(n)} = ${r}`);default:return null}}function Ka(e,t,n){let r=t.entries.at(-1);if(r===void 0){let o={start:t.span.start+1,end:t.span.end-1};return/^[ \t]*$/.test(e.raw.slice(o.start,o.end))?[{...o,text:` ${n} `}]:[Be(o.start,` ${n}`)]}return[Be(r.value.span.end,`, ${n}`)]}function vk(e,t,n){let r=e.raw,o=t.span.end-1,i=t.items.at(-1);if(i===void 0){let p={start:t.span.start+1,end:o};return/^[ \t]*$/.test(r.slice(p.start,p.end))?[{...p,text:n}]:[Be(p.start,n)]}let a=i.comma!==null?i.comma+1:i.value.span.end,c=r.lastIndexOf(`
177
177
  `,i.value.span.start-1)+1,l=r.slice(c,i.value.span.start);if(!(r.slice(a,o).includes(`
178
178
  `)&&/^[ \t]*$/.test(l)))return[Be(i.value.span.end,`, ${n}`)];let u=r.indexOf(`
179
- `,a)+1;return i.comma!==null?[Be(u,`${l}${n},${e.eol}`)]:[Be(i.value.span.end,","),Be(u,`${l}${n}${e.eol}`)]}function yp(e,t){let n=e.statements.some(o=>o.kind!=="blank"),r=t.map(o=>o.join(e.eol)+e.eol).join(e.eol);return Be(e.raw.length,(n?e.eol:"")+r)}function _p(e,t,n){let r=-1;if(e.statements.forEach((a,c)=>{a.kind==="header"&&hn(e.paths[c]??[],t)&&(r=c)}),r<0)return null;let o=$a(e,r)??r,i=n.map(a=>a.join(e.eol)+e.eol).join(e.eol);return Be(e.statements[o].line.end,e.eol+i)}function vk(e,t){let n=Kt(e,t);if(n!==void 0)return n.parent.kind==="entry"?bp(e,n.parent.inline,n.parent.index):n.parent.kind==="item"?$M(e,n.parent.array,n.parent.index):[Pe(e.statements[n.stmt].line)];let r=e.statements,o=[],i=new Set;r.forEach((l,d)=>{if(l.kind!=="header"||!hn(e.paths[d]??[],t))return;i.add(d);let u=$a(e,d);o.push({start:l.line.start,end:r[u??d].line.end})});let a=Fa(o).map(l=>Ek(e,l)),c=[];return r.forEach((l,d)=>{let u=e.paths[d];l.kind==="keyval"&&u!==null&&u.length>t.length&&hn(u,t)&&!i.has(e.sections[d])&&c.push(l.line)}),a.length===0&&c.length===0?null:Fa([...a,...c]).map(Pe)}function xk(e,t){return Pe(Ek(e,e.statements[t].line))}function bp(e,t,n){let r=t.entries,o=r[n];if(r.length===1){let i={start:t.span.start+1,end:t.span.end-1};return e.raw.slice(i.start,i.end).includes(`
180
- `)?[Pe({start:o.key.span.start,end:o.comma!==null?o.comma+1:o.value.span.end})]:[Pe(i)]}return n===r.length-1?[Pe({start:r[n-1].value.span.end,end:o.value.span.end})]:[Pe({start:o.key.span.start,end:r[n+1].key.span.start})]}function $M(e,t,n){let r=e.raw,o=t.items,i=o[n],a={start:i.value.span.start,end:i.comma!==null?i.comma+1:i.value.span.end};if(o.length===1){let p={start:t.span.start+1,end:t.span.end-1};if(!r.slice(p.start,p.end).includes(`
179
+ `,a)+1;return i.comma!==null?[Be(u,`${l}${n},${e.eol}`)]:[Be(i.value.span.end,","),Be(u,`${l}${n}${e.eol}`)]}function _p(e,t){let n=e.statements.some(o=>o.kind!=="blank"),r=t.map(o=>o.join(e.eol)+e.eol).join(e.eol);return Be(e.raw.length,(n?e.eol:"")+r)}function bp(e,t,n){let r=-1;if(e.statements.forEach((a,c)=>{a.kind==="header"&&hn(e.paths[c]??[],t)&&(r=c)}),r<0)return null;let o=$a(e,r)??r,i=n.map(a=>a.join(e.eol)+e.eol).join(e.eol);return Be(e.statements[o].line.end,e.eol+i)}function xk(e,t){let n=Kt(e,t);if(n!==void 0)return n.parent.kind==="entry"?wp(e,n.parent.inline,n.parent.index):n.parent.kind==="item"?jM(e,n.parent.array,n.parent.index):[Pe(e.statements[n.stmt].line)];let r=e.statements,o=[],i=new Set;r.forEach((l,d)=>{if(l.kind!=="header"||!hn(e.paths[d]??[],t))return;i.add(d);let u=$a(e,d);o.push({start:l.line.start,end:r[u??d].line.end})});let a=Fa(o).map(l=>Rk(e,l)),c=[];return r.forEach((l,d)=>{let u=e.paths[d];l.kind==="keyval"&&u!==null&&u.length>t.length&&hn(u,t)&&!i.has(e.sections[d])&&c.push(l.line)}),a.length===0&&c.length===0?null:Fa([...a,...c]).map(Pe)}function Sk(e,t){return Pe(Rk(e,e.statements[t].line))}function wp(e,t,n){let r=t.entries,o=r[n];if(r.length===1){let i={start:t.span.start+1,end:t.span.end-1};return e.raw.slice(i.start,i.end).includes(`
180
+ `)?[Pe({start:o.key.span.start,end:o.comma!==null?o.comma+1:o.value.span.end})]:[Pe(i)]}return n===r.length-1?[Pe({start:r[n-1].value.span.end,end:o.value.span.end})]:[Pe({start:o.key.span.start,end:r[n+1].key.span.start})]}function jM(e,t,n){let r=e.raw,o=t.items,i=o[n],a={start:i.value.span.start,end:i.comma!==null?i.comma+1:i.value.span.end};if(o.length===1){let p={start:t.span.start+1,end:t.span.end-1};if(!r.slice(p.start,p.end).includes(`
181
181
  `))return[Pe(p)]}let c=r.lastIndexOf(`
182
182
  `,i.value.span.start-1)+1,l=r.indexOf(`
183
183
  `,a.end),d=l===-1?r.length:l+1;if(/^[ \t]*$/.test(r.slice(c,i.value.span.start))&&/^[ \t]*(#[^\n]*)?\n?$/.test(r.slice(a.end,d).replace(/\r\n$/,`
184
- `))&&d<t.span.end){let p=[Pe({start:c,end:d})],f=o[n-1];return i.comma===null&&f!==void 0&&f.comma!==null&&p.push(Pe({start:f.comma,end:f.comma+1})),p}return o.length===1?[Pe(a)]:n===o.length-1?[Pe({start:o[n-1].value.span.end,end:i.value.span.end})]:[Pe({start:i.value.span.start,end:o[n+1].value.span.start})]}function Sk(e,t){let n=Fa(t),r=n[0];if(r!==void 0&&r.start===0){let o=e.statements,i=o.findIndex(a=>a.line.start===r.end);for(;i>=0&&i<o.length&&o[i].kind==="blank";)r.end=o[i++].line.end}return Fa(n).map(Pe)}function LM(e,t){return e.statements.findIndex(n=>n.line.start===t)}function Ek(e,t){let n=e.statements,r=LM(e,t.start);return r>0&&n[r-1].kind==="blank"&&n.slice(0,r-1).some(o=>o.kind!=="blank")?{start:n[r-1].line.start,end:t.end}:t}function Fa(e){let t=[];for(let n of[...e].sort((r,o)=>r.start-o.start)){let r=t.at(-1);r!==void 0&&n.start<=r.end?r.end=Math.max(r.end,n.end):t.push({...n})}return t}function Rk(e,t,n=new Set){for(let r=t+1;r<e.statements.length;r++){let o=e.statements[r];if(o.kind==="header")return!0;if(!(o.kind==="blank"||n.has(r)))return!1}return!0}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function Ti(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.toISOString()===t.toISOString();if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>Ti(n,t[r]));if(J(e)||J(t)){if(!J(e)||!J(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Object.hasOwn(t,r)&&Ti(e[r],t[r]))}return Object.is(e,t)}function Wt(e,t){let n=e;for(let r of t)if(typeof r=="number"?n=Array.isArray(n)?n[r]:void 0:n=J(n)?n[r]:void 0,n===void 0)return;return n}function Gt(e,t,n){if(t.length===0)return n(e);let[r,...o]=t;if(typeof r=="number"){let c=Array.isArray(e)?[...e]:[],l=Gt(c[r],o,n);return l===void 0?c.splice(r,1):c[r]=l,c}let i=J(e)?{...e}:{},a=Gt(i[r],o,n);return a===void 0?delete i[r]:i[r]=a,i}function wp(e,t){let n=e;for(let r of[...t].sort((o,i)=>i.length-o.length)){let o=Wt(n,r);(Array.isArray(o)&&o.length===0||J(o)&&Object.keys(o).length===0)&&(n=Gt(n,r,()=>{}))}return n}var Be,bk,Pe,MM,Ga=w(()=>{"use strict";La();Be=s((e,t)=>({start:e,end:e,text:t}),"insertAt"),bk=Be,Pe=s(e=>({start:e.start,end:e.end,text:""}),"removeRange");s(wk,"applyEdits");MM=/^[A-Za-z0-9_-]+$/;s(Ha,"tomlKey");s(ja,"tomlKeyPath");s(Ke,"tomlString");s(Ai,"tomlStringArray");s(Ua,"tomlInlineTable");s(Ba,"replaceValue");s(Ii,"insertKey");s(Ka,"insertInlineEntry");s(kk,"appendArrayItem");s(yp,"appendBlocks");s(_p,"insertBlocksAfterSections");s(vk,"removeAt");s(xk,"removeHeaderLine");s(bp,"removeInlineEntry");s($M,"removeArrayItem");s(Sk,"mergeRemovals");s(LM,"statementAt");s(Ek,"withBlankAbove");s(Fa,"mergeRanges");s(Rk,"sectionIsEmpty");s(J,"isTable");s(Ti,"sameValue");s(Wt,"getIn");s(Gt,"updateIn");s(wp,"pruneEmpty")});import{parse as jM,TomlError as FM}from"smol-toml";function ut(e){try{let t=jM(e,{integersAsBigInt:"asNeeded"});return J(t)?{value:t}:{reason:"is not a TOML table"}}catch(t){if(t instanceof FM){let n=t.message.split(`
185
- `)[0].replace(/^Invalid TOML document:\s*/,"");return{reason:`does not parse as TOML (line ${t.line}, column ${t.column}: ${n})`}}return{reason:`does not parse as TOML (${t instanceof Error?t.message:String(t)})`}}}function ao(e,t){return Ak(e,t)[0]?.command??null}function Ak(e,t){let n=[],r=Wt(e,["hooks","SessionStart"]);return Array.isArray(r)&&r.forEach((o,i)=>{let a=J(o)?o.hooks:void 0;Array.isArray(a)&&a.forEach((c,l)=>{J(c)&&typeof c.command=="string"&&c.command.includes(t)&&n.push({group:i,handler:l,command:c.command})})}),n}function vp(e){let t=e.length>0&&!e.endsWith(`
186
- `)?fp(e):"",n=Ri(e+t);return n===null?null:{doc:n,added:t}}function xp(e,t){let n=wk(e.doc.raw,t);return n===null?null:e.added!==""&&n.endsWith(e.added)?n.slice(0,-e.added.length):n}function Sp(e,t,n=[]){let r=ut(e);return"value"in r&&Ti(wp(t,n),wp(r.value,n))}function kp(e){let t=["[mcp_servers.maind]",`command = ${Ke(e.command)}`,`args = ${Ai(e.args)}`],n=Object.entries(e.env);return n.length===0?[t]:[t,["[mcp_servers.maind.env]",...n.map(([r,o])=>`${Ha(r)} = ${Ke(o)}`)]]}function Ik(e){return Ua(Object.entries(e).map(([t,n])=>[t,Ke(n)]))}function Nk(e,t){let n=["Add or complete the maind entry by hand; it should read:","",...kp(t).flatMap((p,f)=>f===0?p:["",...p])],r=ut(e);if(!("value"in r))return Se(r.reason,[Tk]);let o=r.value,i=o.mcp_servers;if(i!==void 0&&!J(i))return Se("defines mcp_servers, but not as a table",[Ni("mcp_servers")]);let a=J(i)?i.maind:void 0;if(a!==void 0&&!J(a))return Se("defines mcp_servers.maind, but not as a table",[Ni("mcp_servers.maind")]);let c=vp(e);if(c===null)return Se("holds TOML syntax the bridge does not edit",n);let l=a===void 0?HM(c.doc,t):UM(c.doc,a,t);if(l===null)return Se("lays out mcp_servers.maind in a way the bridge does not edit",n);if(l.length===0)return{kind:"unchanged"};let d=xp(c,l),u=Gt(o,Va,p=>{let f=J(p)?p:{};return{...f,command:t.command,args:[...t.args],env:{...J(f.env)?f.env:{},...t.env}}});return d===null||!Sp(d,u)?Se("could not be changed so that it parses to the intended entry",n):{kind:"write",next:d}}function HM(e,t){let n=Kt(e,["mcp_servers"]);if(n!==void 0&&n.node.kind==="inline"){let r=Ua([["command",Ke(t.command)],["args",Ai(t.args)],["env",Ik(t.env)]]);return Ka(e,n.node,`maind = ${r}`)}return[_p(e,["mcp_servers"],kp(t))??yp(e,kp(t))]}function UM(e,t,n){let r=Va,o=[],i=s(c=>c===null?!1:(o.push(...c),!0),"add");if(t.command!==n.command&&!i(Ck(e,r,"command",n.command)))return null;if(!Ti(t.args,[...n.args])){let c=Kt(e,[...r,"args"]),l=t.args;if(c===void 0){if(!i(Ii(e,r,["args"],Ai(n.args))))return null}else c.node.kind==="array"&&Array.isArray(l)&&l.length===n.args.length&&c.node.items.every(d=>d.value.kind==="string")?c.node.items.forEach((d,u)=>{l[u]!==n.args[u]&&d.value.kind==="string"&&o.push(Ba(d.value,Ke(n.args[u],d.value.style)))}):o.push(Ba(c.node,Ai(n.args)))}let a=t.env;if(a===void 0){if(Object.keys(n.env).length>0&&!i(Ii(e,r,["env"],Ik(n.env))))return null}else if(J(a)){for(let[c,l]of Object.entries(n.env))if(a[c]!==l&&!i(Ck(e,[...r,"env"],c,l)))return null}else return null;return o}function Ck(e,t,n,r){let o=Kt(e,[...t,n]);return o===void 0?Ii(e,t,[n],Ke(r)):[Ba(o.node,Ke(r,o.node.kind==="string"?o.node.style:"basic"))]}function BM(e){return Ua([["type",Ke("command")],["command",Ke(e.command)],["timeout",String(e.timeout)],["additionalContextLimit",String(e.additionalContextLimit)]])}function Wa(e){return["[[hooks.SessionStart]]","[[hooks.SessionStart.hooks]]",'type = "command"',`command = ${Ke(e.command)}`,`timeout = ${e.timeout}`,`additionalContextLimit = ${e.additionalContextLimit}`]}function Ok(e,t,n){let r=ut(e);if(!("value"in r))return Se(r.reason,[Tk]);let o=r.value,i=o.features,a=!(J(i)&&i.hooks===!0),c=[a?"Add maind's SessionStart group by hand, and hooks = true in [features]:":"Add maind's SessionStart group by hand:","",...Wa(t)];if(i!==void 0&&!J(i))return Se("defines features, but not as a table",[Ni("features")]);if(J(i)&&i.hooks===!1)return{kind:"off",key:"hooks"};if(J(i)&&i.codex_hooks===!1)return{kind:"off",key:"codex_hooks"};let l=o.hooks;if(l!==void 0&&!J(l))return Se("defines hooks, but not as a table",[Ni("hooks")]);let d=J(l)?l.SessionStart:void 0;if(d!==void 0&&!Array.isArray(d))return Se("defines hooks.SessionStart, but not as an array of tables",[Ni("hooks.SessionStart","an array of tables")]);let u=ao(o,n);if(u!==null)return{kind:"wired",command:u};if(a&&J(i)&&i.hooks!==void 0)return Se("sets features.hooks to something other than true or false",["Set hooks = true in [features] (or remove the key), then run install again."]);let p=vp(e);if(p===null)return Se("holds TOML syntax the bridge does not edit",c);let f=p.doc,m=[],g=[];if(a){let v=Ci(f,["features"]);if(v.kind==="absent"||v.kind==="implicit")g.push(KM);else{let E=v.kind==="conflict"?null:Ii(f,["features"],["hooks"],"true",so);if(E===null)return Se("lays out [features] in a way the bridge does not edit",c);m.push(...E);let S=v.kind==="inline"?f.statements[v.ref.stmt]:void 0;v.kind==="inline"&&v.ref.parent.kind==="keyval"&&S?.kind==="keyval"&&S.comment===null&&m.push(bk(S.value.span.end,` ${so}`))}}let y=`{ hooks = [${BM(t)}] }`;if(d===void 0){let v=Ci(f,["hooks"]);if(v.kind==="inline")m.push(...Ka(f,v.ref.node,`SessionStart = [${y}]`));else{if(v.kind==="conflict")return Se("lays out [hooks] in a way the bridge does not edit",c);g.push(Wa(t))}}else{let v=Kt(f,["hooks","SessionStart"]),E=v===void 0?_p(f,["hooks","SessionStart"],[Wa(t)]):null;if(E!==null)m.push(E);else if(v===void 0)g.push(Wa(t));else if(v.node.kind==="array")m.push(...kk(f,v.node,y));else return Se("lays out hooks.SessionStart in a way the bridge does not edit",c)}g.length>0&&m.push(yp(f,g));let _=xp(p,m),b={hooks:[{type:"command",command:t.command,timeout:t.timeout,additionalContextLimit:t.additionalContextLimit}]},k=a?Gt(o,["features","hooks"],()=>!0):o;return k=Gt(k,["hooks","SessionStart"],v=>[...Array.isArray(v)?v:[],b]),_===null||!Sp(_,k)?Se("could not be changed so that it parses to the intended hook",c):{kind:"write",next:_}}function Dk(e,t){let n=ut(e);if(!("value"in n))return{kind:"refuse",reason:n.reason,manual:[]};let r=n.value,o=vp(e);if(o===null)return{kind:"refuse",reason:"holds TOML syntax the bridge does not edit",manual:[]};let i=o.doc,a=[],c=[],l=[],d=r,u=s((_,b,k)=>{let v=vk(i,_);return v===null?!1:(a.push(...v),d=Gt(d,_,()=>{}),l.push(...k),c.push(b),!0)},"take"),p=s(_=>({kind:"refuse",reason:_,manual:["Remove by hand: the [mcp_servers.maind] table and the SessionStart handler whose command runs on-session-briefing."]}),"manual");if(Wt(r,Va)!==void 0&&!u(Va,"[mcp_servers.maind]",[["mcp_servers"]]))return p("lays out mcp_servers.maind in a way the bridge does not edit");let f=Ak(r,t.token);if(f.length>1)return p(`holds ${f.length} SessionStart handlers that run ${t.token}`);if(f.length===1){let{group:_,handler:b}=f[0],k=Wt(r,["hooks","SessionStart"]),v=Wt(r,["hooks","SessionStart",_]),E=J(v)&&Object.keys(v).length===1&&Array.isArray(v.hooks)&&v.hooks.length===1,S=E?["hooks","SessionStart",_]:["hooks","SessionStart",_,"hooks",b];if(E&&Array.isArray(k)&&k.length===1&&Kt(i,["hooks","SessionStart"])?.parent.kind==="entry"&&(S=["hooks","SessionStart"]),!u(S,"the SessionStart hook",[["hooks","SessionStart",_,"hooks"],["hooks","SessionStart"],["hooks"]]))return p("lays out hooks.SessionStart in a way the bridge does not edit")}let m=Kt(i,["features","hooks"]),g=m===void 0?void 0:i.statements[m.stmt];if(m!==void 0&&g?.kind==="keyval"&&Wt(r,["features","hooks"])===!0&&gp(i,g)===so){let _=a.length;if(m.parent.kind==="keyval"){a.push({start:g.line.start,end:g.line.end,text:""});let b=hp(i,["features"]),k=b>=0?i.statements[b]:void 0;k?.kind==="header"&&gp(i,k)===so&&i.sections[m.stmt]===b&&Rk(i,b,new Set([m.stmt]))&&a.push(xk(i,b))}else m.parent.kind==="entry"&&g.comment!==null&&(a.push(...bp(i,m.parent.inline,m.parent.index)),a.push({start:g.value.span.end,end:g.comment.end,text:""}));a.length>_&&(d=Gt(d,["features","hooks"],()=>{}),l.push(["features"]),c.push("[features] hooks"))}if(a.length===0)return{kind:"none"};let y=xp(o,Sk(i,a));return y===null||!Sp(y,d,l)?p("could not be changed so that it parses to the file without maind's entries"):{kind:"write",next:y,removed:c}}var Va,so,Se,Tk,Ni,KM,co=w(()=>{"use strict";La();Ga();Va=["mcp_servers","maind"],so="# maind: SessionStart hook",Se=s((e,t)=>({kind:"refuse",reason:e,manual:t}),"refuse"),Tk="Fix the file, then run install again.",Ni=s((e,t="a table")=>`Make ${e} ${t} (or remove it), then run install again.`,"makeTable");s(ut,"parseCodexConfig");s(ao,"findCodexHookCommand");s(Ak,"ourHandlers");s(vp,"workOn");s(xp,"finish");s(Sp,"checksOut");s(kp,"serverBlocks");s(Ik,"inlineEnv");s(Nk,"planCodexServer");s(HM,"createServer");s(UM,"updateServer");s(Ck,"setString");s(BM,"handlerInline");s(Wa,"hookBlock");KM=[`[features] ${so}`,`hooks = true ${so}`];s(Ok,"planCodexHook");s(Dk,"planMaindRemoval")});async function Mk(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(c){return Pk(e,"read",c)}let o=r===null,i=Nk(r??"",t);if(i.kind==="unchanged")return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};if(i.kind==="refuse")return{target:e.key,action:"merge",status:"failed",detail:`${e.path} ${i.reason} \u2014 left untouched`,manual:i.manual};let a=o?"write":"merge";if(n)return{target:e.key,action:a,status:o?"would-create":"would-merge",detail:e.path};try{if(!await Ma(e.path,r,i.next))return{target:e.key,action:a,status:"failed",detail:`${e.path} changed while install ran \u2014 left untouched; run install again`}}catch(c){return Pk(e,"write",c)}return{target:e.key,action:a,status:o?"created":"merged",detail:e.path}}function Pk(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var $k=w(()=>{"use strict";se();co();s(Mk,"mergeTomlConfig");s(Pk,"failed")});function qM(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 zM(e){return`I want to add the **maind MCP server** to my AI coding agent.
184
+ `))&&d<t.span.end){let p=[Pe({start:c,end:d})],f=o[n-1];return i.comma===null&&f!==void 0&&f.comma!==null&&p.push(Pe({start:f.comma,end:f.comma+1})),p}return o.length===1?[Pe(a)]:n===o.length-1?[Pe({start:o[n-1].value.span.end,end:i.value.span.end})]:[Pe({start:i.value.span.start,end:o[n+1].value.span.start})]}function Ek(e,t){let n=Fa(t),r=n[0];if(r!==void 0&&r.start===0){let o=e.statements,i=o.findIndex(a=>a.line.start===r.end);for(;i>=0&&i<o.length&&o[i].kind==="blank";)r.end=o[i++].line.end}return Fa(n).map(Pe)}function FM(e,t){return e.statements.findIndex(n=>n.line.start===t)}function Rk(e,t){let n=e.statements,r=FM(e,t.start);return r>0&&n[r-1].kind==="blank"&&n.slice(0,r-1).some(o=>o.kind!=="blank")?{start:n[r-1].line.start,end:t.end}:t}function Fa(e){let t=[];for(let n of[...e].sort((r,o)=>r.start-o.start)){let r=t.at(-1);r!==void 0&&n.start<=r.end?r.end=Math.max(r.end,n.end):t.push({...n})}return t}function Ck(e,t,n=new Set){for(let r=t+1;r<e.statements.length;r++){let o=e.statements[r];if(o.kind==="header")return!0;if(!(o.kind==="blank"||n.has(r)))return!1}return!0}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function Ti(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.toISOString()===t.toISOString();if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>Ti(n,t[r]));if(J(e)||J(t)){if(!J(e)||!J(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Object.hasOwn(t,r)&&Ti(e[r],t[r]))}return Object.is(e,t)}function Wt(e,t){let n=e;for(let r of t)if(typeof r=="number"?n=Array.isArray(n)?n[r]:void 0:n=J(n)?n[r]:void 0,n===void 0)return;return n}function Gt(e,t,n){if(t.length===0)return n(e);let[r,...o]=t;if(typeof r=="number"){let c=Array.isArray(e)?[...e]:[],l=Gt(c[r],o,n);return l===void 0?c.splice(r,1):c[r]=l,c}let i=J(e)?{...e}:{},a=Gt(i[r],o,n);return a===void 0?delete i[r]:i[r]=a,i}function kp(e,t){let n=e;for(let r of[...t].sort((o,i)=>i.length-o.length)){let o=Wt(n,r);(Array.isArray(o)&&o.length===0||J(o)&&Object.keys(o).length===0)&&(n=Gt(n,r,()=>{}))}return n}var Be,wk,Pe,LM,Ga=w(()=>{"use strict";La();Be=s((e,t)=>({start:e,end:e,text:t}),"insertAt"),wk=Be,Pe=s(e=>({start:e.start,end:e.end,text:""}),"removeRange");s(kk,"applyEdits");LM=/^[A-Za-z0-9_-]+$/;s(Ha,"tomlKey");s(ja,"tomlKeyPath");s(Ke,"tomlString");s(Ai,"tomlStringArray");s(Ua,"tomlInlineTable");s(Ba,"replaceValue");s(Ii,"insertKey");s(Ka,"insertInlineEntry");s(vk,"appendArrayItem");s(_p,"appendBlocks");s(bp,"insertBlocksAfterSections");s(xk,"removeAt");s(Sk,"removeHeaderLine");s(wp,"removeInlineEntry");s(jM,"removeArrayItem");s(Ek,"mergeRemovals");s(FM,"statementAt");s(Rk,"withBlankAbove");s(Fa,"mergeRanges");s(Ck,"sectionIsEmpty");s(J,"isTable");s(Ti,"sameValue");s(Wt,"getIn");s(Gt,"updateIn");s(kp,"pruneEmpty")});import{parse as HM,TomlError as UM}from"smol-toml";function ut(e){try{let t=HM(e,{integersAsBigInt:"asNeeded"});return J(t)?{value:t}:{reason:"is not a TOML table"}}catch(t){if(t instanceof UM){let n=t.message.split(`
185
+ `)[0].replace(/^Invalid TOML document:\s*/,"");return{reason:`does not parse as TOML (line ${t.line}, column ${t.column}: ${n})`}}return{reason:`does not parse as TOML (${t instanceof Error?t.message:String(t)})`}}}function ao(e,t){return Ik(e,t)[0]?.command??null}function Ik(e,t){let n=[],r=Wt(e,["hooks","SessionStart"]);return Array.isArray(r)&&r.forEach((o,i)=>{let a=J(o)?o.hooks:void 0;Array.isArray(a)&&a.forEach((c,l)=>{J(c)&&typeof c.command=="string"&&c.command.includes(t)&&n.push({group:i,handler:l,command:c.command})})}),n}function xp(e){let t=e.length>0&&!e.endsWith(`
186
+ `)?mp(e):"",n=Ri(e+t);return n===null?null:{doc:n,added:t}}function Sp(e,t){let n=kk(e.doc.raw,t);return n===null?null:e.added!==""&&n.endsWith(e.added)?n.slice(0,-e.added.length):n}function Ep(e,t,n=[]){let r=ut(e);return"value"in r&&Ti(kp(t,n),kp(r.value,n))}function vp(e){let t=["[mcp_servers.maind]",`command = ${Ke(e.command)}`,`args = ${Ai(e.args)}`],n=Object.entries(e.env);return n.length===0?[t]:[t,["[mcp_servers.maind.env]",...n.map(([r,o])=>`${Ha(r)} = ${Ke(o)}`)]]}function Nk(e){return Ua(Object.entries(e).map(([t,n])=>[t,Ke(n)]))}function Ok(e,t){let n=["Add or complete the maind entry by hand; it should read:","",...vp(t).flatMap((p,f)=>f===0?p:["",...p])],r=ut(e);if(!("value"in r))return Se(r.reason,[Ak]);let o=r.value,i=o.mcp_servers;if(i!==void 0&&!J(i))return Se("defines mcp_servers, but not as a table",[Ni("mcp_servers")]);let a=J(i)?i.maind:void 0;if(a!==void 0&&!J(a))return Se("defines mcp_servers.maind, but not as a table",[Ni("mcp_servers.maind")]);let c=xp(e);if(c===null)return Se("holds TOML syntax the bridge does not edit",n);let l=a===void 0?BM(c.doc,t):KM(c.doc,a,t);if(l===null)return Se("lays out mcp_servers.maind in a way the bridge does not edit",n);if(l.length===0)return{kind:"unchanged"};let d=Sp(c,l),u=Gt(o,Va,p=>{let f=J(p)?p:{};return{...f,command:t.command,args:[...t.args],env:{...J(f.env)?f.env:{},...t.env}}});return d===null||!Ep(d,u)?Se("could not be changed so that it parses to the intended entry",n):{kind:"write",next:d}}function BM(e,t){let n=Kt(e,["mcp_servers"]);if(n!==void 0&&n.node.kind==="inline"){let r=Ua([["command",Ke(t.command)],["args",Ai(t.args)],["env",Nk(t.env)]]);return Ka(e,n.node,`maind = ${r}`)}return[bp(e,["mcp_servers"],vp(t))??_p(e,vp(t))]}function KM(e,t,n){let r=Va,o=[],i=s(c=>c===null?!1:(o.push(...c),!0),"add");if(t.command!==n.command&&!i(Tk(e,r,"command",n.command)))return null;if(!Ti(t.args,[...n.args])){let c=Kt(e,[...r,"args"]),l=t.args;if(c===void 0){if(!i(Ii(e,r,["args"],Ai(n.args))))return null}else c.node.kind==="array"&&Array.isArray(l)&&l.length===n.args.length&&c.node.items.every(d=>d.value.kind==="string")?c.node.items.forEach((d,u)=>{l[u]!==n.args[u]&&d.value.kind==="string"&&o.push(Ba(d.value,Ke(n.args[u],d.value.style)))}):o.push(Ba(c.node,Ai(n.args)))}let a=t.env;if(a===void 0){if(Object.keys(n.env).length>0&&!i(Ii(e,r,["env"],Nk(n.env))))return null}else if(J(a)){for(let[c,l]of Object.entries(n.env))if(a[c]!==l&&!i(Tk(e,[...r,"env"],c,l)))return null}else return null;return o}function Tk(e,t,n,r){let o=Kt(e,[...t,n]);return o===void 0?Ii(e,t,[n],Ke(r)):[Ba(o.node,Ke(r,o.node.kind==="string"?o.node.style:"basic"))]}function GM(e){return Ua([["type",Ke("command")],["command",Ke(e.command)],["timeout",String(e.timeout)],["additionalContextLimit",String(e.additionalContextLimit)]])}function Wa(e){return["[[hooks.SessionStart]]","[[hooks.SessionStart.hooks]]",'type = "command"',`command = ${Ke(e.command)}`,`timeout = ${e.timeout}`,`additionalContextLimit = ${e.additionalContextLimit}`]}function Dk(e,t,n){let r=ut(e);if(!("value"in r))return Se(r.reason,[Ak]);let o=r.value,i=o.features,a=!(J(i)&&i.hooks===!0),c=[a?"Add maind's SessionStart group by hand, and hooks = true in [features]:":"Add maind's SessionStart group by hand:","",...Wa(t)];if(i!==void 0&&!J(i))return Se("defines features, but not as a table",[Ni("features")]);if(J(i)&&i.hooks===!1)return{kind:"off",key:"hooks"};if(J(i)&&i.codex_hooks===!1)return{kind:"off",key:"codex_hooks"};let l=o.hooks;if(l!==void 0&&!J(l))return Se("defines hooks, but not as a table",[Ni("hooks")]);let d=J(l)?l.SessionStart:void 0;if(d!==void 0&&!Array.isArray(d))return Se("defines hooks.SessionStart, but not as an array of tables",[Ni("hooks.SessionStart","an array of tables")]);let u=ao(o,n);if(u!==null)return{kind:"wired",command:u};if(a&&J(i)&&i.hooks!==void 0)return Se("sets features.hooks to something other than true or false",["Set hooks = true in [features] (or remove the key), then run install again."]);let p=xp(e);if(p===null)return Se("holds TOML syntax the bridge does not edit",c);let f=p.doc,m=[],g=[];if(a){let v=Ci(f,["features"]);if(v.kind==="absent"||v.kind==="implicit")g.push(WM);else{let E=v.kind==="conflict"?null:Ii(f,["features"],["hooks"],"true",so);if(E===null)return Se("lays out [features] in a way the bridge does not edit",c);m.push(...E);let S=v.kind==="inline"?f.statements[v.ref.stmt]:void 0;v.kind==="inline"&&v.ref.parent.kind==="keyval"&&S?.kind==="keyval"&&S.comment===null&&m.push(wk(S.value.span.end,` ${so}`))}}let y=`{ hooks = [${GM(t)}] }`;if(d===void 0){let v=Ci(f,["hooks"]);if(v.kind==="inline")m.push(...Ka(f,v.ref.node,`SessionStart = [${y}]`));else{if(v.kind==="conflict")return Se("lays out [hooks] in a way the bridge does not edit",c);g.push(Wa(t))}}else{let v=Kt(f,["hooks","SessionStart"]),E=v===void 0?bp(f,["hooks","SessionStart"],[Wa(t)]):null;if(E!==null)m.push(E);else if(v===void 0)g.push(Wa(t));else if(v.node.kind==="array")m.push(...vk(f,v.node,y));else return Se("lays out hooks.SessionStart in a way the bridge does not edit",c)}g.length>0&&m.push(_p(f,g));let _=Sp(p,m),b={hooks:[{type:"command",command:t.command,timeout:t.timeout,additionalContextLimit:t.additionalContextLimit}]},k=a?Gt(o,["features","hooks"],()=>!0):o;return k=Gt(k,["hooks","SessionStart"],v=>[...Array.isArray(v)?v:[],b]),_===null||!Ep(_,k)?Se("could not be changed so that it parses to the intended hook",c):{kind:"write",next:_}}function Pk(e,t){let n=ut(e);if(!("value"in n))return{kind:"refuse",reason:n.reason,manual:[]};let r=n.value,o=xp(e);if(o===null)return{kind:"refuse",reason:"holds TOML syntax the bridge does not edit",manual:[]};let i=o.doc,a=[],c=[],l=[],d=r,u=s((_,b,k)=>{let v=xk(i,_);return v===null?!1:(a.push(...v),d=Gt(d,_,()=>{}),l.push(...k),c.push(b),!0)},"take"),p=s(_=>({kind:"refuse",reason:_,manual:["Remove by hand: the [mcp_servers.maind] table and the SessionStart handler whose command runs on-session-briefing."]}),"manual");if(Wt(r,Va)!==void 0&&!u(Va,"[mcp_servers.maind]",[["mcp_servers"]]))return p("lays out mcp_servers.maind in a way the bridge does not edit");let f=Ik(r,t.token);if(f.length>1)return p(`holds ${f.length} SessionStart handlers that run ${t.token}`);if(f.length===1){let{group:_,handler:b}=f[0],k=Wt(r,["hooks","SessionStart"]),v=Wt(r,["hooks","SessionStart",_]),E=J(v)&&Object.keys(v).length===1&&Array.isArray(v.hooks)&&v.hooks.length===1,S=E?["hooks","SessionStart",_]:["hooks","SessionStart",_,"hooks",b];if(E&&Array.isArray(k)&&k.length===1&&Kt(i,["hooks","SessionStart"])?.parent.kind==="entry"&&(S=["hooks","SessionStart"]),!u(S,"the SessionStart hook",[["hooks","SessionStart",_,"hooks"],["hooks","SessionStart"],["hooks"]]))return p("lays out hooks.SessionStart in a way the bridge does not edit")}let m=Kt(i,["features","hooks"]),g=m===void 0?void 0:i.statements[m.stmt];if(m!==void 0&&g?.kind==="keyval"&&Wt(r,["features","hooks"])===!0&&yp(i,g)===so){let _=a.length;if(m.parent.kind==="keyval"){a.push({start:g.line.start,end:g.line.end,text:""});let b=gp(i,["features"]),k=b>=0?i.statements[b]:void 0;k?.kind==="header"&&yp(i,k)===so&&i.sections[m.stmt]===b&&Ck(i,b,new Set([m.stmt]))&&a.push(Sk(i,b))}else m.parent.kind==="entry"&&g.comment!==null&&(a.push(...wp(i,m.parent.inline,m.parent.index)),a.push({start:g.value.span.end,end:g.comment.end,text:""}));a.length>_&&(d=Gt(d,["features","hooks"],()=>{}),l.push(["features"]),c.push("[features] hooks"))}if(a.length===0)return{kind:"none"};let y=Sp(o,Ek(i,a));return y===null||!Ep(y,d,l)?p("could not be changed so that it parses to the file without maind's entries"):{kind:"write",next:y,removed:c}}var Va,so,Se,Ak,Ni,WM,co=w(()=>{"use strict";La();Ga();Va=["mcp_servers","maind"],so="# maind: SessionStart hook",Se=s((e,t)=>({kind:"refuse",reason:e,manual:t}),"refuse"),Ak="Fix the file, then run install again.",Ni=s((e,t="a table")=>`Make ${e} ${t} (or remove it), then run install again.`,"makeTable");s(ut,"parseCodexConfig");s(ao,"findCodexHookCommand");s(Ik,"ourHandlers");s(xp,"workOn");s(Sp,"finish");s(Ep,"checksOut");s(vp,"serverBlocks");s(Nk,"inlineEnv");s(Ok,"planCodexServer");s(BM,"createServer");s(KM,"updateServer");s(Tk,"setString");s(GM,"handlerInline");s(Wa,"hookBlock");WM=[`[features] ${so}`,`hooks = true ${so}`];s(Dk,"planCodexHook");s(Pk,"planMaindRemoval")});async function $k(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(c){return Mk(e,"read",c)}let o=r===null,i=Ok(r??"",t);if(i.kind==="unchanged")return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};if(i.kind==="refuse")return{target:e.key,action:"merge",status:"failed",detail:`${e.path} ${i.reason} \u2014 left untouched`,manual:i.manual};let a=o?"write":"merge";if(n)return{target:e.key,action:a,status:o?"would-create":"would-merge",detail:e.path};try{if(!await Ma(e.path,r,i.next))return{target:e.key,action:a,status:"failed",detail:`${e.path} changed while install ran \u2014 left untouched; run install again`}}catch(c){return Mk(e,"write",c)}return{target:e.key,action:a,status:o?"created":"merged",detail:e.path}}function Mk(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}var Lk=w(()=>{"use strict";ae();co();s($k,"mergeTomlConfig");s(Mk,"failed")});function JM(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 YM(e){return`I want to add the **maind MCP server** to my AI coding agent.
187
187
 
188
188
  - My stack: \`__STACK__\`
189
189
  - MCP endpoint: \`${e}\`
@@ -384,7 +384,7 @@ ask me to merge it manually into \`~/.claude/settings.json\` or
384
384
  \`~/.claude/settings.local.json\`; do not auto-write hook JSON:
385
385
 
386
386
  \`\`\`json
387
- { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${Lk}", "timeout": 5 } ] } ] } }
387
+ { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${jk}", "timeout": 5 } ] } ] } }
388
388
  \`\`\`
389
389
 
390
390
  The hook runs the bridge subcommand \`on-session-reminder\` (bridge 0.94.0 or
@@ -489,7 +489,7 @@ ${d}`:""}
489
489
  config[serversKey].maind = server;
490
490
  fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
491
491
  console.log("WROTE " + file);
492
- NODE`}function JM(e){return`#!/usr/bin/env bash
492
+ NODE`}function XM(e){return`#!/usr/bin/env bash
493
493
  set -euo pipefail
494
494
 
495
495
  CONFIG_FILE="$HOME/.codex/config.toml"
@@ -542,7 +542,7 @@ if (serverCount !== 1 || envCount !== 1) {
542
542
 
543
543
  fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
544
544
  console.log("WROTE " + file);
545
- NODE`}function YM(e=Ep){let t=`${e}${VM}`;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:zM(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:`{
545
+ NODE`}function ZM(e=Rp){let t=`${e}${zM}`;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:YM(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:`{
546
546
  "mcpServers": {
547
547
  "maind": {
548
548
  "command": "npx",
@@ -570,7 +570,7 @@ args = ["-y", "@maind-dev/mcp-bridge"]
570
570
 
571
571
  [mcp_servers.maind.env]
572
572
  MAIND_CLIENT_FAMILY = "codex"
573
- 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:JM(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:`{
573
+ 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:XM(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:`{
574
574
  "servers": {
575
575
  "maind": {
576
576
  "type": "stdio",
@@ -616,7 +616,7 @@ echo ""
616
616
  echo "Next step \u2014 install the SessionStart hook for Claude Code:"
617
617
  echo " Merge this snippet into ~/.claude/settings.json (or settings.local.json):"
618
618
  echo ""
619
- echo ' { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${Lk}", "timeout": 5 } ] } ] } }'
619
+ echo ' { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${jk}", "timeout": 5 } ] } ] } }'
620
620
  echo ""
621
621
  echo " \u2022 The hook runs the bridge subcommand on-session-reminder (bridge 0.94.0 or later)"
622
622
  echo " \u2022 An entry that still runs 'cat ~/.claude/maind-session-start-reminder.md' is the"
@@ -694,7 +694,7 @@ const tools = await mcp.getTools();
694
694
  "env": {
695
695
  "MAIND_MCP_URL": "${t}"
696
696
  }
697
- }`}]}var GM,WM,Ep,VM,e3,Lk,Et,t3,qa=w(()=>{"use strict";GM="__STACK__",WM="__INTENT__",Ep="https://mcp.maind.dev/mcp",VM=`?stack=${GM}&intent=${WM}`;s(qM,"buildStackAwareEndpoint");e3=qM(Ep,{stack:["nextjs","supabase"],intent:"mixed"}),Lk="npx -y @maind-dev/mcp-bridge on-session-reminder",Et=`## maind MCP integration \u2014 Mandatory consultation
697
+ }`}]}var VM,qM,Rp,zM,n3,jk,Et,r3,qa=w(()=>{"use strict";VM="__STACK__",qM="__INTENT__",Rp="https://mcp.maind.dev/mcp",zM=`?stack=${VM}&intent=${qM}`;s(JM,"buildStackAwareEndpoint");n3=JM(Rp,{stack:["nextjs","supabase"],intent:"mixed"}),jk="npx -y @maind-dev/mcp-bridge on-session-reminder",Et=`## maind MCP integration \u2014 Mandatory consultation
698
698
 
699
699
  This project uses the maind MCP server (mcp.maind.dev/mcp) as
700
700
  authoritative source for vetted coding conventions and lessons. The
@@ -763,35 +763,35 @@ For non-trivial changes, resolve documentation path in this order:
763
763
  If no path is discoverable, provide a guided fallback:
764
764
  \`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
765
765
 
766
- Full tool set + provenance via \`get_conventions\`.`;s(zM,"buildAiPromptBody");s(ar,"buildJsonConfigInstaller");s(JM,"buildCodexTomlInstaller");s(YM,"buildSnippetTemplates");t3=YM(Ep)});function ZM(e){return`${Ya}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 QM(e){return`${Ya}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,`
767
- `).trim(),o=r.length===0?jk:Cp(r,Rp).text,i=n.team===!0?[XM,QM(t)]:[ZM(t)];return[za,...i,o,Ja].join(`
768
- `)}function Cp(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
766
+ Full tool set + provenance via \`get_conventions\`.`;s(YM,"buildAiPromptBody");s(ar,"buildJsonConfigInstaller");s(XM,"buildCodexTomlInstaller");s(ZM,"buildSnippetTemplates");r3=ZM(Rp)});function e$(e){return`${Ya}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 t$(e){return`${Ya}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,`
767
+ `).trim(),o=r.length===0?Fk:Tp(r,Cp).text,i=n.team===!0?[QM,t$(t)]:[e$(t)];return[za,...i,o,Ja].join(`
768
+ `)}function Tp(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
769
769
  `),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(`
770
770
  `),dropped:n.length-o.length}}o.push(n[a]),i+=c}return{text:o.join(`
771
- `),dropped:0}}function Fk(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Tp(e){let t=e.findIndex(o=>o.trim()===za);if(t<0)return{kind:"none"};let n=e.findIndex((o,i)=>i>t&&o.trim()===Ja);if(n<0)return{kind:"damaged",begin:t};let r=e.slice(t+1,n).some(o=>o.trim().startsWith(Oi));return{kind:"block",begin:t,end:n,team:r}}function Hk(e){let t=Tp(e.split(/\r?\n/));return t.kind==="block"&&t.team}function Uk(e){let t=e.split(/\r?\n/),n=Tp(t);if(n.kind!=="block")return null;let o=t.slice(n.begin+1,n.end).filter(i=>!i.trim().startsWith(Oi)&&!i.startsWith(Ya)).join(`
772
- `).trim();return o.length===0||o===jk?null:o}function Za(e,t,n=cr,r={}){let o=e.includes(`\r
771
+ `),dropped:0}}function Hk(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Ap(e){let t=e.findIndex(o=>o.trim()===za);if(t<0)return{kind:"none"};let n=e.findIndex((o,i)=>i>t&&o.trim()===Ja);if(n<0)return{kind:"damaged",begin:t};let r=e.slice(t+1,n).some(o=>o.trim().startsWith(Oi));return{kind:"block",begin:t,end:n,team:r}}function Uk(e){let t=Ap(e.split(/\r?\n/));return t.kind==="block"&&t.team}function Bk(e){let t=e.split(/\r?\n/),n=Ap(t);if(n.kind!=="block")return null;let o=t.slice(n.begin+1,n.end).filter(i=>!i.trim().startsWith(Oi)&&!i.startsWith(Ya)).join(`
772
+ `).trim();return o.length===0||o===Fk?null:o}function Za(e,t,n=cr,r={}){let o=e.includes(`\r
773
773
  `)?`\r
774
774
  `:`
775
775
  `,i=e.split(o),a=t.split(`
776
- `),c=Tp(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(t$(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:e$(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),m=i.slice(p+1),g=[...f,"",...a];return d===i.length?g.push(...m.length===0?[""]:m):((m.length===0||m[0].trim()!=="")&&g.push(""),g.push(...m)),{next:g.join(o),changed:!0,outcome:"inserted"}}function e$(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 t$(e,t){let n=s(i=>i.map(a=>a.replace(/\r$/,"")).filter(a=>!a.startsWith(Ya)),"strip"),r=n(e),o=n(t);return r.length===o.length&&r.every((i,a)=>i===o[a])}var za,Ja,Oi,XM,cr,Rp,jk,Ya,lo=w(()=>{"use strict";za="<!-- maind:conventions v1 begin -->",Ja="<!-- maind:conventions v1 end -->",Oi="<!-- maind:conventions scope=team",XM=`${Oi} \xB7 chosen with \`maind-mcp-bridge install --team\`: this block travels with the repository -->`,cr="## maind MCP integration",Rp=6e3,jk="(No conventions loaded yet \u2014 the bridge fills this block on the next session start in this repository.)",Ya="Project conventions \u2014 ";s(ZM,"renderConventionsLead");s(QM,"renderTeamLead");s(Xa,"renderConventionsBlock");s(Cp,"capAtLineBoundary");s(Fk,"countConventions");s(Tp,"locateConventionsBlock");s(Hk,"hasTeamBlock");s(Uk,"blockConventionsText");s(Za,"upsertConventionsBlock");s(e$,"appendBlock");s(t$,"sameConventions")});import{existsSync as n$}from"node:fs";import*as Bk from"node:path";function Me(e,t={},n=Ge){let r=t.fileExists??n$,o=t.expectedCommand??i$,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ap(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=s$(i,a.event,a.subcommand),d=l===null&&a.supersedes?a$(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(Ra(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(pn(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=c$(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 Ip(e){return e.some(t=>t.status!=="ok")}function Qa(e){return e.some(t=>t.remedy==="run-install")}function i$(e){return Qe(ve({entryPath:ie(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function s$(e,t,n){return Kk(e,t,r=>r.includes(n))}function a$(e,t,n){return Kk(e,t,r=>n.test(r))}function Kk(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!Ap(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!Ap(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function c$(e){for(let t of l$(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Bk.isAbsolute(t)?t:null;return null}function l$(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 Ap(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Y,Di,Vt,r$,o$,Ge,uo,he=w(()=>{"use strict";St();Y="on-session-briefing",Di=".claude/maind-session-start-reminder.md",Vt="on-session-reminder",r$=/maind-session-start-reminder\.md/,o$=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,Ge=[{event:"SessionStart",subcommand:Vt,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:r$,replaceable:o$},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:Y,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."}],uo=[{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(Me,"inspectHookWiring");s(Ip,"hasWiringDrift");s(Qa,"needsInstallRun");s(i$,"defaultExpectedCommand");s(s$,"findCommand");s(a$,"findCommandMatching");s(Kk,"findFirstCommand");s(c$,"extractScriptPath");s(l$,"tokenize");s(Ap,"isObject")});import*as Gk from"node:path";async function Np(e,t){let n=Gk.join(e,Di);try{if(await ck(n,cr))return{target:ec,action:"skip",status:"skipped",detail:`${cr} header already present`};let r=await q(n);if(t)return{target:ec,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:n};let o=r===null||r.length===0?`${Et}
777
- `:d$(r)+`${Et}
778
- `;return await B(n,o),{target:ec,action:r===null?"write":"append",status:r===null?"created":"merged",detail:n}}catch(r){return{target:ec,action:"write",status:"failed",detail:r instanceof Error?r.message:String(r)}}}function d$(e){return e.endsWith(`
776
+ `),c=Ap(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(r$(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:n$(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),m=i.slice(p+1),g=[...f,"",...a];return d===i.length?g.push(...m.length===0?[""]:m):((m.length===0||m[0].trim()!=="")&&g.push(""),g.push(...m)),{next:g.join(o),changed:!0,outcome:"inserted"}}function n$(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 r$(e,t){let n=s(i=>i.map(a=>a.replace(/\r$/,"")).filter(a=>!a.startsWith(Ya)),"strip"),r=n(e),o=n(t);return r.length===o.length&&r.every((i,a)=>i===o[a])}var za,Ja,Oi,QM,cr,Cp,Fk,Ya,lo=w(()=>{"use strict";za="<!-- maind:conventions v1 begin -->",Ja="<!-- maind:conventions v1 end -->",Oi="<!-- maind:conventions scope=team",QM=`${Oi} \xB7 chosen with \`maind-mcp-bridge install --team\`: this block travels with the repository -->`,cr="## maind MCP integration",Cp=6e3,Fk="(No conventions loaded yet \u2014 the bridge fills this block on the next session start in this repository.)",Ya="Project conventions \u2014 ";s(e$,"renderConventionsLead");s(t$,"renderTeamLead");s(Xa,"renderConventionsBlock");s(Tp,"capAtLineBoundary");s(Hk,"countConventions");s(Ap,"locateConventionsBlock");s(Uk,"hasTeamBlock");s(Bk,"blockConventionsText");s(Za,"upsertConventionsBlock");s(n$,"appendBlock");s(r$,"sameConventions")});import{existsSync as o$}from"node:fs";import*as Kk from"node:path";function Me(e,t={},n=Ge){let r=t.fileExists??o$,o=t.expectedCommand??a$,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ip(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=c$(i,a.event,a.subcommand),d=l===null&&a.supersedes?l$(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(Ra(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(pn(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=d$(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 Np(e){return e.some(t=>t.status!=="ok")}function Qa(e){return e.some(t=>t.remedy==="run-install")}function a$(e){return Qe(ve({entryPath:se(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function c$(e,t,n){return Gk(e,t,r=>r.includes(n))}function l$(e,t,n){return Gk(e,t,r=>n.test(r))}function Gk(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!Ip(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!Ip(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function d$(e){for(let t of u$(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Kk.isAbsolute(t)?t:null;return null}function u$(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 Ip(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Y,Di,Vt,i$,s$,Ge,uo,he=w(()=>{"use strict";St();Y="on-session-briefing",Di=".claude/maind-session-start-reminder.md",Vt="on-session-reminder",i$=/maind-session-start-reminder\.md/,s$=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,Ge=[{event:"SessionStart",subcommand:Vt,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:i$,replaceable:s$},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:Y,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."}],uo=[{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(Me,"inspectHookWiring");s(Np,"hasWiringDrift");s(Qa,"needsInstallRun");s(a$,"defaultExpectedCommand");s(c$,"findCommand");s(l$,"findCommandMatching");s(Gk,"findFirstCommand");s(d$,"extractScriptPath");s(u$,"tokenize");s(Ip,"isObject")});import*as Wk from"node:path";async function Op(e,t){let n=Wk.join(e,Di);try{if(await lk(n,cr))return{target:ec,action:"skip",status:"skipped",detail:`${cr} header already present`};let r=await q(n);if(t)return{target:ec,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:n};let o=r===null||r.length===0?`${Et}
777
+ `:p$(r)+`${Et}
778
+ `;return await B(n,o),{target:ec,action:r===null?"write":"append",status:r===null?"created":"merged",detail:n}}catch(r){return{target:ec,action:"write",status:"failed",detail:r instanceof Error?r.message:String(r)}}}function p$(e){return e.endsWith(`
779
779
 
780
780
  `)?e:e.endsWith(`
781
781
  `)?e+`
782
782
  `:e+`
783
783
 
784
- `}var ec,Wk=w(()=>{"use strict";qa();lo();se();he();ec="reminder:~/.claude/maind-session-start-reminder.md";s(Np,"writeReminderFile");s(d$,"ensureTrailingBlankLine")});import*as Vk from"node:path";async function qk(e){let t=Vk.join(e.projectRoot,"AGENTS.md"),n=s((r,o,i="upsert")=>({target:u$,action:i,status:r,detail:o}),"row");try{let r=await q(t),o=await e.conventions()??(r!==null?Uk(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 B(t,i+`
785
- `),n("created",`${t}${a}`,"write"));let c=Za(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 B(t,c.next),n("merged",`${t} (${l})${a}`))}}}catch(r){return n("failed",r instanceof Error?r.message:String(r))}}var u$,zk=w(()=>{"use strict";Ue();lo();se();u$="team:AGENTS.md#conventions";s(qk,"writeTeamConventionsBlock")});import{existsSync as p$,readFileSync as f$}from"node:fs";import{join as m$}from"node:path";function We(){return m$(dt(),"config.json")}function ee(){try{let e=We();if(!p$(e))return null;let t=JSON.parse(f$(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 Ve=w(()=>{"use strict";oe();s(We,"bridgeConfigPath");s(ee,"readBridgeConfig")});function h$(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===Op?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 Jk(e,t,n=We()){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=h$(i,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await B(n,JSON.stringify(c,null,2)+`
786
- `,384)}catch{}}var Op,Dp=w(()=>{"use strict";Ve();se();Op="user declined";s(h$,"nextDeclinedHooks");s(Jk,"recordHookDecisions")});import*as Yk from"node:path";import*as Xk from"node:readline";async function g$(e,t){let n=Yk.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: ${Pp(g)}`}}let i,a="create";if(o===null||o.trim().length===0)i={};else{a="merge";try{let g=JSON.parse(o);if(!Pi(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: ${Pp(g)}`}}}let c=b$(i,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};let l=t.supersedes?_$(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?`
784
+ `}var ec,Vk=w(()=>{"use strict";qa();lo();ae();he();ec="reminder:~/.claude/maind-session-start-reminder.md";s(Op,"writeReminderFile");s(p$,"ensureTrailingBlankLine")});import*as qk from"node:path";async function zk(e){let t=qk.join(e.projectRoot,"AGENTS.md"),n=s((r,o,i="upsert")=>({target:f$,action:i,status:r,detail:o}),"row");try{let r=await q(t),o=await e.conventions()??(r!==null?Bk(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 B(t,i+`
785
+ `),n("created",`${t}${a}`,"write"));let c=Za(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 B(t,c.next),n("merged",`${t} (${l})${a}`))}}}catch(r){return n("failed",r instanceof Error?r.message:String(r))}}var f$,Jk=w(()=>{"use strict";Ue();lo();ae();f$="team:AGENTS.md#conventions";s(zk,"writeTeamConventionsBlock")});import{existsSync as m$,readFileSync as h$}from"node:fs";import{join as g$}from"node:path";function We(){return g$(dt(),"config.json")}function te(){try{let e=We();if(!m$(e))return null;let t=JSON.parse(h$(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 Ve=w(()=>{"use strict";ie();s(We,"bridgeConfigPath");s(te,"readBridgeConfig")});function y$(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===Dp?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 Yk(e,t,n=We()){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=y$(i,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await B(n,JSON.stringify(c,null,2)+`
786
+ `,384)}catch{}}var Dp,Pp=w(()=>{"use strict";Ve();ae();Dp="user declined";s(y$,"nextDeclinedHooks");s(Yk,"recordHookDecisions")});import*as Xk from"node:path";import*as Zk from"node:readline";async function _$(e,t){let n=Xk.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: ${Mp(g)}`}}let i,a="create";if(o===null||o.trim().length===0)i={};else{a="merge";try{let g=JSON.parse(o);if(!Pi(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: ${Mp(g)}`}}}let c=k$(i,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};let l=t.supersedes?w$(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?`
787
787
  Replace the ${t.event} hook \`${l.command}\` in ${n}?
788
788
  ${t.consentDescription}
789
789
  [Y/n]: `:`
790
790
  Merge a ${t.event} hook into ${n}?
791
791
  ${t.consentDescription}
792
- [Y/n]: `;if(!await(e.prompt??w$)(e.out,g))return{target:r,action:"skip",status:"skipped",detail:Op}}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)+`
793
- `,m=l===null?"":` (replaced \`${l.command}\`)`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:l===null?n:`${n} (would replace \`${l.command}\`)`};try{await B(n,f,384)}catch(g){return{target:r,action:"merge",status:"failed",detail:`write: ${Pp(g)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n+m}}function y$(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Mi(e,t){let n=e.launch??ve({entryPath:ie(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Qe(n);return g$(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:y$(t),supersedes:t.supersedes,skipDetail:s(o=>{let i=`${t.label} already runs maind ${t.subcommand}`;return Ra(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}`:pn(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 Zk(e){let t=[];for(let n of Ge)t.push(await Mi(e,n));return t}function _$(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(!Pi(i))continue;let a=i.hooks;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=a[c];if(!Pi(l))continue;let d=l.command;if(typeof d=="string"&&n.test(d))return{group:o,hook:c,command:d}}}return null}function b$(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!Pi(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!Pi(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function w$(e,t){e.write(t);let n=Xk.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 Pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pp(e){return e instanceof Error?e.message:String(e)}var tc=w(()=>{"use strict";se();St();he();Dp();he();s(g$,"mergeClaudeHook");s(y$,"targetKeyFor");s(Mi,"mergeSubcommandHook");s(Zk,"mergeAllSubcommandHooks");s(_$,"findHookEntry");s(b$,"findExistingHookCommand");s(w$,"promptYesNo");s(Pi,"isObject");s(Pp,"errMessage")});import*as Qk from"node:readline";async function ev(e){let t=e.configPath??We(),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:lr,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:lr,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??v$)(e.out,k$)}else return{target:lr,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:lr,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)+`
794
- `;if(e.dryRun)return{target:lr,action:"merge",status:"would-merge",detail:t};try{await B(t,i,384)}catch(a){return{target:lr,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:lr,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}async function v$(e,t){e.write(t);let n=Qk.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 lr,k$,tv=w(()=>{"use strict";Ve();se();lr="config:auto_working_paths",k$=`
792
+ [Y/n]: `;if(!await(e.prompt??v$)(e.out,g))return{target:r,action:"skip",status:"skipped",detail:Dp}}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)+`
793
+ `,m=l===null?"":` (replaced \`${l.command}\`)`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:l===null?n:`${n} (would replace \`${l.command}\`)`};try{await B(n,f,384)}catch(g){return{target:r,action:"merge",status:"failed",detail:`write: ${Mp(g)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n+m}}function b$(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Mi(e,t){let n=e.launch??ve({entryPath:se(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Qe(n);return _$(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:b$(t),supersedes:t.supersedes,skipDetail:s(o=>{let i=`${t.label} already runs maind ${t.subcommand}`;return Ra(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}`:pn(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 Qk(e){let t=[];for(let n of Ge)t.push(await Mi(e,n));return t}function w$(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(!Pi(i))continue;let a=i.hooks;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=a[c];if(!Pi(l))continue;let d=l.command;if(typeof d=="string"&&n.test(d))return{group:o,hook:c,command:d}}}return null}function k$(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let o of r){if(!Pi(o))continue;let i=o.hooks;if(Array.isArray(i))for(let a of i){if(!Pi(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function v$(e,t){e.write(t);let n=Zk.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 Pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mp(e){return e instanceof Error?e.message:String(e)}var tc=w(()=>{"use strict";ae();St();he();Pp();he();s(_$,"mergeClaudeHook");s(b$,"targetKeyFor");s(Mi,"mergeSubcommandHook");s(Qk,"mergeAllSubcommandHooks");s(w$,"findHookEntry");s(k$,"findExistingHookCommand");s(v$,"promptYesNo");s(Pi,"isObject");s(Mp,"errMessage")});import*as ev from"node:readline";async function tv(e){let t=e.configPath??We(),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:lr,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:lr,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??S$)(e.out,x$)}else return{target:lr,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:lr,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)+`
794
+ `;if(e.dryRun)return{target:lr,action:"merge",status:"would-merge",detail:t};try{await B(t,i,384)}catch(a){return{target:lr,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:lr,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}async function S$(e,t){e.write(t);let n=ev.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 lr,x$,nv=w(()=>{"use strict";Ve();ae();lr="config:auto_working_paths",x$=`
795
795
  Enable presence enrichment (auto working_paths)?
796
796
  With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
797
797
  locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
@@ -800,12 +800,12 @@ before editing the same area. Directory names only: never file contents, never
800
800
  absolute paths. Server-side these paths are account-private (org members never
801
801
  see them) and revocable any time on the dashboard consent page or via
802
802
  {"auto_working_paths": false} in the bridge config.
803
- [y/N]: `;s(ev,"applyWorkingPathsConsent");s(v$,"promptYesNoDefaultNo")});function Mp(){return{ultracode:!1,planMode:!1,autoMode:!1}}var $p=w(()=>{"use strict";s(Mp,"newModeState")});import{createReadStream as x$,existsSync as S$}from"node:fs";import{stat as E$}from"node:fs/promises";import{createInterface as R$}from"node:readline";async function Lp(e){if(!e||!S$(e))return null;let t;try{t=await E$(e)}catch{return null}let n=new Set,r=0,o=0,i=0;return await new Promise(a=>{let c=x$(e,{encoding:"utf-8"}),l=R$({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 m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=m??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(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(Lp,"summariseTranscript")});var rv=w(()=>{"use strict"});function $i(e){if(!e)return null;let t=null;for(let n of e.matchAll(T$)){let r=n[1].toLowerCase();C$.has(r)&&(t=r)}return t}var C$,T$,nc=w(()=>{"use strict";C$=new Set(["low","medium","high","xhigh","max"]),T$=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s($i,"detectEffortLevel")});function po(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,rc=w(()=>{"use strict";ov=["mcp__maind__","mcp__plugin_maind_maind__"];s(po,"maindToolName")});import{createReadStream as A$,existsSync as I$,readdirSync as N$}from"node:fs";import{basename as av,dirname as O$,join as iv}from"node:path";import{createInterface as D$}from"node:readline";function lv(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!$$.test(n)||e.ids.includes(n)||e.ids.length>=cv||e.ids.push(n)}function L$(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=po(r.name);if(o===null||M$.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 j$(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 F$(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=j$(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 fo(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function U$(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=H$[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 oc(e){let t=av(e).replace(/\.jsonl$/,""),n=iv(O$(e),t,"subagents"),r;try{r=N$(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){I$(e)&&await new Promise(a=>{let c=A$(e,{encoding:"utf-8"}),l=D$({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"){F$(i,f.message.content);return}if(f.message?.role!=="assistant")return;L$(i,f.message.content);let m=typeof f.message.id=="string"&&f.message.id?f.message.id:null,g=typeof f.requestId=="string"&&f.requestId?f.requestId:null,y=m??g??`${e}#${d}`,_=U$(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 k=f.message.usage??{},v=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(v)?v:0,model:E||"<unknown>",synthetic:E===P$,input_tokens:fo(k.input_tokens),output_tokens:fo(k.output_tokens),cache_read_tokens:fo(k.cache_read_input_tokens),cache_creation_tokens:fo(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(fo(k.cache_creation?.ephemeral_1h_input_tokens),fo(k.cache_creation_input_tokens)),sidechain:f.isSidechain===!0,stream:t,edited_paths:_,cwd:typeof f.cwd=="string"&&f.cwd?f.cwd:null};r.set(y,S),o.push(S)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function jp(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 Li(e){let t=new Set,n=new Map,r=[],o=e?oc(e):[],i={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:o,coordination_ids:[]};let a=[];await sv(e,dr,t,n,a,i),jp(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),jp(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:o,coordination_ids:i.ids}}var dr,P$,M$,$$,cv,H$,ic=w(()=>{"use strict";rc();dr="main",P$="<synthetic>",M$=new Set(["get_session_analysis","get_session_cost_context"]),$$=/^[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(L$,"noteCoordinationUse");s(j$,"resultText");s(F$,"noteAnnounceResult");H$={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(fo,"num");s(U$,"editedPathsOf");s(oc,"subagentFilesOf");s(sv,"readStream");s(jp,"fillTimestamps");s(Li,"collectTurns")});import{createReadStream as dv,existsSync as B$}from"node:fs";import{createInterface as uv}from"node:readline";function J$(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 sc(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Y$(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
804
- `)}function X$(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 Z$(e,t,n){return K$.test(e)?{polarity:-1,magnitude:mo.rework,kind:"rework"}:n&&G$.test(e)?{polarity:-1,magnitude:mo.correction,kind:"correction"}:W$.test(e)?{polarity:1,magnitude:mo.acceptance,kind:"acceptance"}:t!==null&&X$(t,e)?{polarity:-1,magnitude:mo.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Q$(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 eL(e,t){for(let n of oc(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 sc(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string")continue;let d=po(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 Fp(e,t={}){let n=Q$("");if(!e||!B$(e))return n;let r=t.turns??(await Li(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let o=[],i=new Map,a=null,c=!1,l=null;await new Promise(m=>{let g=dv(e,{encoding:"utf-8"}),y=uv({input:g}),_=s(b=>{let k=b.trim();if(!k)return;let v;try{v=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let D=v.sessionId??v.session_id;typeof D=="string"&&D&&(n.session_id=D)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let E=v.message?.role,S=v.isSidechain===!0;if(E==="assistant")for(let D of sc(v.message?.content)){if(D.type!=="tool_use"||typeof D.name!="string")continue;let j=po(D.name);j!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[j]=(n.maind_tool_calls[j]??0)+1)}if(S)return;if(E==="assistant"){let D=sc(v.message?.content),j=!1;for(let At of D)At.type==="tool_use"&&(n.tool_calls++,j=!0,At.name==="AskUserQuestion"&&n.agent_questions++);c=j;return}if(E!=="user")return;let R=sc(v.message?.content),P=Y$(R);if(P.includes(V$)){n.interrupts++,o.push({polarity:-1,magnitude:mo.interrupt,kind:"interrupt"});return}if(R.some(D=>D.type==="tool_result"&&D.is_error===!0&&typeof D.content=="string"&&D.content.includes(q$))){n.tool_denials++,o.push({polarity:-1,magnitude:mo.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=$i(P);x&&(a=x);let T=Z$(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",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await eL(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||J$(i,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...i.values()].sort((m,g)=>m.first_ts-g.first_ts||m.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return o.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*z$+m.polarity*m.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=y,g>0&&o[g-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var pv,K$,G$,W$,V$,q$,z$,mo,fv=w(()=>{"use strict";nc();rc();ic();pv="2026-10-01",K$=/(\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,G$=/(\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,W$=/(\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,V$="[Request interrupted by user",q$="The user doesn't want to proceed with this tool use",z$=.7,mo={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(J$,"bumpModel");s(sc,"asBlocks");s(Y$,"textOf");s(X$,"isRepeat");s(Z$,"classifyGenuine");s(Q$,"emptyAnalysis");s(eL,"tallySubagentMaindCalls");s(Fp,"analyzeSession")});function Hp(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 Up(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 Bp(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(Hp,"parseIngestResponse");s(Up,"describeSliceVerdict");s(Bp,"ingestBody")});import{isAbsolute as hv,relative as tL,resolve as gv,sep as yv}from"node:path";function _v(e){return e>cc[1]?"above_272k":e>cc[0]?"band_200k_272k":"standard"}function bv(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ac(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function ji(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=ac(d.from);typeof d.object_id!="string"||!Kp.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ac(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=ac(c.from);typeof c.path_prefix!="string"||l===null||o.push({path_prefix:c.path_prefix,from:l,to:ac(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"||!Kp.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"&&Kp.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 lc(e,t){if(!hv(e))return null;let n=tL(gv(t),gv(e));return!n||n==="."||n.startsWith("..")||hv(n)?null:yv==="/"?n:n.split(yv).join("/")}function rL(e,t){return t===""||e===t||e.startsWith(t+"/")}function Wp(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 Vp(e,t){for(let n of wv(t))if(rL(e,n.path_prefix))return n.object_id;return null}function oL(e,t){for(let n of wv(t))if(Wp(e,n.path_prefix))return n.object_id;return null}function Gp(e,t){return e>=t.from&&(t.to===null||e<t.to)}function kv(e,t,n,r){let o=e.ts,i=r?.anchors??[],a=t.map(c=>Vp(c,i)).filter(c=>c!==null);if(r&&o>0){let c=r.leases.filter(u=>Gp(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=>Gp(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=>Gp(o,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>Wp(f.path_prefix,u))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=oL(f.path_prefix,i);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function qp(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?_=>lc(_,o):null),a=s(_=>{if(!i)return[];let b=[];for(let k of _.edited_paths){let v=i(k);v!==null&&!b.includes(v)&&b.push(v)}return b},"relOf"),c=s(_=>{for(let b of _){let k=Vp(b,r);if(k)return{object_id:k,rel:b}}return null},"firstAnchoredEdit"),l=new Map;for(let _ of e){let b=l.get(_.stream)??[];b.push(_),l.set(_.stream,b)}let d=[...l.entries()].sort(([_],[b])=>_===dr?-1:b===dr?1:0),u=[],p=s(_=>{let b=null;for(let k of u){if(k.ts>_&&_>0)break;b=k.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let k=b.map((E,S)=>({t:E,i:S,rels:a(E)})).sort((E,S)=>E.t.ts-S.t.ts||E.i-S.i),v=null;for(let E of k){let S=c(E.rels);if(S){v=S;break}}!v&&_!==dr&&k.length&&(v=p(k[0].t.ts));for(let E of k){let S=c(E.rels);S&&(v=S),_===dr&&u.push({ts:E.t.ts,seg:v});let R=E.t;if(R.input_tokens+R.output_tokens+R.cache_read_tokens+R.cache_creation_tokens===0)continue;let K=kv(R,E.rels,v,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}`,j=f.get(D);j||(j={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,j)),j.input_tokens+=R.input_tokens,j.output_tokens+=R.output_tokens,j.cache_read_tokens+=R.cache_read_tokens,j.cache_creation_tokens+=R.cache_creation_tokens,j.cache_creation_1h_tokens+=R.cache_creation_1h_tokens,j.turns+=1,R.ts>0&&((j.firstMs===0||R.ts<j.firstMs)&&(j.firstMs=R.ts),R.ts>j.lastMs&&(j.lastMs=R.ts))}}let m=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:k,...v}=_;v.first_ts=new Date(b>0?b:m).toISOString(),v.last_ts=new Date(k>0?k:m).toISOString(),g.push(v)}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 cc,nL,Kp,zp=w(()=>{"use strict";ic();cc=[2e5,272e3];s(_v,"contextTierOf");s(bv,"normalizeModelId");nL=cc[0],Kp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(ac,"msOf");s(ji,"parseCostContext");s(lc,"toRepoRelative");s(rL,"underPrefix");s(Wp,"prefixesOverlap");s(wv,"sortedAnchors");s(Vp,"anchorFor");s(oL,"bestAnchorOverlapping");s(Gp,"inWindow");s(kv,"assignTurn");s(qp,"sliceSession")});import{mkdirSync as iL,readFileSync as sL,renameSync as aL,writeFileSync as cL}from"node:fs";import{dirname as lL,isAbsolute as dc,sep as Jp}from"node:path";function dL(e){let t=e.split(Jp).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function uL(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function Yp(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])=>dc(u)).sort((u,p)=>p[0].length-u[0].length),c=new Map,l=s(u=>{if(!e.isDir)return null;let p=c.get(u);if(p!==void 0)return p;let f=d(u);return c.set(u,f),f},"byConvention"),d=s(u=>{if(!e.isDir)return null;let p=u.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let g=p.slice(0,f-1).join("/")||"/",y=p[f-1];for(let _=y.lastIndexOf("-");_>0;_=y.lastIndexOf("-",_-1)){let b=`${g==="/"?"":g}/${y.slice(0,_)}`;if(e.isDir(b)&&o(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!dc(u))return null;let p=u.split(Jp).join("/"),f=dL(p),m=o(f);if(m){let g=n(m);return i.set(m,g),{root:m,key:g}}for(let[g,y]of a)if(!(!uL(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 Xp(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 Zp(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:lc(n.split(Jp).join("/"),r.root)}}function Sv(e){try{let t=JSON.parse(sL(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 Fi(e){let t=new Map,n=Sv(e);for(let[r,o]of Object.entries(n.checkouts)){if(!dc(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 Hi(e,t,n=Date.now()){try{let r=Sv(e),o=new Date(n).toISOString(),i=!1;for(let c of t){if(!dc(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>pL)&&(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;iL(lL(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;cL(a,JSON.stringify(r),{mode:384}),aL(a,e)}catch{}}var vv,pL,xv,Ev=w(()=>{"use strict";zp();s(dL,"dirOf");s(uL,"within");s(Yp,"createCheckoutResolver");s(Xp,"dominantProjectKey");s(Zp,"relativizerFor");vv=90*24*60*60*1e3,pL=60*60*1e3,xv=/^[a-f0-9]{64}$/;s(Sv,"readMemory");s(Fi,"loadCheckoutMemory");s(Hi,"rememberCheckouts")});import{homedir as fL}from"node:os";import{isAbsolute as R5,join as mL}from"node:path";var hL,Qp=w(()=>{"use strict";hL=mL(fL(),".codex","sessions")});var Rv=w(()=>{"use strict";Qp()});var ef=w(()=>{"use strict"});var Cv=w(()=>{"use strict";ef()});import{createReadStream as wL,existsSync as kL}from"node:fs";import{createInterface as vL}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 EL(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
805
- `)}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 RL(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=EL(n);return r.includes(xL)?{holder:"human",genuine:!1}:n.some(i=>i.type==="tool_result"&&i.is_error===!0&&typeof i.content=="string"&&i.content.includes(SL))?{holder:"agent",genuine:!1}:n.some(i=>i.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function tf(e){let t=Nv("");if(!e||!kL(e))return t;let n=null,r=0,o=0,i=null,a="human",c=[];return await new Promise(l=>{let d=wL(e,{encoding:"utf-8"}),u=vL({input:d}),p=s(f=>{let m=f.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let b=g.sessionId??g.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||i!==null&&y<i)return;let _=RL(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 xL,SL,Av,Iv,Ov=w(()=>{"use strict";xL="[Request interrupted by user",SL="The user doesn't want to proceed with this tool use",Av=60,Iv=200;s(Tv,"asBlocks");s(EL,"textOf");s(Nv,"emptySpan");s(RL,"classify");s(tf,"analyzeSpan")});import{createReadStream as CL,existsSync as TL}from"node:fs";import{createInterface as AL}from"node:readline";function NL(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function uc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function OL(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(`
806
- `)}return""}async function nf(e,t={}){if(!e||!TL(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Mp(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),o=t.initialEffort??null,i=t.initialModes?{...t.initialModes}:Mp(),a=t.start??0;return await new Promise(c=>{let l=CL(e,{encoding:"utf-8",start:t.start??0}),d=AL({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),_=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=IL[m.attachment.type];b&&(i[NL(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=OL(m.message?.content),k=$i(b);k&&(o=k);let v={session_id:g,ts:y,text:b,effort_directive:k};n.push({kind:"user",...v});return}if(_==="assistant"){let b=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,v=typeof m.requestId=="string"&&m.requestId?m.requestId:null,E=k??v,S=E!==null&&r.has(E);E!==null&&!S&&r.add(E);let R={session_id:g,ts:y,model:m.message?.model??null,input_tokens:S?0:uc(b?.input_tokens),output_tokens:S?0:uc(b?.output_tokens),cache_read_input_tokens:S?0:uc(b?.cache_read_input_tokens),cache_creation_input_tokens:S?0:uc(b?.cache_creation_input_tokens),effort:o,isSidechain:m.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 IL,Dv=w(()=>{"use strict";nc();$p();IL={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(NL,"modeFlagKey");s(uc,"num");s(OL,"extractUserText");s(nf,"streamTranscript")});var Pv=w(()=>{"use strict"});import{homedir as DL}from"node:os";import{join as PL}from"node:path";function of(e){return e.replace(/[/.]/g,"-")}var ML,rf,Mv=w(()=>{"use strict";ML=DL(),rf=PL(ML,".claude","projects");s(of,"projectPathFromCwd")});var ur=w(()=>{"use strict";$p();nv();rv();fv();rc();mv();ic();Ev();Qp();Rv();zp();ef();Cv();Ov();Dv();nc();Pv();Mv()});import{mkdir as $L,readFile as LL,writeFile as jL,rename as FL}from"node:fs/promises";import{existsSync as Lv}from"node:fs";import{homedir as HL}from"node:os";import{join as jv}from"node:path";function $v(){return{config:null,sessions:{},pending_metrics:[]}}async function te(){if(!Lv(pc))return $v();try{let e=await LL(pc,"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)}
807
- `),$v()}}async function Rt(e){Lv(Ae)||await $L(Ae,{recursive:!0,mode:448});let t=`${pc}.${process.pid}.tmp`;await jL(t,JSON.stringify(e,null,2),{mode:384}),await FL(t,pc)}function sf(e){return e.thresholds??e.config?.thresholds??UL}var Ae,pc,UL,qe=w(()=>{"use strict";Ae=jv(HL(),".maind"),pc=jv(Ae,"state.json"),UL={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s($v,"emptyState");s(te,"loadState");s(Rt,"saveState");s(sf,"resolveThresholds")});import{execFileSync as BL}from"node:child_process";import{existsSync as KL}from"node:fs";import{join as Fv}from"node:path";function fc(e=GL()){return e?.checkout_memory===!0}function GL(){try{return ee()}catch{return null}}function WL(e){try{let t=BL("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?un(t):null}catch{return null}}function Hv(e,t){try{if(!(t.isCheckoutRoot??(o=>KL(Fv(o,".git"))))(e)||Fi(t.memoryPath).has(e))return!1;let r=(t.keyOf??WL)(e);return Hi(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var ho,mc=w(()=>{"use strict";ur();Ve();qe();me();ho=Fv(Ae,"checkout-roots.json");s(fc,"checkoutMemoryAllowed");s(GL,"safeReadConfig");s(WL,"originKey");s(Hv,"rememberEditCheckout")});import{rmSync as VL}from"node:fs";import*as Uv from"node:readline";async function af(e){let t=e.configPath??We(),n=e.memoryPath??ho;if(e.skip)return{target:gn,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:gn,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:gn,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};o=await(e.promptFn??zL)(e.out,qL)}else return{target:gn,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:gn,action:"merge",status:"would-merge",detail:t};let i={...r,checkout_memory:o};try{await B(t,JSON.stringify(i,null,2)+`
808
- `,384)}catch(a){return{target:gn,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}if(!o){let a=!1;try{VL(n,{force:!0}),a=!0}catch{a=!1}return{target:gn,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory off${a?`; ${n} removed if it existed`:`; could not remove ${n}`}`}}return{target:gn,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory on (${n}, local only; off: checkout_memory=false)`}}async function zL(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 gn,qL,Bv=w(()=>{"use strict";Ve();mc();se();gn="config:checkout_memory",qL=`
803
+ [y/N]: `;s(tv,"applyWorkingPathsConsent");s(S$,"promptYesNoDefaultNo")});function $p(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Lp=w(()=>{"use strict";s($p,"newModeState")});import{createReadStream as E$,existsSync as R$}from"node:fs";import{stat as C$}from"node:fs/promises";import{createInterface as T$}from"node:readline";async function jp(e){if(!e||!R$(e))return null;let t;try{t=await C$(e)}catch{return null}let n=new Set,r=0,o=0,i=0;return await new Promise(a=>{let c=E$(e,{encoding:"utf-8"}),l=T$({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 m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=m??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(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 rv=w(()=>{"use strict";s(jp,"summariseTranscript")});var ov=w(()=>{"use strict"});function $i(e){if(!e)return null;let t=null;for(let n of e.matchAll(I$)){let r=n[1].toLowerCase();A$.has(r)&&(t=r)}return t}var A$,I$,nc=w(()=>{"use strict";A$=new Set(["low","medium","high","xhigh","max"]),I$=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s($i,"detectEffortLevel")});function po(e){for(let t of iv)if(e.startsWith(t)){let n=e.slice(t.length);return n.length>0?n:null}return null}var iv,rc=w(()=>{"use strict";iv=["mcp__maind__","mcp__plugin_maind_maind__"];s(po,"maindToolName")});import{createReadStream as N$,existsSync as O$,readdirSync as D$}from"node:fs";import{basename as cv,dirname as P$,join as sv}from"node:path";import{createInterface as M$}from"node:readline";function dv(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!j$.test(n)||e.ids.includes(n)||e.ids.length>=lv||e.ids.push(n)}function F$(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=po(r.name);if(o===null||L$.has(o))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?dv(e,i.session_id):o==="announce_session"&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function H$(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 U$(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=H$(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}dv(e,i)}}function fo(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function K$(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=B$[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 oc(e){let t=cv(e).replace(/\.jsonl$/,""),n=sv(P$(e),t,"subagents"),r;try{r=D$(n)}catch{return[]}return r.filter(o=>o.endsWith(".jsonl")).sort().map(o=>sv(n,o))}async function av(e,t,n,r,o,i){O$(e)&&await new Promise(a=>{let c=N$(e,{encoding:"utf-8"}),l=M$({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"){U$(i,f.message.content);return}if(f.message?.role!=="assistant")return;F$(i,f.message.content);let m=typeof f.message.id=="string"&&f.message.id?f.message.id:null,g=typeof f.requestId=="string"&&f.requestId?f.requestId:null,y=m??g??`${e}#${d}`,_=K$(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 k=f.message.usage??{},v=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(v)?v:0,model:E||"<unknown>",synthetic:E===$$,input_tokens:fo(k.input_tokens),output_tokens:fo(k.output_tokens),cache_read_tokens:fo(k.cache_read_input_tokens),cache_creation_tokens:fo(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(fo(k.cache_creation?.ephemeral_1h_input_tokens),fo(k.cache_creation_input_tokens)),sidechain:f.isSidechain===!0,stream:t,edited_paths:_,cwd:typeof f.cwd=="string"&&f.cwd?f.cwd:null};r.set(y,S),o.push(S)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function Fp(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 Li(e){let t=new Set,n=new Map,r=[],o=e?oc(e):[],i={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:o,coordination_ids:[]};let a=[];await av(e,dr,t,n,a,i),Fp(a),r.push(...a);for(let c of o){let l=[],d=cv(c).replace(/\.jsonl$/,"");i.pendingAnnounce.clear(),await av(c,d,t,n,l,i),Fp(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:o,coordination_ids:i.ids}}var dr,$$,L$,j$,lv,B$,ic=w(()=>{"use strict";rc();dr="main",$$="<synthetic>",L$=new Set(["get_session_analysis","get_session_cost_context"]),j$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lv=32;s(dv,"addCoordinationId");s(F$,"noteCoordinationUse");s(H$,"resultText");s(U$,"noteAnnounceResult");B$={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(fo,"num");s(K$,"editedPathsOf");s(oc,"subagentFilesOf");s(av,"readStream");s(Fp,"fillTimestamps");s(Li,"collectTurns")});import{createReadStream as uv,existsSync as G$}from"node:fs";import{createInterface as pv}from"node:readline";function X$(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 sc(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Z$(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
804
+ `)}function Q$(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 eL(e,t,n){return W$.test(e)?{polarity:-1,magnitude:mo.rework,kind:"rework"}:n&&V$.test(e)?{polarity:-1,magnitude:mo.correction,kind:"correction"}:q$.test(e)?{polarity:1,magnitude:mo.acceptance,kind:"acceptance"}:t!==null&&Q$(t,e)?{polarity:-1,magnitude:mo.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function tL(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:fv,behaviour_measured:!0}}async function nL(e,t){for(let n of oc(e))await new Promise(r=>{let o=pv({input:uv(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 sc(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string")continue;let d=po(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 Hp(e,t={}){let n=tL("");if(!e||!G$(e))return n;let r=t.turns??(await Li(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let o=[],i=new Map,a=null,c=!1,l=null;await new Promise(m=>{let g=uv(e,{encoding:"utf-8"}),y=pv({input:g}),_=s(b=>{let k=b.trim();if(!k)return;let v;try{v=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let D=v.sessionId??v.session_id;typeof D=="string"&&D&&(n.session_id=D)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let E=v.message?.role,S=v.isSidechain===!0;if(E==="assistant")for(let D of sc(v.message?.content)){if(D.type!=="tool_use"||typeof D.name!="string")continue;let j=po(D.name);j!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[j]=(n.maind_tool_calls[j]??0)+1)}if(S)return;if(E==="assistant"){let D=sc(v.message?.content),j=!1;for(let At of D)At.type==="tool_use"&&(n.tool_calls++,j=!0,At.name==="AskUserQuestion"&&n.agent_questions++);c=j;return}if(E!=="user")return;let R=sc(v.message?.content),P=Z$(R);if(P.includes(z$)){n.interrupts++,o.push({polarity:-1,magnitude:mo.interrupt,kind:"interrupt"});return}if(R.some(D=>D.type==="tool_result"&&D.is_error===!0&&typeof D.content=="string"&&D.content.includes(J$))){n.tool_denials++,o.push({polarity:-1,magnitude:mo.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=$i(P);x&&(a=x);let T=eL(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",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await nL(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||X$(i,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...i.values()].sort((m,g)=>m.first_ts-g.first_ts||m.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return o.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*Y$+m.polarity*m.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=y,g>0&&o[g-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var fv,W$,V$,q$,z$,J$,Y$,mo,mv=w(()=>{"use strict";nc();rc();ic();fv="2026-10-01",W$=/(\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,V$=/(\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,q$=/(\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,z$="[Request interrupted by user",J$="The user doesn't want to proceed with this tool use",Y$=.7,mo={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(X$,"bumpModel");s(sc,"asBlocks");s(Z$,"textOf");s(Q$,"isRepeat");s(eL,"classifyGenuine");s(tL,"emptyAnalysis");s(nL,"tallySubagentMaindCalls");s(Hp,"analyzeSession")});function Up(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 Bp(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 Kp(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 hv=w(()=>{"use strict";s(Up,"parseIngestResponse");s(Bp,"describeSliceVerdict");s(Kp,"ingestBody")});import{isAbsolute as gv,relative as rL,resolve as yv,sep as _v}from"node:path";function bv(e){return e>cc[1]?"above_272k":e>cc[0]?"band_200k_272k":"standard"}function wv(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ac(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function ji(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=ac(d.from);typeof d.object_id!="string"||!Gp.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ac(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=ac(c.from);typeof c.path_prefix!="string"||l===null||o.push({path_prefix:c.path_prefix,from:l,to:ac(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"||!Gp.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"&&Gp.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 lc(e,t){if(!gv(e))return null;let n=rL(yv(t),yv(e));return!n||n==="."||n.startsWith("..")||gv(n)?null:_v==="/"?n:n.split(_v).join("/")}function iL(e,t){return t===""||e===t||e.startsWith(t+"/")}function Vp(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function kv(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function qp(e,t){for(let n of kv(t))if(iL(e,n.path_prefix))return n.object_id;return null}function sL(e,t){for(let n of kv(t))if(Vp(e,n.path_prefix))return n.object_id;return null}function Wp(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=>qp(c,i)).filter(c=>c!==null);if(r&&o>0){let c=r.leases.filter(u=>Wp(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=>Wp(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=>Wp(o,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>Vp(f.path_prefix,u))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=sL(f.path_prefix,i);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function zp(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?_=>lc(_,o):null),a=s(_=>{if(!i)return[];let b=[];for(let k of _.edited_paths){let v=i(k);v!==null&&!b.includes(v)&&b.push(v)}return b},"relOf"),c=s(_=>{for(let b of _){let k=qp(b,r);if(k)return{object_id:k,rel:b}}return null},"firstAnchoredEdit"),l=new Map;for(let _ of e){let b=l.get(_.stream)??[];b.push(_),l.set(_.stream,b)}let d=[...l.entries()].sort(([_],[b])=>_===dr?-1:b===dr?1:0),u=[],p=s(_=>{let b=null;for(let k of u){if(k.ts>_&&_>0)break;b=k.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let k=b.map((E,S)=>({t:E,i:S,rels:a(E)})).sort((E,S)=>E.t.ts-S.t.ts||E.i-S.i),v=null;for(let E of k){let S=c(E.rels);if(S){v=S;break}}!v&&_!==dr&&k.length&&(v=p(k[0].t.ts));for(let E of k){let S=c(E.rels);S&&(v=S),_===dr&&u.push({ts:E.t.ts,seg:v});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,v,t),x=bv(R.input_tokens+R.cache_read_tokens+R.cache_creation_tokens),T=wv(R.model),D=`${K.object_id??""}|${K.source}|${T}|${x}`,j=f.get(D);j||(j={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,j)),j.input_tokens+=R.input_tokens,j.output_tokens+=R.output_tokens,j.cache_read_tokens+=R.cache_read_tokens,j.cache_creation_tokens+=R.cache_creation_tokens,j.cache_creation_1h_tokens+=R.cache_creation_1h_tokens,j.turns+=1,R.ts>0&&((j.firstMs===0||R.ts<j.firstMs)&&(j.firstMs=R.ts),R.ts>j.lastMs&&(j.lastMs=R.ts))}}let m=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:k,...v}=_;v.first_ts=new Date(b>0?b:m).toISOString(),v.last_ts=new Date(k>0?k:m).toISOString(),g.push(v)}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 cc,oL,Gp,Jp=w(()=>{"use strict";ic();cc=[2e5,272e3];s(bv,"contextTierOf");s(wv,"normalizeModelId");oL=cc[0],Gp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(ac,"msOf");s(ji,"parseCostContext");s(lc,"toRepoRelative");s(iL,"underPrefix");s(Vp,"prefixesOverlap");s(kv,"sortedAnchors");s(qp,"anchorFor");s(sL,"bestAnchorOverlapping");s(Wp,"inWindow");s(vv,"assignTurn");s(zp,"sliceSession")});import{mkdirSync as aL,readFileSync as cL,renameSync as lL,writeFileSync as dL}from"node:fs";import{dirname as uL,isAbsolute as dc,sep as Yp}from"node:path";function pL(e){let t=e.split(Yp).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function fL(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function Xp(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])=>dc(u)).sort((u,p)=>p[0].length-u[0].length),c=new Map,l=s(u=>{if(!e.isDir)return null;let p=c.get(u);if(p!==void 0)return p;let f=d(u);return c.set(u,f),f},"byConvention"),d=s(u=>{if(!e.isDir)return null;let p=u.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let g=p.slice(0,f-1).join("/")||"/",y=p[f-1];for(let _=y.lastIndexOf("-");_>0;_=y.lastIndexOf("-",_-1)){let b=`${g==="/"?"":g}/${y.slice(0,_)}`;if(e.isDir(b)&&o(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!dc(u))return null;let p=u.split(Yp).join("/"),f=pL(p),m=o(f);if(m){let g=n(m);return i.set(m,g),{root:m,key:g}}for(let[g,y]of a)if(!(!fL(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 Zp(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 Qp(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:lc(n.split(Yp).join("/"),r.root)}}function Ev(e){try{let t=JSON.parse(cL(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 Fi(e){let t=new Map,n=Ev(e);for(let[r,o]of Object.entries(n.checkouts)){if(!dc(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&Sv.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}function Hi(e,t,n=Date.now()){try{let r=Ev(e),o=new Date(n).toISOString(),i=!1;for(let c of t){if(!dc(c.root))continue;let l=c.key&&Sv.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>mL)&&(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>xv)&&(delete r.checkouts[c],i=!0)}if(!i)return;aL(uL(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;dL(a,JSON.stringify(r),{mode:384}),lL(a,e)}catch{}}var xv,mL,Sv,Rv=w(()=>{"use strict";Jp();s(pL,"dirOf");s(fL,"within");s(Xp,"createCheckoutResolver");s(Zp,"dominantProjectKey");s(Qp,"relativizerFor");xv=90*24*60*60*1e3,mL=60*60*1e3,Sv=/^[a-f0-9]{64}$/;s(Ev,"readMemory");s(Fi,"loadCheckoutMemory");s(Hi,"rememberCheckouts")});import{homedir as hL}from"node:os";import{isAbsolute as T5,join as gL}from"node:path";var yL,ef=w(()=>{"use strict";yL=gL(hL(),".codex","sessions")});var Cv=w(()=>{"use strict";ef()});var tf=w(()=>{"use strict"});var Tv=w(()=>{"use strict";tf()});import{createReadStream as vL,existsSync as xL}from"node:fs";import{createInterface as SL}from"node:readline";function Av(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function CL(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
805
+ `)}function Ov(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 TL(e){let t=e.message?.role;if(t==="assistant")return{holder:Av(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Av(e.message?.content),r=CL(n);return r.includes(EL)?{holder:"human",genuine:!1}:n.some(i=>i.type==="tool_result"&&i.is_error===!0&&typeof i.content=="string"&&i.content.includes(RL))?{holder:"agent",genuine:!1}:n.some(i=>i.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function nf(e){let t=Ov("");if(!e||!xL(e))return t;let n=null,r=0,o=0,i=null,a="human",c=[];return await new Promise(l=>{let d=vL(e,{encoding:"utf-8"}),u=SL({input:d}),p=s(f=>{let m=f.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let b=g.sessionId??g.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||i!==null&&y<i)return;let _=TL(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>=Iv*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<Nv&&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 EL,RL,Iv,Nv,Dv=w(()=>{"use strict";EL="[Request interrupted by user",RL="The user doesn't want to proceed with this tool use",Iv=60,Nv=200;s(Av,"asBlocks");s(CL,"textOf");s(Ov,"emptySpan");s(TL,"classify");s(nf,"analyzeSpan")});import{createReadStream as AL,existsSync as IL}from"node:fs";import{createInterface as NL}from"node:readline";function DL(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function uc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function PL(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(`
806
+ `)}return""}async function rf(e,t={}){if(!e||!IL(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:$p(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),o=t.initialEffort??null,i=t.initialModes?{...t.initialModes}:$p(),a=t.start??0;return await new Promise(c=>{let l=AL(e,{encoding:"utf-8",start:t.start??0}),d=NL({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),_=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=OL[m.attachment.type];b&&(i[DL(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=PL(m.message?.content),k=$i(b);k&&(o=k);let v={session_id:g,ts:y,text:b,effort_directive:k};n.push({kind:"user",...v});return}if(_==="assistant"){let b=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,v=typeof m.requestId=="string"&&m.requestId?m.requestId:null,E=k??v,S=E!==null&&r.has(E);E!==null&&!S&&r.add(E);let R={session_id:g,ts:y,model:m.message?.model??null,input_tokens:S?0:uc(b?.input_tokens),output_tokens:S?0:uc(b?.output_tokens),cache_read_input_tokens:S?0:uc(b?.cache_read_input_tokens),cache_creation_input_tokens:S?0:uc(b?.cache_creation_input_tokens),effort:o,isSidechain:m.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 OL,Pv=w(()=>{"use strict";nc();Lp();OL={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(DL,"modeFlagKey");s(uc,"num");s(PL,"extractUserText");s(rf,"streamTranscript")});var Mv=w(()=>{"use strict"});import{homedir as ML}from"node:os";import{join as $L}from"node:path";function sf(e){return e.replace(/[/.]/g,"-")}var LL,of,$v=w(()=>{"use strict";LL=ML(),of=$L(LL,".claude","projects");s(sf,"projectPathFromCwd")});var ur=w(()=>{"use strict";Lp();rv();ov();mv();rc();hv();ic();Rv();ef();Cv();Jp();tf();Tv();Dv();Pv();nc();Mv();$v()});import{mkdir as jL,readFile as FL,writeFile as HL,rename as UL}from"node:fs/promises";import{existsSync as jv}from"node:fs";import{homedir as BL}from"node:os";import{join as Fv}from"node:path";function Lv(){return{config:null,sessions:{},pending_metrics:[]}}async function ne(){if(!jv(pc))return Lv();try{let e=await FL(pc,"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)}
807
+ `),Lv()}}async function Rt(e){jv(Ae)||await jL(Ae,{recursive:!0,mode:448});let t=`${pc}.${process.pid}.tmp`;await HL(t,JSON.stringify(e,null,2),{mode:384}),await UL(t,pc)}function af(e){return e.thresholds??e.config?.thresholds??KL}var Ae,pc,KL,qe=w(()=>{"use strict";Ae=Fv(BL(),".maind"),pc=Fv(Ae,"state.json"),KL={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(Lv,"emptyState");s(ne,"loadState");s(Rt,"saveState");s(af,"resolveThresholds")});import{execFileSync as GL}from"node:child_process";import{existsSync as WL}from"node:fs";import{join as Hv}from"node:path";function fc(e=VL()){return e?.checkout_memory===!0}function VL(){try{return te()}catch{return null}}function qL(e){try{let t=GL("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?un(t):null}catch{return null}}function Uv(e,t){try{if(!(t.isCheckoutRoot??(o=>WL(Hv(o,".git"))))(e)||Fi(t.memoryPath).has(e))return!1;let r=(t.keyOf??qL)(e);return Hi(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var ho,mc=w(()=>{"use strict";ur();Ve();qe();me();ho=Hv(Ae,"checkout-roots.json");s(fc,"checkoutMemoryAllowed");s(VL,"safeReadConfig");s(qL,"originKey");s(Uv,"rememberEditCheckout")});import{rmSync as zL}from"node:fs";import*as Bv from"node:readline";async function cf(e){let t=e.configPath??We(),n=e.memoryPath??ho;if(e.skip)return{target:gn,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:gn,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:gn,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};o=await(e.promptFn??YL)(e.out,JL)}else return{target:gn,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:gn,action:"merge",status:"would-merge",detail:t};let i={...r,checkout_memory:o};try{await B(t,JSON.stringify(i,null,2)+`
808
+ `,384)}catch(a){return{target:gn,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}if(!o){let a=!1;try{zL(n,{force:!0}),a=!0}catch{a=!1}return{target:gn,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory off${a?`; ${n} removed if it existed`:`; could not remove ${n}`}`}}return{target:gn,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory on (${n}, local only; off: checkout_memory=false)`}}async function YL(e,t){e.write(t);let n=Bv.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 gn,JL,Kv=w(()=>{"use strict";Ve();mc();ae();gn="config:checkout_memory",JL=`
809
809
  Remember the repositories you edit in (checkout memory)?
810
810
  With this ON, the repo-health hook (before an edit) and the Stop hook (after a
811
811
  turn) record the ROOT directory of each git checkout you edit in, plus its
@@ -816,26 +816,26 @@ never file names, never contents. The file never leaves this machine; entries
816
816
  not seen for 90 days are pruned. Without it, a deleted worktree is still
817
817
  recognised when it follows the \`maind feature start\` naming (<repo>-<name>).
818
818
  Off later: {"checkout_memory": false} in the bridge config.
819
- [Y/n]: `;s(af,"applyCheckoutMemoryConsent");s(zL,"promptYesNoDefaultYes")});import{existsSync as JL}from"node:fs";import{dirname as YL,join as Kv}from"node:path";function _n(e,t=JL){let n=e;for(;;){if(t(Kv(n,".git")))return n;let r=YL(n);if(r===n)return null;n=r}}var yn,hc=w(()=>{"use strict";yn=Kv(".maind","code-index.sqlite");s(_n,"findRepoRoot")});import{existsSync as XL}from"node:fs";import{join as ZL}from"node:path";function QL(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=XL){if(!QL(t))return null;let r=_n(e,n)??e;return n(ZL(r,yn))?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";hc();s(QL,"readHookWired");s(Gv,"contextIndexRow")});import*as df from"node:path";import*as qv from"node:readline";function zv(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}function pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nj(e,t,n){if(!pr(e)||!pr(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let o of r)if(pr(o)&&typeof o.command=="string"&&o.command.includes(n))return o.command;return null}async function rj(e,t){let n=df.join(e.homeDir,ej),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: ${lf(g)}`)}let a={},c=i===null||i.trim().length===0;if(!c){let g;try{g=JSON.parse(i)}catch(_){return o("failed",`parse: ${lf(_)} \u2014 ${n} left untouched`)}if(!pr(g))return o("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==cf)return o("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${cf}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!pr(a.hooks))return o("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=pr(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??ve({entryPath:ie(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=Qe(l),u=nj(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return o("skipped",pn(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??oj)(e.out,`
819
+ [Y/n]: `;s(cf,"applyCheckoutMemoryConsent");s(YL,"promptYesNoDefaultYes")});import{existsSync as XL}from"node:fs";import{dirname as ZL,join as Gv}from"node:path";function _n(e,t=XL){let n=e;for(;;){if(t(Gv(n,".git")))return n;let r=ZL(n);if(r===n)return null;n=r}}var yn,hc=w(()=>{"use strict";yn=Gv(".maind","code-index.sqlite");s(_n,"findRepoRoot")});import{existsSync as QL}from"node:fs";import{join as ej}from"node:path";function tj(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 Wv(e,t,n=QL){if(!tj(t))return null;let r=_n(e,n)??e;return n(ej(r,yn))?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 Vv=w(()=>{"use strict";hc();s(tj,"readHookWired");s(Wv,"contextIndexRow")});import*as uf from"node:path";import*as zv from"node:readline";function Jv(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}function pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oj(e,t,n){if(!pr(e)||!pr(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let o of r)if(pr(o)&&typeof o.command=="string"&&o.command.includes(n))return o.command;return null}async function ij(e,t){let n=uf.join(e.homeDir,nj),r=Jv(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: ${df(g)}`)}let a={},c=i===null||i.trim().length===0;if(!c){let g;try{g=JSON.parse(i)}catch(_){return o("failed",`parse: ${df(_)} \u2014 ${n} left untouched`)}if(!pr(g))return o("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==lf)return o("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${lf}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!pr(a.hooks))return o("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=pr(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??ve({entryPath:se(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=Qe(l),u=oj(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return o("skipped",pn(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??sj)(e.out,`
820
820
  Add a ${t.event} hook to ${n}?
821
821
  ${t.consentDescription}
822
- [Y/n]: `))return o("skipped","user declined","skip")}let p=pr(a.hooks)?a.hooks:{},f=Array.isArray(p[t.event])?p[t.event]:[],m={...a,version:a.version??cf,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 B(n,JSON.stringify(m,null,2)+`
823
- `)}catch(g){return o("failed",`write: ${lf(g)}`)}return o(c?"created":"merged",n,c?"write":"merge")}async function uf(e){if(!e.explicit&&!e.skip&&!dk(e.presence.ctx,e.presence.probe)){let n=Ut(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 rj(e,n));return t}async function oj(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 lf(e){return e instanceof Error?e.message:String(e)}var ej,cf,tj,Vv,Jv=w(()=>{"use strict";se();St();et();io();ej=df.join(".cursor","hooks.json"),cf=1,tj="on-cursor-session-start",Vv=[{event:"sessionStart",subcommand:tj,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(pr,"isObject");s(nj,"findCursorHookCommand");s(rj,"mergeCursorHook");s(uf,"mergeCursorHooks");s(oj,"promptYesNo");s(lf,"errMessage")});import{existsSync as ij,readdirSync as sj,readFileSync as aj}from"node:fs";import*as bn from"node:path";function cj(e){let t=e[Xv]?.trim();return t!==void 0&&t.length>0?t:null}function lj(e,t){let n=t.CLAUDE_CONFIG_DIR?.trim();return n&&bn.isAbsolute(n)?n:bn.join(e,".claude")}function dj(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[Ui];return typeof r=="boolean"?r:void 0}catch{return}}function $e(e){let t=dj(e.platform),n=[bn.join(t,"managed-settings.json")],r=e.list(bn.join(t,"managed-settings.d"));if(r!==null)for(let a of[...r].sort())a.startsWith(".")||!a.endsWith(".json")||n.push(bn.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=bn.join(lj(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&&cj(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 gc(e){return`Claude Code hooks: provided by the maind plugin (${Ui} is enabled${Zv(e)}) \u2014 none written to settings.json`}function Qv(e){return`Claude Code MCP server: provided by the maind plugin (${Ui} is enabled${Zv(e)}) \u2014 nothing written to ~/.claude.json, which would start a second maind server`}function Le(e,t,n){return{homeDir:e,env:t,platform:n,read:s(r=>{try{return ij(r)?aj(r,"utf8"):null}catch{return null}},"read"),list:s(r=>{try{return sj(r)}catch{return null}},"list")}}var Ui,Xv,go=w(()=>{"use strict";Ui="maind@maind",Xv="MAIND_CLAUDE_PLUGIN";s(cj,"pluginEnvVersion");s(lj,"claudeConfigDir");s(dj,"managedSettingsDir");s(Yv,"pluginEntryIn");s($e,"maindPluginState");s(Zv,"where");s(gc,"pluginRowDetail");s(Qv,"pluginMcpRowDetail");s(Le,"fsPluginProbe")});import*as wn from"node:path";import*as tx from"node:readline";function hj(e,t){let n=wn.relative(t,e),r=n!==""&&!n.startsWith("..")&&!wn.isAbsolute(n)?`~/${n.split(wn.sep).join("/")}`:e;return`hook(${Y}):${r}`}async function pf(e){let t=xi(e.presence.ctx),n=hj(t,e.homeDir),r=s((f,m,g="merge")=>({target:n,action:g,status:f,detail:m}),"row");if(e.skip)return r("skipped","--no-hook","skip");if(e.skipCodex)return r("skipped","--skip-codex","skip");if(!e.explicit&&!De(oo(e.presence.ctx),e.presence.probe))return r("skipped",oo(e.presence.ctx).skipDetail,"skip");let o;try{o=await q(t)}catch(f){return r("failed",`read: ${ex(f)}`)}let i=o===null,a=e.launch??ve({entryPath:ie(),nodePath:process.execPath,extraArgs:[Y,uj],isElectron:process.versions.electron!==void 0}),c=Qe(a),l=Ok(o??"",{command:c,timeout:pj,additionalContextLimit:fj},Y);if(l.kind==="refuse")return{...r("failed",`${t} ${l.reason} \u2014 left untouched`),manual:l.manual};if(l.kind==="off")return r("skipped",`hooks are switched off in ${t} ([features] ${l.key} = false) \u2014 left as it is`,"skip");let d=s(f=>{let m=`Codex's SessionStart hook already runs maind ${Y}`;return r("skipped",f!==null&&pn(f)?`${m}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${c}`:m,"skip")},"alreadyWired");if(l.kind==="wired")return d(l.command);if(l.kind==="unchanged")return d(null);let u=await gj(e.presence.ctx);if(u!==null)return d(u);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(i?"would-create":"would-merge",`${t} (would prompt for consent in real run)`);if(!await(e.prompt??yj)(e.out,`
822
+ [Y/n]: `))return o("skipped","user declined","skip")}let p=pr(a.hooks)?a.hooks:{},f=Array.isArray(p[t.event])?p[t.event]:[],m={...a,version:a.version??lf,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 B(n,JSON.stringify(m,null,2)+`
823
+ `)}catch(g){return o("failed",`write: ${df(g)}`)}return o(c?"created":"merged",n,c?"write":"merge")}async function pf(e){if(!e.explicit&&!e.skip&&!uk(e.presence.ctx,e.presence.probe)){let n=Ut(e.presence.ctx).skipDetail;return qv.map(r=>({target:Jv(r),action:"skip",status:"skipped",detail:n}))}let t=[];for(let n of qv)t.push(await ij(e,n));return t}async function sj(e,t){e.write(t);let n=zv.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 df(e){return e instanceof Error?e.message:String(e)}var nj,lf,rj,qv,Yv=w(()=>{"use strict";ae();St();et();io();nj=uf.join(".cursor","hooks.json"),lf=1,rj="on-cursor-session-start",qv=[{event:"sessionStart",subcommand:rj,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(Jv,"targetKeyFor");s(pr,"isObject");s(oj,"findCursorHookCommand");s(ij,"mergeCursorHook");s(pf,"mergeCursorHooks");s(sj,"promptYesNo");s(df,"errMessage")});import{existsSync as aj,readdirSync as cj,readFileSync as lj}from"node:fs";import*as bn from"node:path";function dj(e){let t=e[Zv]?.trim();return t!==void 0&&t.length>0?t:null}function uj(e,t){let n=t.CLAUDE_CONFIG_DIR?.trim();return n&&bn.isAbsolute(n)?n:bn.join(e,".claude")}function pj(e){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}function Xv(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[Ui];return typeof r=="boolean"?r:void 0}catch{return}}function $e(e){let t=pj(e.platform),n=[bn.join(t,"managed-settings.json")],r=e.list(bn.join(t,"managed-settings.d"));if(r!==null)for(let a of[...r].sort())a.startsWith(".")||!a.endsWith(".json")||n.push(bn.join(t,"managed-settings.d",a));let o=null;for(let a of n){let c=Xv(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=bn.join(uj(e.homeDir,e.env),"settings.json"),c=Xv(e.read(a));return c!==void 0?{enabled:c,source:"user",file:a}:{enabled:!1,source:null,file:null}})();return!i.enabled&&dj(e.env)!==null?{enabled:!0,source:"env",file:null}:i}function Qv(e){return e.source==="env"?` (this process was started by the plugin, ${Zv})`:e.file?` in ${e.file}`:""}function gc(e){return`Claude Code hooks: provided by the maind plugin (${Ui} is enabled${Qv(e)}) \u2014 none written to settings.json`}function ex(e){return`Claude Code MCP server: provided by the maind plugin (${Ui} is enabled${Qv(e)}) \u2014 nothing written to ~/.claude.json, which would start a second maind server`}function Le(e,t,n){return{homeDir:e,env:t,platform:n,read:s(r=>{try{return aj(r)?lj(r,"utf8"):null}catch{return null}},"read"),list:s(r=>{try{return cj(r)}catch{return null}},"list")}}var Ui,Zv,go=w(()=>{"use strict";Ui="maind@maind",Zv="MAIND_CLAUDE_PLUGIN";s(dj,"pluginEnvVersion");s(uj,"claudeConfigDir");s(pj,"managedSettingsDir");s(Xv,"pluginEntryIn");s($e,"maindPluginState");s(Qv,"where");s(gc,"pluginRowDetail");s(ex,"pluginMcpRowDetail");s(Le,"fsPluginProbe")});import*as wn from"node:path";import*as nx from"node:readline";function yj(e,t){let n=wn.relative(t,e),r=n!==""&&!n.startsWith("..")&&!wn.isAbsolute(n)?`~/${n.split(wn.sep).join("/")}`:e;return`hook(${Y}):${r}`}async function ff(e){let t=xi(e.presence.ctx),n=yj(t,e.homeDir),r=s((f,m,g="merge")=>({target:n,action:g,status:f,detail:m}),"row");if(e.skip)return r("skipped","--no-hook","skip");if(e.skipCodex)return r("skipped","--skip-codex","skip");if(!e.explicit&&!De(oo(e.presence.ctx),e.presence.probe))return r("skipped",oo(e.presence.ctx).skipDetail,"skip");let o;try{o=await q(t)}catch(f){return r("failed",`read: ${tx(f)}`)}let i=o===null,a=e.launch??ve({entryPath:se(),nodePath:process.execPath,extraArgs:[Y,fj],isElectron:process.versions.electron!==void 0}),c=Qe(a),l=Dk(o??"",{command:c,timeout:mj,additionalContextLimit:hj},Y);if(l.kind==="refuse")return{...r("failed",`${t} ${l.reason} \u2014 left untouched`),manual:l.manual};if(l.kind==="off")return r("skipped",`hooks are switched off in ${t} ([features] ${l.key} = false) \u2014 left as it is`,"skip");let d=s(f=>{let m=`Codex's SessionStart hook already runs maind ${Y}`;return r("skipped",f!==null&&pn(f)?`${m}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${c}`:m,"skip")},"alreadyWired");if(l.kind==="wired")return d(l.command);if(l.kind==="unchanged")return d(null);let u=await _j(e.presence.ctx);if(u!==null)return d(u);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(i?"would-create":"would-merge",`${t} (would prompt for consent in real run)`);if(!await(e.prompt??bj)(e.out,`
824
824
  Add a SessionStart hook to ${t}?
825
- ${mj}
826
- [Y/n]: `))return r("skipped","user declined","skip")}let p="Codex runs it after you trust it once: /hooks in Codex";if(e.dryRun)return r(i?"would-create":"would-merge",`${t} \u2014 ${p}`,i?"write":"merge");try{if(!await Ma(t,o,l.next))return r("failed",`${t} changed while install ran \u2014 left untouched; run install again`)}catch(f){return r("failed",`write: ${ex(f)}`)}return r(i?"created":"merged",`${t} \u2014 ${p}`,i?"write":"merge")}async function gj(e){try{let t=await q(wn.join(ro(e),"hooks.json"));if(t===null)return null;let n=JSON.parse(t);return ao(n,Y)}catch{return null}}async function yj(e,t){e.write(t);let n=tx.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 ex(e){return e instanceof Error?e.message:String(e)}var uj,pj,fj,mj,nx=w(()=>{"use strict";se();St();et();co();io();he();uj="--host=codex",pj=10,fj=4e3,mj="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. Everything else in config.toml stays as it is, comments and layout included. Codex runs a new hook only after you trust it: open /hooks in Codex once.";s(hj,"codexHookTarget");s(pf,"mergeCodexHook");s(gj,"hooksJsonCommand");s(yj,"promptYesNo");s(ex,"errMessage")});import{createHash as _j}from"node:crypto";import*as nt from"node:path";import*as ox from"node:readline";function wj(e){return nt.join(e.homeDir,".copilot","instructions","maind.instructions.md")}function kj(e,t){let n=(e.documentsDirs&&e.documentsDirs.length>0?e.documentsDirs:[nt.join(e.homeDir,"Documents")]).map(r=>nt.join(r,"Cline","Rules"));return n.find(r=>t.exists(r))??n[0]}function vj(e){return nt.join(Na(e),"rules","maind.md")}function fr(e,t){return[{id:"copilot",family:"copilot",label:"GitHub Copilot user instructions",path:wj(e),presence:ap(e),frontmatter:["name: maind",`description: ${rx}`,'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:nt.join(kj(e,t),"maind.md"),presence:ip(e),frontmatter:null,loads:"Cline loads as an always-active global rule in every workspace"},{id:"continue",family:"continue",label:"Continue global rule",path:vj(e),presence:sp(e),frontmatter:["name: maind",`description: ${rx}`,"alwaysApply: true"],loads:"Continue includes in every workspace (`alwaysApply: true`)"}]}function sx(e){return e==="copilot"||e==="cline"||e==="continue"?e:null}function xj(e,t){return`rules(${e.id}):${Sj(e.path,t)}`}function Sj(e,t){let n=nt.relative(t,e);return n!==""&&!n.startsWith("..")&&!nt.isAbsolute(n)?`~/${n.split(nt.sep).join("/")}`:e}function ff(e,t,n){let r=[];e.frontmatter!==null&&r.push("---",...e.frontmatter,"---"),r.push(bj,"",Et.replace(/\r\n/g,`
825
+ ${gj}
826
+ [Y/n]: `))return r("skipped","user declined","skip")}let p="Codex runs it after you trust it once: /hooks in Codex";if(e.dryRun)return r(i?"would-create":"would-merge",`${t} \u2014 ${p}`,i?"write":"merge");try{if(!await Ma(t,o,l.next))return r("failed",`${t} changed while install ran \u2014 left untouched; run install again`)}catch(f){return r("failed",`write: ${tx(f)}`)}return r(i?"created":"merged",`${t} \u2014 ${p}`,i?"write":"merge")}async function _j(e){try{let t=await q(wn.join(ro(e),"hooks.json"));if(t===null)return null;let n=JSON.parse(t);return ao(n,Y)}catch{return null}}async function bj(e,t){e.write(t);let n=nx.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 tx(e){return e instanceof Error?e.message:String(e)}var fj,mj,hj,gj,rx=w(()=>{"use strict";ae();St();et();co();io();he();fj="--host=codex",mj=10,hj=4e3,gj="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. Everything else in config.toml stays as it is, comments and layout included. Codex runs a new hook only after you trust it: open /hooks in Codex once.";s(yj,"codexHookTarget");s(ff,"mergeCodexHook");s(_j,"hooksJsonCommand");s(bj,"promptYesNo");s(tx,"errMessage")});import{createHash as wj}from"node:crypto";import*as nt from"node:path";import*as ix from"node:readline";function vj(e){return nt.join(e.homeDir,".copilot","instructions","maind.instructions.md")}function xj(e,t){let n=(e.documentsDirs&&e.documentsDirs.length>0?e.documentsDirs:[nt.join(e.homeDir,"Documents")]).map(r=>nt.join(r,"Cline","Rules"));return n.find(r=>t.exists(r))??n[0]}function Sj(e){return nt.join(Na(e),"rules","maind.md")}function fr(e,t){return[{id:"copilot",family:"copilot",label:"GitHub Copilot user instructions",path:vj(e),presence:ap(e),frontmatter:["name: maind",`description: ${ox}`,'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:nt.join(xj(e,t),"maind.md"),presence:ip(e),frontmatter:null,loads:"Cline loads as an always-active global rule in every workspace"},{id:"continue",family:"continue",label:"Continue global rule",path:Sj(e),presence:sp(e),frontmatter:["name: maind",`description: ${ox}`,"alwaysApply: true"],loads:"Continue includes in every workspace (`alwaysApply: true`)"}]}function ax(e){return e==="copilot"||e==="cline"||e==="continue"?e:null}function Ej(e,t){return`rules(${e.id}):${Rj(e.path,t)}`}function Rj(e,t){let n=nt.relative(t,e);return n!==""&&!n.startsWith("..")&&!nt.isAbsolute(n)?`~/${n.split(nt.sep).join("/")}`:e}function mf(e,t,n){let r=[];e.frontmatter!==null&&r.push("---",...e.frontmatter,"---"),r.push(kj,"",Et.replace(/\r\n/g,`
827
827
  `).trimEnd(),"","### Project conventions","");let o=t.repo??"no repository (organization- and user-wide only)",i=(t.conventions??"").replace(/\r\n/g,`
828
- `).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 ${Ej(n.nowMs)} (mcp-bridge ${n.bridgeVersion}).`,""),r.push(Cp(i,Rp).text)),r.join(`
828
+ `).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 ${Cj(n.nowMs)} (mcp-bridge ${n.bridgeVersion}).`,""),r.push(Tp(i,Cp).text)),r.join(`
829
829
  `)+`
830
- `}function Ej(e){return new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}function _o(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(ix)}function yo(e){return e.replace(/\r\n/g,`
830
+ `}function Cj(e){return new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}function _o(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(sx)}function yo(e){return e.replace(/\r\n/g,`
831
831
  `).split(`
832
832
  `).map(t=>t.replace(/^(Conventions for .+?), refreshed .*$/,"$1")).join(`
833
- `)}function Bi(e){return _j("sha256").update(yo(e)).digest("hex")}function Rj(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 Cj(e,t){let n=xj(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&&!De(t.presence,e.probe))return r("skipped",t.presence.skipDetail,"skip");try{let o=await q(t.path);if(o!==null&&!_o(o))return r("skipped",`${t.path} is yours (no maind marker) \u2014 left as it is`,"skip");let i=await e.content(),a=ff(t,i,{nowMs:e.nowMs??Date.now(),bridgeVersion:e.bridgeVersion??H});if(o!==null)return yo(o)===yo(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 B(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??Tj)(e.out,`
833
+ `)}function Bi(e){return wj("sha256").update(yo(e)).digest("hex")}function Tj(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 Aj(e,t){let n=Ej(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&&!De(t.presence,e.probe))return r("skipped",t.presence.skipDetail,"skip");try{let o=await q(t.path);if(o!==null&&!_o(o))return r("skipped",`${t.path} is yours (no maind marker) \u2014 left as it is`,"skip");let i=await e.content(),a=mf(t,i,{nowMs:e.nowMs??Date.now(),bridgeVersion:e.bridgeVersion??H});if(o!==null)return yo(o)===yo(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 B(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??Ij)(e.out,`
834
834
  Write the ${t.label} ${t.path}?
835
- ${Rj(t)}
836
- [Y/n]: `))return r("skipped","user declined","skip")}return e.dryRun?r("would-create",t.path):(await B(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 mf(e,t){let n=[];for(let r of t)n.push(await Cj(e,r));return n}async function Tj(e,t){e.write(t);let n=ox.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 ix,bj,rx,yc=w(()=>{"use strict";qa();Ue();lo();se();et();et();io();ix="<!-- maind:rules v1",bj=`${ix} \xB7 written by maind-mcp-bridge (ADR-364): the bridge rewrites this file when it refreshes \u2014 do not edit by hand -->`;s(wj,"copilotInstructionsPath");s(kj,"clineRulesDir");s(vj,"continueRulesPath");rx="MAIND consultation triggers and the project conventions of the repository you work in";s(fr,"ruleChannels");s(sx,"ruleChannelIdForFamily");s(xj,"rulesTargetKey");s(Sj,"tildify");s(ff,"renderRulesFile");s(Ej,"stamp");s(_o,"isOurRulesFile");s(yo,"canonicalRulesContent");s(Bi,"rulesContentHash");s(Rj,"ruleConsentDescription");s(Cj,"mergeRuleChannel");s(mf,"mergeRuleChannels");s(Tj,"promptYesNo")});async function ax(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 cx=w(()=>{"use strict";s(ax,"exchangeOneClickToken")});async function ux(e){let t="browser-pair";if(e.token!==null)try{let i=Aj(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(wi(),or(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:lx(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=Ea(e.bridgeVersion),a=await ax({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:Ow(),clientMeta:{...i}});if(a.ok)return wi(),or(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,dx(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
837
- `)}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 no(e.bridgeVersion,dx(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:lx(i)}}}}function Aj(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 lx(e){return e instanceof Error?e.message:String(e)}function dx(e){return e.out??process.stdout}var px=w(()=>{"use strict";tp();oe();cx();s(ux,"pairOrUseToken");s(Aj,"validateTokenShape");s(lx,"errMessage");s(dx,"out")});async function fx(e){if(!e.enabled||e.apiKey===null)return;let t=eo(Ij),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Dj(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Oj(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,o=setTimeout(()=>r.abort(),Nj);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 Oj(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 Dj(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}var Ij,Nj,mx=w(()=>{"use strict";to();Ij="install-completed",Nj=3e3;s(fx,"postInstallTelemetry");s(Oj,"countStatuses");s(Dj,"parseNodeMajor")});function _c(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function vn(e){return e+1}function bc(e){return(e.text.split(`
838
- `,1)[0]??"").trim().slice(0,200)}function Pj(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 Mj(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let o=Pj(r.childForFieldName("function"));o&&n.add(o)}return[...n]}function hf(e,t,n,r){for(let o of Mj(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:o})}function Ki(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let 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 kn(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 kn(t.childForFieldName("name"));case"parenthesized_type":return kn(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?kn(n[0]):"#"}default:return"#"}}function Lj(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function gf(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 Gi(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=kn(n.childForFieldName("type"))??gf(o)??(Lj(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=kn(n.childForFieldName("type"));o&&t.set(r.text,o)}return t}function xn(e,t,n,r,o={locals:Gi(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",...$j]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(Ki(l.childForFieldName("function")));else if(l.type==="new_expression")a(Ki(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(Ki(d))}}var $j,wc=w(()=>{"use strict";s(_c,"newResult");s(vn,"line1");s(bc,"signatureOf");s(Pj,"calleeName");s(Mj,"collectCallTargets");s(hf,"addCallRefs");s(Ki,"calleeRef");$j=["jsx_opening_element","jsx_self_closing_element"];s(kn,"typeNameOf");s(Lj,"isMethodCallResult");s(gf,"newTypeOf");s(Gi,"collectTypeHints");s(xn,"addTsRefs")});function gx(e,t){let n=_c();for(let r of e.namedChildren)jj(r,t,n);return n}function yx(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function jj(e,t,n){let r=yx(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Hj(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=kc(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&&hf(n,i.nodeKey,a,hx);return}case"class_definition":Fj(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=kc(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 Fj(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let o=kc(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=yx(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=kc(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&&hf(n,p.nodeKey,f,hx)}}function kc(e,t,n,r,o){return{nodeKey:kt(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vn(e.startPosition.row),endLine:vn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:bc(e),doc:null}}function Hj(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var hx,_x=w(()=>{"use strict";zn();wc();hx="call";s(gx,"extractPython");s(yx,"unwrapDecorated");s(jj,"handleTopLevel");s(Fj,"addClass");s(kc,"makeNode");s(Hj,"firstDottedName")});function wx(e,t){let n=_c(),r=t.language!=="typescript";for(let o of e.namedChildren)Bj(o,t,n,r);return Wj(e,t,n),n}function Uj(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function Bj(e,t,n,r){if(e.type==="export_statement"&&Kj(e,t,n,r))return;let o=Uj(e),i=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(o.type){case"import_statement":Gj(o,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=bx(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=qj(o,t,n,r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":yf(o,t,n,"interface");return;case"type_alias_declaration":yf(o,t,n,"type_alias");return;case"enum_declaration":yf(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&&xn(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";bx(a,t,n,d?"function":"variable",r,c,l)}return}default:xn(n,t.moduleKey,o,r);return}}function Kj(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let o=bf(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}):xn(n,t.moduleKey,c,r),!0):!1}function Gj(e,t,n){let r=bf(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 Wj(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"?bf(o):null;if(i===null)continue;let c=Vj(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 Vj(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function bx(e,t,n,r,o,i,a){let l=(i??e.childForFieldName("name"))?.text;if(!l)return null;let d=vc(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;xn(n,d.nodeKey,u,o,{locals:Gi(e)})}else a&&xn(n,d.nodeKey,a,o);return d}function yf(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return;let i=vc(e,t,o,o,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function qj(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return null;let i=vc(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:_f(p)})):[{kind:"extends",ref:_f(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=zj(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&xn(n,i.nodeKey,g,r,{locals:Gi(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${o}.${u}`,f=vc(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&xn(n,f.nodeKey,m,r,{locals:Gi(d),thisFields:l})}return i}function zj(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=kn(n.childForFieldName("type"))??gf(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=kn(r.childForFieldName("type"));o?.type==="identifier"&&i&&t.set(o.text,i)}return t}function vc(e,t,n,r,o){return{nodeKey:kt(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vn(e.startPosition.row),endLine:vn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:bc(e),doc:null}}function _f(e){if(!e)return null;switch(e.type){case"generic_type":return _f(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return Ki(e);default:return null}}function bf(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var kx=w(()=>{"use strict";zn();wc();s(wx,"extractTypescript");s(Uj,"unwrapExport");s(Bj,"handleTopLevel");s(Kj,"handleExportForm");s(Gj,"addImport");s(Wj,"collectDynamicImports");s(Vj,"enclosingDeclarator");s(bx,"addFunctionLike");s(yf,"addSimpleNamed");s(qj,"addClass");s(zj,"classFieldTypes");s(vc,"makeNode");s(_f,"heritageRef");s(bf,"stringValue")});import{createRequire as Jj}from"node:module";import{join as Yj}from"node:path";function Sx(e,t){return t?Yj(t,vx[e]):Jj(import.meta.url).resolve(`tree-sitter-wasms/out/${vx[e]}`)}var vx,xx,Ex=w(()=>{"use strict";vx={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},xx="tree-sitter.wasm";s(Sx,"grammarPath")});import{join as Xj}from"node:path";import wf from"web-tree-sitter";var Zj,xc,Rx=w(()=>{"use strict";zn();Vs();_x();kx();wc();Ex();Zj=["typescript","tsx","javascript","python"],xc=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await wf.init(this.assetDir?{locateFile:s(t=>Xj(this.assetDir,t||xx),"locateFile")}:void 0),this.parser=new wf,this.initialized=!0)}supports(t){return Zj.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=wt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:vn(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?gx(a,d):wx(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 wf.Language.load(Sx(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as Qj}from"node:module";function Cx(){return Sc("node:sqlite")}function bo(){if(Wi)return Wi;try{let{DatabaseSync:e}=Cx(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Wi={ok:!0}}finally{t.close()}}catch(e){Wi={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Wi}function eF(e){let{DatabaseSync:t}=Cx(),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 tF(e){let t=Sc("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 Tx(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Ec(e){let t=Tx(),n=s(()=>{let{DatabaseSync:o}=Sc("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=Sc("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 Rc(e){let t=Tx(),n=s(o=>{let i=o==="node:sqlite"?eF(e):tF(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:o}},"openAs");if(t==="builtin"){let o=bo();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=bo();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 Sc,Wi,Cc=w(()=>{"use strict";Sc=Qj(import.meta.url);s(Cx,"loadBuiltin");Wi=null;s(bo,"probeBuiltinSqlite");s(eF,"openBuiltin");s(tF,"openBetter");s(Tx,"backendOverride");s(Ec,"openSqliteReadOnly");s(Rc,"openSqliteDatabase")});function $x(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 Lx(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:mr(a.receiver),receiverType:mr(a.receiver_type)});for(let a of n){let c=i(a);if(!c)continue;let l={fromModuleKey:wt(c.filePath),specifier:String(a.specifier),importedName:mr(a.imported_name),localName:mr(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:mr(a.local_name),specifier:mr(a.specifier),importedName:mr(a.imported_name)};i(a)?.exports.push(c)}return[...o.values()]}var Ax,Ix,Nx,Ox,Dx,Px,Mx,mr,jx=w(()=>{"use strict";zn();Ax=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Ix="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Nx="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Ox="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Dx="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Px="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Mx="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s($x,"factRows");mr=s(e=>e==null?null:String(e),"str");s(Lx,"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 Fx,Vi,Hx=w(()=>{"use strict";Cc();Xr();jx();Nu();s(Tc,"toNodeRow");Fx=400,Vi=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Rc(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Cu)}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 m of o.contains)l.run(m.srcKey,m.dstKey,m.kind);let d=$x(t.path,o),u=this.db.prepare(Ix);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Nx);for(let m of d.imports)p.run(...m);let f=this.db.prepare(Ox);for(let m of d.exports)f.run(...m)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return Lx(t,this.db.prepare(Dx).all(),this.db.prepare(Px).all(),this.db.prepare(Mx).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=ew(t);if(!o)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
835
+ ${Tj(t)}
836
+ [Y/n]: `))return r("skipped","user declined","skip")}return e.dryRun?r("would-create",t.path):(await B(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 hf(e,t){let n=[];for(let r of t)n.push(await Aj(e,r));return n}async function Ij(e,t){e.write(t);let n=ix.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 sx,kj,ox,yc=w(()=>{"use strict";qa();Ue();lo();ae();et();et();io();sx="<!-- maind:rules v1",kj=`${sx} \xB7 written by maind-mcp-bridge (ADR-364): the bridge rewrites this file when it refreshes \u2014 do not edit by hand -->`;s(vj,"copilotInstructionsPath");s(xj,"clineRulesDir");s(Sj,"continueRulesPath");ox="MAIND consultation triggers and the project conventions of the repository you work in";s(fr,"ruleChannels");s(ax,"ruleChannelIdForFamily");s(Ej,"rulesTargetKey");s(Rj,"tildify");s(mf,"renderRulesFile");s(Cj,"stamp");s(_o,"isOurRulesFile");s(yo,"canonicalRulesContent");s(Bi,"rulesContentHash");s(Tj,"ruleConsentDescription");s(Aj,"mergeRuleChannel");s(hf,"mergeRuleChannels");s(Ij,"promptYesNo")});async function cx(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 lx=w(()=>{"use strict";s(cx,"exchangeOneClickToken")});async function px(e){let t="browser-pair";if(e.token!==null)try{let i=Nj(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(wi(),or(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:dx(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=Ea(e.bridgeVersion),a=await cx({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:Dw(),clientMeta:{...i}});if(a.ok)return wi(),or(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,ux(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
837
+ `)}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 no(e.bridgeVersion,ux(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:dx(i)}}}}function Nj(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 dx(e){return e instanceof Error?e.message:String(e)}function ux(e){return e.out??process.stdout}var fx=w(()=>{"use strict";tp();ie();lx();s(px,"pairOrUseToken");s(Nj,"validateTokenShape");s(dx,"errMessage");s(ux,"out")});async function mx(e){if(!e.enabled||e.apiKey===null)return;let t=eo(Oj),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Mj(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Pj(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,o=setTimeout(()=>r.abort(),Dj);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 Pj(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 Mj(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}var Oj,Dj,hx=w(()=>{"use strict";to();Oj="install-completed",Dj=3e3;s(mx,"postInstallTelemetry");s(Pj,"countStatuses");s(Mj,"parseNodeMajor")});function _c(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function vn(e){return e+1}function bc(e){return(e.text.split(`
838
+ `,1)[0]??"").trim().slice(0,200)}function $j(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 Lj(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let o=$j(r.childForFieldName("function"));o&&n.add(o)}return[...n]}function gf(e,t,n,r){for(let o of Lj(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:o})}function Ki(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let 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 kn(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 kn(t.childForFieldName("name"));case"parenthesized_type":return kn(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?kn(n[0]):"#"}default:return"#"}}function Fj(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function yf(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 Gi(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=kn(n.childForFieldName("type"))??yf(o)??(Fj(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=kn(n.childForFieldName("type"));o&&t.set(r.text,o)}return t}function xn(e,t,n,r,o={locals:Gi(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",...jj]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(Ki(l.childForFieldName("function")));else if(l.type==="new_expression")a(Ki(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(Ki(d))}}var jj,wc=w(()=>{"use strict";s(_c,"newResult");s(vn,"line1");s(bc,"signatureOf");s($j,"calleeName");s(Lj,"collectCallTargets");s(gf,"addCallRefs");s(Ki,"calleeRef");jj=["jsx_opening_element","jsx_self_closing_element"];s(kn,"typeNameOf");s(Fj,"isMethodCallResult");s(yf,"newTypeOf");s(Gi,"collectTypeHints");s(xn,"addTsRefs")});function yx(e,t){let n=_c();for(let r of e.namedChildren)Hj(r,t,n);return n}function _x(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function Hj(e,t,n){let r=_x(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Bj(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=kc(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&&gf(n,i.nodeKey,a,gx);return}case"class_definition":Uj(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=kc(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 Uj(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let o=kc(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=_x(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=kc(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&&gf(n,p.nodeKey,f,gx)}}function kc(e,t,n,r,o){return{nodeKey:kt(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vn(e.startPosition.row),endLine:vn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:bc(e),doc:null}}function Bj(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var gx,bx=w(()=>{"use strict";zn();wc();gx="call";s(yx,"extractPython");s(_x,"unwrapDecorated");s(Hj,"handleTopLevel");s(Uj,"addClass");s(kc,"makeNode");s(Bj,"firstDottedName")});function kx(e,t){let n=_c(),r=t.language!=="typescript";for(let o of e.namedChildren)Gj(o,t,n,r);return qj(e,t,n),n}function Kj(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function Gj(e,t,n,r){if(e.type==="export_statement"&&Wj(e,t,n,r))return;let o=Kj(e),i=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(o.type){case"import_statement":Vj(o,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=wx(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=Jj(o,t,n,r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":_f(o,t,n,"interface");return;case"type_alias_declaration":_f(o,t,n,"type_alias");return;case"enum_declaration":_f(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&&xn(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";wx(a,t,n,d?"function":"variable",r,c,l)}return}default:xn(n,t.moduleKey,o,r);return}}function Wj(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let o=wf(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}):xn(n,t.moduleKey,c,r),!0):!1}function Vj(e,t,n){let r=wf(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 qj(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"?wf(o):null;if(i===null)continue;let c=zj(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 zj(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function wx(e,t,n,r,o,i,a){let l=(i??e.childForFieldName("name"))?.text;if(!l)return null;let d=vc(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;xn(n,d.nodeKey,u,o,{locals:Gi(e)})}else a&&xn(n,d.nodeKey,a,o);return d}function _f(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return;let i=vc(e,t,o,o,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function Jj(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return null;let i=vc(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:bf(p)})):[{kind:"extends",ref:bf(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=Yj(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&xn(n,i.nodeKey,g,r,{locals:Gi(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${o}.${u}`,f=vc(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&xn(n,f.nodeKey,m,r,{locals:Gi(d),thisFields:l})}return i}function Yj(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=kn(n.childForFieldName("type"))??yf(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=kn(r.childForFieldName("type"));o?.type==="identifier"&&i&&t.set(o.text,i)}return t}function vc(e,t,n,r,o){return{nodeKey:kt(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vn(e.startPosition.row),endLine:vn(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:bc(e),doc:null}}function bf(e){if(!e)return null;switch(e.type){case"generic_type":return bf(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return Ki(e);default:return null}}function wf(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var vx=w(()=>{"use strict";zn();wc();s(kx,"extractTypescript");s(Kj,"unwrapExport");s(Gj,"handleTopLevel");s(Wj,"handleExportForm");s(Vj,"addImport");s(qj,"collectDynamicImports");s(zj,"enclosingDeclarator");s(wx,"addFunctionLike");s(_f,"addSimpleNamed");s(Jj,"addClass");s(Yj,"classFieldTypes");s(vc,"makeNode");s(bf,"heritageRef");s(wf,"stringValue")});import{createRequire as Xj}from"node:module";import{join as Zj}from"node:path";function Ex(e,t){return t?Zj(t,xx[e]):Xj(import.meta.url).resolve(`tree-sitter-wasms/out/${xx[e]}`)}var xx,Sx,Rx=w(()=>{"use strict";xx={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Sx="tree-sitter.wasm";s(Ex,"grammarPath")});import{join as Qj}from"node:path";import kf from"web-tree-sitter";var eF,xc,Cx=w(()=>{"use strict";zn();Vs();bx();vx();wc();Rx();eF=["typescript","tsx","javascript","python"],xc=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await kf.init(this.assetDir?{locateFile:s(t=>Qj(this.assetDir,t||Sx),"locateFile")}:void 0),this.parser=new kf,this.initialized=!0)}supports(t){return eF.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=wt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:vn(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?yx(a,d):kx(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 kf.Language.load(Ex(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as tF}from"node:module";function Tx(){return Sc("node:sqlite")}function bo(){if(Wi)return Wi;try{let{DatabaseSync:e}=Tx(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Wi={ok:!0}}finally{t.close()}}catch(e){Wi={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Wi}function nF(e){let{DatabaseSync:t}=Tx(),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 rF(e){let t=Sc("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 Ax(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Ec(e){let t=Ax(),n=s(()=>{let{DatabaseSync:o}=Sc("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=Sc("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 Rc(e){let t=Ax(),n=s(o=>{let i=o==="node:sqlite"?nF(e):rF(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:o}},"openAs");if(t==="builtin"){let o=bo();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=bo();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 Sc,Wi,Cc=w(()=>{"use strict";Sc=tF(import.meta.url);s(Tx,"loadBuiltin");Wi=null;s(bo,"probeBuiltinSqlite");s(nF,"openBuiltin");s(rF,"openBetter");s(Ax,"backendOverride");s(Ec,"openSqliteReadOnly");s(Rc,"openSqliteDatabase")});function Lx(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 jx(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:mr(a.receiver),receiverType:mr(a.receiver_type)});for(let a of n){let c=i(a);if(!c)continue;let l={fromModuleKey:wt(c.filePath),specifier:String(a.specifier),importedName:mr(a.imported_name),localName:mr(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:mr(a.local_name),specifier:mr(a.specifier),importedName:mr(a.imported_name)};i(a)?.exports.push(c)}return[...o.values()]}var Ix,Nx,Ox,Dx,Px,Mx,$x,mr,Fx=w(()=>{"use strict";zn();Ix=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Nx="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Ox="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Dx="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Px="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Mx="SELECT file_path, specifier, imported_name, local_name FROM file_imports",$x="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(Lx,"factRows");mr=s(e=>e==null?null:String(e),"str");s(jx,"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 Hx,Vi,Ux=w(()=>{"use strict";Cc();Xr();Fx();Nu();s(Tc,"toNodeRow");Hx=400,Vi=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Rc(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Cu)}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 m of o.contains)l.run(m.srcKey,m.dstKey,m.kind);let d=Lx(t.path,o),u=this.db.prepare(Nx);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Ox);for(let m of d.imports)p.run(...m);let f=this.db.prepare(Dx);for(let m of d.exports)f.run(...m)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return jx(t,this.db.prepare(Px).all(),this.db.prepare(Mx).all(),this.db.prepare($x).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=tw(t);if(!o)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
839
839
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
840
840
  WHERE nodes_fts MATCH ? AND n.kind = ?
841
841
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
@@ -848,7 +848,7 @@ ${Rj(t)}
848
848
  FROM nodes n
849
849
  WHERE n.kind = 'module'
850
850
  ORDER BY imports_in DESC, symbol_count DESC
851
- 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+=Fx)for(let a of n.slice(i,i+Fx))r.run(a),o.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let i of Ax)this.db.prepare(i).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
851
+ 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+=Hx)for(let a of n.slice(i,i+Hx))r.run(a),o.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let i of Ix)this.db.prepare(i).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
852
852
  node_key, kind, name, qualified_name, file_path, language,
853
853
  start_line, end_line, start_byte, end_byte, signature, doc
854
854
  ) 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)
@@ -858,111 +858,111 @@ ${Rj(t)}
858
858
  content_hash = excluded.content_hash,
859
859
  mtime_ms = excluded.mtime_ms,
860
860
  size = excluded.size,
861
- indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as nF}from"node:crypto";function wo(e){return nF("sha256").update(e,"utf8").digest("hex")}function Ux(e){return{node_key_hash:wo(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:wo(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?wo(e.signature):null}}function Bx(e){return{src_key_hash:wo(e.srcKey),dst_key_hash:wo(e.dstKey),kind:e.kind}}function Kx(e,t,n){return{node_key_hash:wo(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Gx=w(()=>{"use strict";s(wo,"sha256");s(Ux,"toCloudNode");s(Bx,"toCloudEdge");s(Kx,"toCloudEmbedding")});import{randomUUID as rF}from"node:crypto";function kf(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Wx(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Vx(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ko,vo,oF,vf=w(()=>{"use strict";Xr();Gx();ko=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},vo=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(Jr),lastSyncedAt:Wx(await this.store.getMeta(Au))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Ux),n=(await this.store.getAllEdges()).map(Bx),r=await this.store.getMeta(cn)??an,o=await this.store.getMeta(Jr),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=rF(),l={project_key:this.cfg.projectKey,head_commit:o,schema_version:r,file_count:i,lang_dist:a},d=0,u=kf(t,this.chunk),p=kf(n,this.chunk*2),f=Math.max(1,u.length+p.length);for(let _ of u)await this.post("/api/codebase/push",{...l,nodes:_,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:f});for(let _ of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:_,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:f});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let m=t.map(_=>_.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(Au,String(Date.now())),o&&await this.store.setMeta(Zb,o),{nodes:t.length,edges:n.length,pruned:Vx(g.nodes_deleted),edgesPruned:Vx(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=>Kx(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=kf(a,oF),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(fa),n=await this.store.getMeta(ma),r=Wx(await this.store.getMeta(ha));if(!t||!n||!r)throw new ko("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 ko(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return o}},oF=250;s(kf,"chunkArray");s(Wx,"numOrNull");s(Vx,"numOr0")});var Sf={};Q(Sf,{CodeIndexSync:()=>vo,DEFAULT_DB_RELPATH:()=>xf,SyncError:()=>ko,createCodeIndexSync:()=>sF,createNodeCodeIndex:()=>Ic,openIndexReader:()=>aF,openSqliteDatabase:()=>Rc,openSqliteReadOnly:()=>Ec,probeBuiltinSqlite:()=>bo});import{mkdirSync as iF}from"node:fs";import{posix as Ac}from"node:path";function Ic(e){let t=e.dbPath??Ac.join(e.repoRoot,xf);iF(Ac.dirname(t),{recursive:!0}),e.dbPath===void 0&&ti(Ac.dirname(t));let n=new Vi(t),r=new xc;return new gi({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function sF(e){let t=e.dbPath??Ac.join(e.repoRoot,xf),n=e.projectKey??W_(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new Vi(t);return new vo(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function aF(e){return ju(Ec(e).db)}var xf,Nc=w(()=>{"use strict";Ud();Rx();Ou();Fu();Hx();Cc();vf();zs();vf();Cc();xf=".maind/code-index.sqlite";s(Ic,"createNodeCodeIndex");s(sF,"createCodeIndexSync");s(aF,"openIndexReader")});import{execFileSync as qx}from"node:child_process";import{existsSync as zx,realpathSync as Jx}from"node:fs";import{createRequire as cF}from"node:module";import{basename as lF,dirname as dF,isAbsolute as Yx,join as uF,relative as Xx,resolve as Oc,sep as Zx}from"node:path";function Dc(){let e=bo();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return cF(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 Qx(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 je(e=process.cwd()){try{let t=qx("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 tS(e,t=je(),n=process.cwd()){let r=Yx(e)?[e]:[Oc(t,e),Oc(n,e)];for(let o of r){let i=dF(o);if(!zx(i))continue;let a;try{a=Jx(i)}catch{continue}let c=nS(a);if(c===null)continue;let l=Xx(c,uF(a,lF(o)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Zx).join("/")}}return null}function xo(e,t=je(),n=process.cwd()){let r=Yx(e)?[e]:[Oc(t,e),Oc(n,e)];for(let o of r){if(!zx(o))continue;let i;try{i=Jx(o)}catch{continue}let a=nS(i);if(a===null)continue;let c=Xx(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Zx).join("/")}}return null}function nS(e){try{let t=qx("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 rS(){return Ic({repoRoot:je()})}function oS(e){return Ic({repoRoot:e})}var eS,Sn=w(()=>{"use strict";Nc();s(Dc,"probeNativeStore");s(Qx,"isNativeStoreUnavailable");eS="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(je,"resolveRepoRoot");s(tS,"resolveRepoRootForPath");s(xo,"resolveRepoRootForDir");s(nS,"gitToplevelOf");s(rS,"defaultEngineFactory");s(oS,"engineForRoot")});async function hr(e){return qt("get_session_briefing",{tools:["claude-code"]},e)}async function qt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??qi,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:pF,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 iS(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 m=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await iS(p):await p.text();if(m.trim().length===0)return null;let g=JSON.parse(m);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(i)}}async function iS(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(`
861
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as oF}from"node:crypto";function wo(e){return oF("sha256").update(e,"utf8").digest("hex")}function Bx(e){return{node_key_hash:wo(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:wo(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?wo(e.signature):null}}function Kx(e){return{src_key_hash:wo(e.srcKey),dst_key_hash:wo(e.dstKey),kind:e.kind}}function Gx(e,t,n){return{node_key_hash:wo(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Wx=w(()=>{"use strict";s(wo,"sha256");s(Bx,"toCloudNode");s(Kx,"toCloudEdge");s(Gx,"toCloudEmbedding")});import{randomUUID as iF}from"node:crypto";function vf(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Vx(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function qx(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ko,vo,sF,xf=w(()=>{"use strict";Xr();Wx();ko=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},vo=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(Jr),lastSyncedAt:Vx(await this.store.getMeta(Au))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Bx),n=(await this.store.getAllEdges()).map(Kx),r=await this.store.getMeta(cn)??an,o=await this.store.getMeta(Jr),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=iF(),l={project_key:this.cfg.projectKey,head_commit:o,schema_version:r,file_count:i,lang_dist:a},d=0,u=vf(t,this.chunk),p=vf(n,this.chunk*2),f=Math.max(1,u.length+p.length);for(let _ of u)await this.post("/api/codebase/push",{...l,nodes:_,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:f});for(let _ of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:_,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:f});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let m=t.map(_=>_.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(Au,String(Date.now())),o&&await this.store.setMeta(Qb,o),{nodes:t.length,edges:n.length,pruned:qx(g.nodes_deleted),edgesPruned:qx(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=>Gx(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=vf(a,sF),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(fa),n=await this.store.getMeta(ma),r=Vx(await this.store.getMeta(ha));if(!t||!n||!r)throw new ko("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 ko(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return o}},sF=250;s(vf,"chunkArray");s(Vx,"numOrNull");s(qx,"numOr0")});var Ef={};ee(Ef,{CodeIndexSync:()=>vo,DEFAULT_DB_RELPATH:()=>Sf,SyncError:()=>ko,createCodeIndexSync:()=>cF,createNodeCodeIndex:()=>Ic,openIndexReader:()=>lF,openSqliteDatabase:()=>Rc,openSqliteReadOnly:()=>Ec,probeBuiltinSqlite:()=>bo});import{mkdirSync as aF}from"node:fs";import{posix as Ac}from"node:path";function Ic(e){let t=e.dbPath??Ac.join(e.repoRoot,Sf);aF(Ac.dirname(t),{recursive:!0}),e.dbPath===void 0&&ti(Ac.dirname(t));let n=new Vi(t),r=new xc;return new gi({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function cF(e){let t=e.dbPath??Ac.join(e.repoRoot,Sf),n=e.projectKey??V_(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new Vi(t);return new vo(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function lF(e){return ju(Ec(e).db)}var Sf,Nc=w(()=>{"use strict";Ud();Cx();Ou();Fu();Ux();Cc();xf();zs();xf();Cc();Sf=".maind/code-index.sqlite";s(Ic,"createNodeCodeIndex");s(cF,"createCodeIndexSync");s(lF,"openIndexReader")});import{execFileSync as zx}from"node:child_process";import{existsSync as Jx,realpathSync as Yx}from"node:fs";import{createRequire as dF}from"node:module";import{basename as uF,dirname as pF,isAbsolute as Xx,join as fF,relative as Zx,resolve as Oc,sep as Qx}from"node:path";function Dc(){let e=bo();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return dF(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 eS(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 je(e=process.cwd()){try{let t=zx("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 nS(e,t=je(),n=process.cwd()){let r=Xx(e)?[e]:[Oc(t,e),Oc(n,e)];for(let o of r){let i=pF(o);if(!Jx(i))continue;let a;try{a=Yx(i)}catch{continue}let c=rS(a);if(c===null)continue;let l=Zx(c,fF(a,uF(o)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Qx).join("/")}}return null}function xo(e,t=je(),n=process.cwd()){let r=Xx(e)?[e]:[Oc(t,e),Oc(n,e)];for(let o of r){if(!Jx(o))continue;let i;try{i=Yx(o)}catch{continue}let a=rS(i);if(a===null)continue;let c=Zx(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Qx).join("/")}}return null}function rS(e){try{let t=zx("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 oS(){return Ic({repoRoot:je()})}function iS(e){return Ic({repoRoot:e})}var tS,Sn=w(()=>{"use strict";Nc();s(Dc,"probeNativeStore");s(eS,"isNativeStoreUnavailable");tS="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(je,"resolveRepoRoot");s(nS,"resolveRepoRootForPath");s(xo,"resolveRepoRootForDir");s(rS,"gitToplevelOf");s(oS,"defaultEngineFactory");s(iS,"engineForRoot")});async function hr(e){return qt("get_session_briefing",{tools:["claude-code"]},e)}async function qt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??qi,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:mF,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 sS(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 m=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await sS(p):await p.text();if(m.trim().length===0)return null;let g=JSON.parse(m);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(i)}}async function sS(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(`
862
862
  `).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(`
863
- `))!==-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 qi,pF,En=w(()=>{"use strict";qi="https://mcp.maind.dev/mcp",pF="2025-06-18";s(hr,"fetchSessionBriefing");s(qt,"fetchToolText");s(iS,"readSseMessage")});function sS(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(sS(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(sS(t))),e.on("error",()=>a({}))})}function So(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function rt(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var Ee=w(()=>{"use strict";s(sS,"parsePayload");s(V,"readHookInput");s(So,"transcriptPathOf");s(rt,"toolFilePathOf")});function gr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function yr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function zi(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function Pc(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Ef(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Ji=w(()=>{"use strict";s(gr,"denyPayload");s(yr,"advisoryPayload");s(zi,"postAdvisoryPayload");s(Pc,"postFailureAdvisoryPayload");s(Ef,"promptAdvisoryPayload")});function fF(e){return Rn(e)&&/[\\/]\.claude[^\\/]*[\\/]projects[\\/]/.test(e)}function mF(e){return Rn(e)&&/[\\/]sessions[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/]rollout-[^\\/]+\.jsonl$/.test(e)}function aS(e){for(let t of e)if(t==="--host=codex")return"codex";return null}function Yi(e,t=process.env,n=null){return n==="codex"?"codex":Rn(e.cursor_version)?"cursor":fF(e.transcript_path)?"claude-code":mF(e.transcript_path)?"codex":Rn(t.CURSOR_VERSION)?"cursor":Rn(t.DEVIN_PROJECT_DIR)?"devin":Rn(t.CLAUDE_PROJECT_DIR)||t.CLAUDECODE==="1"?"claude-code":"unknown"}function cS(e,t=process.env){return Yi(e,t)==="cursor"}function Cn(e){return e==="cursor"||e==="devin"||e==="codex"}function pt(e,t=process.env){return Cn(Yi(e,t))}function hF(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 pe(e,t=process.env,n=ee,r=null){let o=Yi(e,t,r);return{host:o,devinOutput:o==="devin"?hF(t,n()):!1}}function gF(e){switch(e.kind){case"text":return e.text;case"deny":return gr(e.reason);case"context":switch(e.event){case"UserPromptSubmit":return Ef(e.text);case"PreToolUse":return yr(e.text);case"PostToolUse":return zi(e.text);case"PostToolUseFailure":return Pc(e.text)}}}function yF(e){return e.kind==="deny"?JSON.stringify({permission:"deny",user_message:e.reason,agent_message:e.reason}):null}function _F(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"?Ef(e.text):e.event==="PostToolUse"?zi(e.text):null}}function bF(e){return e.kind!=="text"?null:JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.text.replace(/\s+$/,"")}})}function ge(e,t){switch(e.host){case"claude-code":case"unknown":return gF(t);case"cursor":return yF(t);case"devin":return e.devinOutput?_F(t):null;case"codex":return bF(t)}}function Re(e,t){let n=t.kind==="deny"?{kind:"deny",reason:"x"}:{...t,text:"x"};return ge(e,n)!==null}function Mc(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}function $c(e,t=process.env){return e.host==="devin"&&Rn(t.DEVIN_PROJECT_DIR)?t.DEVIN_PROJECT_DIR.trim():e.host==="cursor"&&Rn(t.CURSOR_PROJECT_DIR)?t.CURSOR_PROJECT_DIR.trim():null}var Rn,Fe=w(()=>{"use strict";Ve();Ji();Rn=s(e=>typeof e=="string"&&e.trim().length>0,"filled");s(fF,"isClaudeCodeTranscript");s(mF,"isCodexTranscript");s(aS,"hostHintFromArgv");s(Yi,"detectHookHost");s(cS,"runsUnderCursor");s(Cn,"isForeignHost");s(pt,"guardStandsDown");s(hF,"devinOutputEnabled");s(pe,"resolveHookTarget");s(gF,"claudeCodeBytes");s(yF,"cursorBytes");s(_F,"devinBytes");s(bF,"codexBytes");s(ge,"renderHookOutput");s(Re,"hostDelivers");s(Mc,"writeHookStdout");s($c,"hostProjectDir")});import{existsSync as wF,readFileSync as kF}from"node:fs";import{join as Rf}from"node:path";function lS(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function Cf(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function uS(e,t={}){return e.some(n=>Cf(Me(n,t,[dS])[0]))}function Xi(e,t){let n=Me(e,t,[dS])[0],r=Me(e,t,[vF])[0];return{channel:Cf(n)?"core":Cf(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function pS(e,t){let n=[Rf(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(Rf(t,".claude","settings.json"),Rf(t,".claude","settings.local.json")),n.map(r=>{try{return wF(r)?kF(r,"utf8"):null}catch{return null}})}var dS,vF,Lc=w(()=>{"use strict";he();s(lS,"hookOf");dS=lS(Ge,Y),vF=lS(uo,"guard-inject");s(Cf,"isRunnable");s(uS,"coreBriefingWiredIn");s(Xi,"briefingChannel");s(pS,"claudeSettingsSources")});function fS(e){return e==="on"?!0:e==="off"?!1:null}function ye(e=process.env,t=ee()){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:fS(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:fS(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function _r(e,t=We()){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 B(t,JSON.stringify(r,null,2)+`
864
- `,384)}var Ct=w(()=>{"use strict";Ve();se();s(fS,"envSwitch");s(ye,"resolveGuardConfig");s(_r,"writeGuardConfig")});function Fc(e){if(!e)return null;let t=e.split(`
863
+ `))!==-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 qi,mF,En=w(()=>{"use strict";qi="https://mcp.maind.dev/mcp",mF="2025-06-18";s(hr,"fetchSessionBriefing");s(qt,"fetchToolText");s(sS,"readSseMessage")});function aS(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(aS(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(aS(t))),e.on("error",()=>a({}))})}function So(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function rt(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var Ee=w(()=>{"use strict";s(aS,"parsePayload");s(V,"readHookInput");s(So,"transcriptPathOf");s(rt,"toolFilePathOf")});function gr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function yr(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function zi(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function Pc(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Rf(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Ji=w(()=>{"use strict";s(gr,"denyPayload");s(yr,"advisoryPayload");s(zi,"postAdvisoryPayload");s(Pc,"postFailureAdvisoryPayload");s(Rf,"promptAdvisoryPayload")});function hF(e){return Rn(e)&&/[\\/]\.claude[^\\/]*[\\/]projects[\\/]/.test(e)}function gF(e){return Rn(e)&&/[\\/]sessions[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/]rollout-[^\\/]+\.jsonl$/.test(e)}function cS(e){for(let t of e)if(t==="--host=codex")return"codex";return null}function Yi(e,t=process.env,n=null){return n==="codex"?"codex":Rn(e.cursor_version)?"cursor":hF(e.transcript_path)?"claude-code":gF(e.transcript_path)?"codex":Rn(t.CURSOR_VERSION)?"cursor":Rn(t.DEVIN_PROJECT_DIR)?"devin":Rn(t.CLAUDE_PROJECT_DIR)||t.CLAUDECODE==="1"?"claude-code":"unknown"}function lS(e,t=process.env){return Yi(e,t)==="cursor"}function Cn(e){return e==="cursor"||e==="devin"||e==="codex"}function pt(e,t=process.env){return Cn(Yi(e,t))}function yF(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 pe(e,t=process.env,n=te,r=null){let o=Yi(e,t,r);return{host:o,devinOutput:o==="devin"?yF(t,n()):!1}}function _F(e){switch(e.kind){case"text":return e.text;case"deny":return gr(e.reason);case"context":switch(e.event){case"UserPromptSubmit":return Rf(e.text);case"PreToolUse":return yr(e.text);case"PostToolUse":return zi(e.text);case"PostToolUseFailure":return Pc(e.text)}}}function bF(e){return e.kind==="deny"?JSON.stringify({permission:"deny",user_message:e.reason,agent_message:e.reason}):null}function wF(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"?Rf(e.text):e.event==="PostToolUse"?zi(e.text):null}}function kF(e){return e.kind!=="text"?null:JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.text.replace(/\s+$/,"")}})}function ge(e,t){switch(e.host){case"claude-code":case"unknown":return _F(t);case"cursor":return bF(t);case"devin":return e.devinOutput?wF(t):null;case"codex":return kF(t)}}function Re(e,t){let n=t.kind==="deny"?{kind:"deny",reason:"x"}:{...t,text:"x"};return ge(e,n)!==null}function Mc(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}function $c(e,t=process.env){return e.host==="devin"&&Rn(t.DEVIN_PROJECT_DIR)?t.DEVIN_PROJECT_DIR.trim():e.host==="cursor"&&Rn(t.CURSOR_PROJECT_DIR)?t.CURSOR_PROJECT_DIR.trim():null}var Rn,Fe=w(()=>{"use strict";Ve();Ji();Rn=s(e=>typeof e=="string"&&e.trim().length>0,"filled");s(hF,"isClaudeCodeTranscript");s(gF,"isCodexTranscript");s(cS,"hostHintFromArgv");s(Yi,"detectHookHost");s(lS,"runsUnderCursor");s(Cn,"isForeignHost");s(pt,"guardStandsDown");s(yF,"devinOutputEnabled");s(pe,"resolveHookTarget");s(_F,"claudeCodeBytes");s(bF,"cursorBytes");s(wF,"devinBytes");s(kF,"codexBytes");s(ge,"renderHookOutput");s(Re,"hostDelivers");s(Mc,"writeHookStdout");s($c,"hostProjectDir")});import{existsSync as vF,readFileSync as xF}from"node:fs";import{join as Cf}from"node:path";function dS(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function Tf(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function pS(e,t={}){return e.some(n=>Tf(Me(n,t,[uS])[0]))}function Xi(e,t){let n=Me(e,t,[uS])[0],r=Me(e,t,[SF])[0];return{channel:Tf(n)?"core":Tf(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function fS(e,t){let n=[Cf(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(Cf(t,".claude","settings.json"),Cf(t,".claude","settings.local.json")),n.map(r=>{try{return vF(r)?xF(r,"utf8"):null}catch{return null}})}var uS,SF,Lc=w(()=>{"use strict";he();s(dS,"hookOf");uS=dS(Ge,Y),SF=dS(uo,"guard-inject");s(Tf,"isRunnable");s(pS,"coreBriefingWiredIn");s(Xi,"briefingChannel");s(fS,"claudeSettingsSources")});function mS(e){return e==="on"?!0:e==="off"?!1:null}function ye(e=process.env,t=te()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0,difficulty:mS(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:mS(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function _r(e,t=We()){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 B(t,JSON.stringify(r,null,2)+`
864
+ `,384)}var Ct=w(()=>{"use strict";Ve();ae();s(mS,"envSwitch");s(ye,"resolveGuardConfig");s(_r,"writeGuardConfig")});function Fc(e){if(!e)return null;let t=e.split(`
865
865
  `),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(`
866
- `):null}function xF(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(`
866
+ `):null}function EF(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(`
867
867
  `),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 Hc(e,t,n,r=9e3){let o=[];if(t){let[d,...u]=t.split(`
868
- `);o.push({title:d,lines:u,more:"get_conventions"})}o.push(...xF(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of o){let u=`
868
+ `);o.push({title:d,lines:u,more:"get_conventions"})}o.push(...EF(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of o){let u=`
869
869
 
870
870
  ${d.title}`;if(jc(c+u)>a){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let f=`
871
871
  ${d.lines[p]}`;if(jc(c+f)<=a){c+=f;continue}l=!1;let m=`
872
872
  (+${d.lines.length-p} more \u2014 via ${d.more})`;jc(c+m)<=r&&(c+=m);break}if(!l)break}if(!l){let d=`
873
873
  \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;jc(c+d)<=r&&(c+=d)}return{text:c+`
874
- `,complete:l}}var jc,Uc=w(()=>{"use strict";jc=s(e=>Buffer.byteLength(e,"utf8"),"bytes");s(Fc,"extractConventionsBlock");s(xF,"briefingSections");s(Hc,"composeInjection")});import{existsSync as hS}from"node:fs";import{mkdir as SF,readFile as EF,readdir as RF,rename as CF,stat as TF,unlink as AF,writeFile as IF}from"node:fs/promises";import{join as Zi}from"node:path";function gS(e){return Zi(Tf,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function zt(e){try{let t=gS(e);if(!hS(t))return{};let n=JSON.parse(await EF(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function He(e,t){await SF(Tf,{recursive:!0,mode:448});let n=gS(e),r=`${n}.tmp`;await IF(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await CF(r,n)}async function yS(e=7*24*60*60*1e3,t=Date.now()){await mS(Tf,".json",e,t),await mS(Af,".jsonl",e,t)}async function mS(e,t,n,r){try{if(!hS(e))return;for(let o of await RF(e)){if(!o.endsWith(t))continue;let i=Zi(e,o);try{let a=await TF(i);r-a.mtimeMs>n&&await AF(i)}catch{}}}catch{}}var Ie,Tf,Af,ft=w(()=>{"use strict";qe();Ie=Zi(Ae,"guard"),Tf=Zi(Ie,"sessions"),Af=Zi(Ie,"triggers");s(gS,"sessionFile");s(zt,"loadGuardSession");s(He,"saveGuardSession");s(yS,"sweepOldGuardSessions");s(mS,"sweepDir")});import{existsSync as NF}from"node:fs";import{appendFile as OF,mkdir as DF,open as PF}from"node:fs/promises";import{join as MF}from"node:path";async function ne(e){try{await DF(Ie,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
875
- `;await OF(br,t,{mode:384})}catch{}}async function _S(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(!NF(br))return t;let n=await PF(br,"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(`
876
- `);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 br,Jt=w(()=>{"use strict";ft();br=MF(Ie,"events.jsonl");s(ne,"appendGuardEvent");s(_S,"readGuardEventCounts")});var SS={};Q(SS,{BRIEFING_CACHE_FILE:()=>Eo,UNAVAILABLE_LINE:()=>vS,carriesBriefing:()=>kS,deliverSessionBriefing:()=>Bc,formatInjection:()=>xS,resolveBriefingInjection:()=>Ro,runGuardInject:()=>WF,runsUnderCursor:()=>cS});import{existsSync as $F}from"node:fs";import{mkdir as LF,readFile as jF,rename as FF,writeFile as HF}from"node:fs/promises";import{homedir as bS}from"node:os";import{dirname as UF,join as BF}from"node:path";async function Ro(e,t,n={}){let r=n.nowMs??Date.now(),o=n.cacheFile??Eo,i=n.fetcher??hr,a=await JF(o),c=a!==null&&a.format===wS&&r-Date.parse(a.fetched_at)<KF&&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:XF(),projectKey:e,bridgeVersion:H,timeoutMs:GF});if(u!==null){let p=d;return await YF(o,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:wS,...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 WF(){try{if(ye().mode==="off")return 0;let t=await V();return uS(pS(bS(),zF(t)))||$e(Le(bS(),process.env,process.platform)).enabled&&!(ee()?.declined_hooks??[]).includes(Y)?0:await Bc("guard",t)}catch{return 0}}function kS(e){return e==="resume"||e==="fork"}function VF(e,t){let n=$c(e,t);if(n===null)return re();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:xt(n)}function qF(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Bc(e,t,n={}){let r=n.env??process.env,o=pe(t,r,n.readConfig??ee,n.hostHint??null);if(!Re(o,{kind:"text",event:"SessionStart"}))return 0;let i=n.write??qF,a=s(async k=>{let v=ge(o,{kind:"text",event:"SessionStart",text:k});v!==null&&await i(v)},"write"),c=Cn(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 yS();let d=typeof t.source=="string"?t.source:"startup";if(kS(d)){let k=await zt(l);return await He(l,{...k,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??(()=>VF(o,r)))(),m=o.host==="codex"&&n.inject?.fetcher===void 0?{...n.inject,fetcher:s(k=>hr({...k,clientFamily:"codex"}),"fetcher")}:n.inject,g=await Ro(f,u,m),y=await zt(l);if(g.text===null)return await He(l,{...y,inject_failed:!0}),await ne({event:"inject_fail",session_id:l,cwd:p,project_key:f??void 0,...e==="core"?{detail:"core"}:{},...c}),await a(vS),0;let _=xS(g.text,g.via,g.conventions??null,e);await a(_.text),await He(l,{...y,injected:!0});let b=_.complete?g.via:`${g.via}+budget`;return await ne({event:"inject_ok",session_id:l,cwd:p,project_key:f??void 0,detail:e==="core"?`core:${b}`:b,...c}),0}function zF(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 xS(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 Hc(a,n,e)}async function JF(e){try{if(!$F(e))return null;let t=JSON.parse(await jF(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 YF(e,t){try{await LF(UF(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await HF(n,JSON.stringify(t,null,2),{mode:384}),await FF(n,e)}catch{}}function XF(){try{return ce()}catch{return null}}var Eo,KF,wS,GF,vS,wr=w(()=>{"use strict";Ve();oe();Ee();Fe();Lc();go();he();me();Ue();Ct();Uc();Jt();ft();En();Eo=BF(Ie,"briefing-cache.json"),KF=12*60*60*1e3,wS=2,GF=3e3;s(Ro,"resolveBriefingInjection");s(WF,"runGuardInject");s(kS,"carriesBriefing");s(VF,"sessionProjectKey");s(qF,"writeStdout");s(Bc,"deliverSessionBriefing");vS=`[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.
877
- `;s(zF,"projectDirOf");s(xS,"formatInjection");s(JF,"readCache");s(YF,"writeCache");s(XF,"safeDeviceId")});var OS={};Q(OS,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>IS,AGENTS_MD_REFRESH_INTERVAL_MS:()=>TS,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>AS,AGENTS_MD_REFRESH_STATE_FILE:()=>CS,gitToplevel:()=>Kc,isSet:()=>Qi,isWithin:()=>NS,loadProjectConventions:()=>kr,realpathOrResolve:()=>Nf,refreshAgentsMdConventions:()=>If,refreshAgentsMdForSession:()=>d1});import{execFileSync as ZF}from"node:child_process";import{createHash as QF}from"node:crypto";import{mkdir as e1,readFile as t1,realpath as n1,rename as r1,writeFile as o1}from"node:fs/promises";import{dirname as i1,isAbsolute as s1,join as RS,relative as a1,resolve as c1}from"node:path";async function kr(e,t,n){if(e===null)return null;let r=n.clientFamily??"mcp-bridge",o=await Ro(t,e,{fetcher:n.allowFetch?i=>hr({...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 If(e,t){let n=t.err??(r=>process.stderr.write(`${r}
878
- `));try{let r=t.env??process.env;if(u1(r))return{status:"skipped",reason:"opt-out"};let o=t.cwd??process.cwd(),i=(t.gitToplevel??Kc)(o);if(i===null)return Of(r)&&n(`maind: AGENTS.md team block skipped \u2014 ${o} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Nf(i),c=[];for(let E of await(t.findRoots??Da)(o)){let S=await Nf(E);NS(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=RS(E,"AGENTS.md"),R=await q(S);if(R!==null&&Hk(R)){l=S,d=R;break}}if(l===null||d===null)return Of(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??CS,f=await f1(p),m=p1(l),g=f.roots[m]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<TS)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((E,S)=>kr(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}),k=Za(d,b,void 0,{replaceOnly:!0});if(k.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(k.outcome==="no-header"||k.outcome==="inserted")return{status:"skipped",reason:"no-team-block"};if(k.changed&&await B(l,k.next),await m1(p,f,m,u),!k.changed)return{status:"unchanged",file:l};let v=Fk(b);return n(`maind: AGENTS.md team conventions block refreshed (${v} conventions)`),{status:"refreshed",file:l,conventions:v}}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 d1(e,t){let n=await If(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}
879
- `)),i;try{i=await t.listRoots()}catch{i=null}if(i===null||i.length===0)return Of(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 If(e,{...t,cwd:l,projectKey:(t.projectKeyFor??xt)(l)??t.projectKey});ES(d)>ES(c)&&(c=d)}return c}function ES(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function Kc(e){try{let t=ZF("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 NS(e,t){let n=a1(t,e);return n===""||!n.startsWith("..")&&!s1(n)}async function Nf(e){try{return await n1(e)}catch{return c1(e)}}function u1(e){return Qi(e[AS])}function Of(e){return Qi(e[IS])}function Qi(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function p1(e){return QF("sha256").update(e).digest("hex")}async function f1(e){let t={version:1,roots:{}};try{let n=JSON.parse(await t1(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 m1(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<l1&&(o[a]=c)}o[n]={checked_at:new Date(r).toISOString()},await e1(i1(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;await o1(i,JSON.stringify({version:1,roots:o},null,2),{mode:384}),await r1(i,e)}var CS,TS,AS,IS,l1,Gc=w(()=>{"use strict";En();wr();ft();lo();se();dp();me();Ue();CS=RS(Ie,"agents-md-refresh.json"),TS=12*60*60*1e3,AS="MAIND_NO_AGENTS_MD_REFRESH",IS="MAIND_DEBUG",l1=30*24*60*60*1e3;s(kr,"loadProjectConventions");s(If,"refreshAgentsMdConventions");s(d1,"refreshAgentsMdForSession");s(ES,"rank");s(Kc,"gitToplevel");s(NS,"isWithin");s(Nf,"realpathOrResolve");s(u1,"isOptedOut");s(Of,"isDebug");s(Qi,"isSet");s(p1,"fileKey");s(f1,"readState");s(m1,"writeState")});var $f={};Q($f,{REFRESH_RULES_USAGE:()=>Wc,RULES_REFRESH_INTERVAL_MS:()=>DS,RULES_REFRESH_OPT_OUT_ENV:()=>Df,RULES_REFRESH_STATE_FILE:()=>Pf,recordRulesCheck:()=>qc,refreshRulesForSession:()=>A1,refreshUserRules:()=>Mf,repoDisplayName:()=>PS,repoIdentity:()=>Co,runRefreshRules:()=>I1});import{execFileSync as h1}from"node:child_process";import{createHash as g1}from"node:crypto";import{existsSync as y1,statSync as _1}from"node:fs";import{mkdir as b1,readFile as w1,rename as k1,writeFile as v1}from"node:fs/promises";import{homedir as x1}from"node:os";import{basename as S1,dirname as E1,join as R1,resolve as C1}from"node:path";function Co(e){let t=Kc(e);if(t===null)return{root:null,name:null,projectKey:null,key:"none"};let n=null;try{n=h1("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:un(n);return{root:t,name:PS(n,t),projectKey:r,key:r??rp(`path:${t}`)}}function PS(e,t){let n=e===null?null:op(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 S1(t)}async function Mf(e,t={}){let n=t.env??process.env;if(Qi(n[Df]))return{outcome:"opted_out",repo:null,files:[]};try{let r=t.homeDir??x1(),o=(t.identity??Co)(e),i=t.channels??fr(Bt({projectRoot:e,homeDir:r,platform:process.platform,env:n}),de),a=t.only===void 0?i:i.filter(k=>t.only?.includes(k.id)),c=[];for(let k of a){let v=await q(k.path);v!==null&&_o(v)&&c.push({channel:k,raw:v})}if(c.length===0)return{outcome:"no_channels",repo:o.name,files:[]};let l=t.nowMs??Date.now(),d=t.stateFile??Pf,u=await MS(d),p=c.filter(({channel:k,raw:v})=>{if(t.force===!0)return!0;let E=u.files[Vc(k.path)];if(E===void 0||E.repo!==o.key)return!0;let S=Date.parse(E.checked_at);return Number.isNaN(S)||l-S>=DS?!0:E.content!==Bi(v)});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??((k,v)=>kr(v,k,{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:k,raw:v}of p){let E=ff(k,{repo:o.name,conventions:g},{nowMs:l,bridgeVersion:t.bridgeVersion??H});try{if(yo(v)===yo(E)){b++,u.files[Vc(k.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Bi(v)};continue}let S=await q(k.path);if(S===null||!_o(S))continue;await B(k.path,E),y.push(k.path),u.files[Vc(k.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Bi(E)}}catch(S){_.push(`${k.path}: ${S instanceof Error?S.message:String(S)}`)}}return await $S(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 qc(e,t,n,r={}){try{let o=r.nowMs??Date.now(),i=r.stateFile??Pf,a=await MS(i);a.files[Vc(e)]={repo:n,checked_at:new Date(o).toISOString(),content:Bi(t)},await $S(i,a,o)}catch{}}async function A1(e,t={}){let n=sx(e);if(n===null)return null;let r=t.err??(o=>process.stderr.write(`${o}
880
- `));try{let o=t.identity??Co,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 Mf(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 I1(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(Wc),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
874
+ `,complete:l}}var jc,Uc=w(()=>{"use strict";jc=s(e=>Buffer.byteLength(e,"utf8"),"bytes");s(Fc,"extractConventionsBlock");s(EF,"briefingSections");s(Hc,"composeInjection")});import{existsSync as gS}from"node:fs";import{mkdir as RF,readFile as CF,readdir as TF,rename as AF,stat as IF,unlink as NF,writeFile as OF}from"node:fs/promises";import{join as Zi}from"node:path";function yS(e){return Zi(Af,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function zt(e){try{let t=yS(e);if(!gS(t))return{};let n=JSON.parse(await CF(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function He(e,t){await RF(Af,{recursive:!0,mode:448});let n=yS(e),r=`${n}.tmp`;await OF(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await AF(r,n)}async function _S(e=7*24*60*60*1e3,t=Date.now()){await hS(Af,".json",e,t),await hS(If,".jsonl",e,t)}async function hS(e,t,n,r){try{if(!gS(e))return;for(let o of await TF(e)){if(!o.endsWith(t))continue;let i=Zi(e,o);try{let a=await IF(i);r-a.mtimeMs>n&&await NF(i)}catch{}}}catch{}}var Ie,Af,If,ft=w(()=>{"use strict";qe();Ie=Zi(Ae,"guard"),Af=Zi(Ie,"sessions"),If=Zi(Ie,"triggers");s(yS,"sessionFile");s(zt,"loadGuardSession");s(He,"saveGuardSession");s(_S,"sweepOldGuardSessions");s(hS,"sweepDir")});import{existsSync as DF}from"node:fs";import{appendFile as PF,mkdir as MF,open as $F}from"node:fs/promises";import{join as LF}from"node:path";async function re(e){try{await MF(Ie,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
875
+ `;await PF(br,t,{mode:384})}catch{}}async function bS(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(!DF(br))return t;let n=await $F(br,"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(`
876
+ `);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 br,Jt=w(()=>{"use strict";ft();br=LF(Ie,"events.jsonl");s(re,"appendGuardEvent");s(bS,"readGuardEventCounts")});var ES={};ee(ES,{BRIEFING_CACHE_FILE:()=>Eo,UNAVAILABLE_LINE:()=>xS,carriesBriefing:()=>vS,deliverSessionBriefing:()=>Bc,formatInjection:()=>SS,resolveBriefingInjection:()=>Ro,runGuardInject:()=>qF,runsUnderCursor:()=>lS});import{existsSync as jF}from"node:fs";import{mkdir as FF,readFile as HF,rename as UF,writeFile as BF}from"node:fs/promises";import{homedir as wS}from"node:os";import{dirname as KF,join as GF}from"node:path";async function Ro(e,t,n={}){let r=n.nowMs??Date.now(),o=n.cacheFile??Eo,i=n.fetcher??hr,a=await XF(o),c=a!==null&&a.format===kS&&r-Date.parse(a.fetched_at)<WF&&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:QF(),projectKey:e,bridgeVersion:H,timeoutMs:VF});if(u!==null){let p=d;return await ZF(o,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:kS,...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 qF(){try{if(ye().mode==="off")return 0;let t=await V();return pS(fS(wS(),YF(t)))||$e(Le(wS(),process.env,process.platform)).enabled&&!(te()?.declined_hooks??[]).includes(Y)?0:await Bc("guard",t)}catch{return 0}}function vS(e){return e==="resume"||e==="fork"}function zF(e,t){let n=$c(e,t);if(n===null)return oe();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:xt(n)}function JF(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Bc(e,t,n={}){let r=n.env??process.env,o=pe(t,r,n.readConfig??te,n.hostHint??null);if(!Re(o,{kind:"text",event:"SessionStart"}))return 0;let i=n.write??JF,a=s(async k=>{let v=ge(o,{kind:"text",event:"SessionStart",text:k});v!==null&&await i(v)},"write"),c=Cn(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 _S();let d=typeof t.source=="string"?t.source:"startup";if(vS(d)){let k=await zt(l);return await He(l,{...k,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??(()=>zF(o,r)))(),m=o.host==="codex"&&n.inject?.fetcher===void 0?{...n.inject,fetcher:s(k=>hr({...k,clientFamily:"codex"}),"fetcher")}:n.inject,g=await Ro(f,u,m),y=await zt(l);if(g.text===null)return await He(l,{...y,inject_failed:!0}),await re({event:"inject_fail",session_id:l,cwd:p,project_key:f??void 0,...e==="core"?{detail:"core"}:{},...c}),await a(xS),0;let _=SS(g.text,g.via,g.conventions??null,e);await a(_.text),await He(l,{...y,injected:!0});let b=_.complete?g.via:`${g.via}+budget`;return await re({event:"inject_ok",session_id:l,cwd:p,project_key:f??void 0,detail:e==="core"?`core:${b}`:b,...c}),0}function YF(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 SS(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 Hc(a,n,e)}async function XF(e){try{if(!jF(e))return null;let t=JSON.parse(await HF(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 ZF(e,t){try{await FF(KF(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await BF(n,JSON.stringify(t,null,2),{mode:384}),await UF(n,e)}catch{}}function QF(){try{return le()}catch{return null}}var Eo,WF,kS,VF,xS,wr=w(()=>{"use strict";Ve();ie();Ee();Fe();Lc();go();he();me();Ue();Ct();Uc();Jt();ft();En();Eo=GF(Ie,"briefing-cache.json"),WF=12*60*60*1e3,kS=2,VF=3e3;s(Ro,"resolveBriefingInjection");s(qF,"runGuardInject");s(vS,"carriesBriefing");s(zF,"sessionProjectKey");s(JF,"writeStdout");s(Bc,"deliverSessionBriefing");xS=`[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.
877
+ `;s(YF,"projectDirOf");s(SS,"formatInjection");s(XF,"readCache");s(ZF,"writeCache");s(QF,"safeDeviceId")});var DS={};ee(DS,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>NS,AGENTS_MD_REFRESH_INTERVAL_MS:()=>AS,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>IS,AGENTS_MD_REFRESH_STATE_FILE:()=>TS,gitToplevel:()=>Kc,isSet:()=>Qi,isWithin:()=>OS,loadProjectConventions:()=>kr,realpathOrResolve:()=>Of,refreshAgentsMdConventions:()=>Nf,refreshAgentsMdForSession:()=>p1});import{execFileSync as e1}from"node:child_process";import{createHash as t1}from"node:crypto";import{mkdir as n1,readFile as r1,realpath as o1,rename as i1,writeFile as s1}from"node:fs/promises";import{dirname as a1,isAbsolute as c1,join as CS,relative as l1,resolve as d1}from"node:path";async function kr(e,t,n){if(e===null)return null;let r=n.clientFamily??"mcp-bridge",o=await Ro(t,e,{fetcher:n.allowFetch?i=>hr({...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 Nf(e,t){let n=t.err??(r=>process.stderr.write(`${r}
878
+ `));try{let r=t.env??process.env;if(f1(r))return{status:"skipped",reason:"opt-out"};let o=t.cwd??process.cwd(),i=(t.gitToplevel??Kc)(o);if(i===null)return Df(r)&&n(`maind: AGENTS.md team block skipped \u2014 ${o} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Of(i),c=[];for(let E of await(t.findRoots??Da)(o)){let S=await Of(E);OS(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=CS(E,"AGENTS.md"),R=await q(S);if(R!==null&&Uk(R)){l=S,d=R;break}}if(l===null||d===null)return Df(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??TS,f=await h1(p),m=m1(l),g=f.roots[m]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<AS)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((E,S)=>kr(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}),k=Za(d,b,void 0,{replaceOnly:!0});if(k.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(k.outcome==="no-header"||k.outcome==="inserted")return{status:"skipped",reason:"no-team-block"};if(k.changed&&await B(l,k.next),await g1(p,f,m,u),!k.changed)return{status:"unchanged",file:l};let v=Hk(b);return n(`maind: AGENTS.md team conventions block refreshed (${v} conventions)`),{status:"refreshed",file:l,conventions:v}}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 p1(e,t){let n=await Nf(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}
879
+ `)),i;try{i=await t.listRoots()}catch{i=null}if(i===null||i.length===0)return Df(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 Nf(e,{...t,cwd:l,projectKey:(t.projectKeyFor??xt)(l)??t.projectKey});RS(d)>RS(c)&&(c=d)}return c}function RS(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function Kc(e){try{let t=e1("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 OS(e,t){let n=l1(t,e);return n===""||!n.startsWith("..")&&!c1(n)}async function Of(e){try{return await o1(e)}catch{return d1(e)}}function f1(e){return Qi(e[IS])}function Df(e){return Qi(e[NS])}function Qi(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function m1(e){return t1("sha256").update(e).digest("hex")}async function h1(e){let t={version:1,roots:{}};try{let n=JSON.parse(await r1(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 g1(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<u1&&(o[a]=c)}o[n]={checked_at:new Date(r).toISOString()},await n1(a1(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;await s1(i,JSON.stringify({version:1,roots:o},null,2),{mode:384}),await i1(i,e)}var TS,AS,IS,NS,u1,Gc=w(()=>{"use strict";En();wr();ft();lo();ae();dp();me();Ue();TS=CS(Ie,"agents-md-refresh.json"),AS=12*60*60*1e3,IS="MAIND_NO_AGENTS_MD_REFRESH",NS="MAIND_DEBUG",u1=30*24*60*60*1e3;s(kr,"loadProjectConventions");s(Nf,"refreshAgentsMdConventions");s(p1,"refreshAgentsMdForSession");s(RS,"rank");s(Kc,"gitToplevel");s(OS,"isWithin");s(Of,"realpathOrResolve");s(f1,"isOptedOut");s(Df,"isDebug");s(Qi,"isSet");s(m1,"fileKey");s(h1,"readState");s(g1,"writeState")});var Lf={};ee(Lf,{REFRESH_RULES_USAGE:()=>Wc,RULES_REFRESH_INTERVAL_MS:()=>PS,RULES_REFRESH_OPT_OUT_ENV:()=>Pf,RULES_REFRESH_STATE_FILE:()=>Mf,recordRulesCheck:()=>qc,refreshRulesForSession:()=>N1,refreshUserRules:()=>$f,repoDisplayName:()=>MS,repoIdentity:()=>Co,runRefreshRules:()=>O1});import{execFileSync as y1}from"node:child_process";import{createHash as _1}from"node:crypto";import{existsSync as b1,statSync as w1}from"node:fs";import{mkdir as k1,readFile as v1,rename as x1,writeFile as S1}from"node:fs/promises";import{homedir as E1}from"node:os";import{basename as R1,dirname as C1,join as T1,resolve as A1}from"node:path";function Co(e){let t=Kc(e);if(t===null)return{root:null,name:null,projectKey:null,key:"none"};let n=null;try{n=y1("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:un(n);return{root:t,name:MS(n,t),projectKey:r,key:r??rp(`path:${t}`)}}function MS(e,t){let n=e===null?null:op(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 R1(t)}async function $f(e,t={}){let n=t.env??process.env;if(Qi(n[Pf]))return{outcome:"opted_out",repo:null,files:[]};try{let r=t.homeDir??E1(),o=(t.identity??Co)(e),i=t.channels??fr(Bt({projectRoot:e,homeDir:r,platform:process.platform,env:n}),de),a=t.only===void 0?i:i.filter(k=>t.only?.includes(k.id)),c=[];for(let k of a){let v=await q(k.path);v!==null&&_o(v)&&c.push({channel:k,raw:v})}if(c.length===0)return{outcome:"no_channels",repo:o.name,files:[]};let l=t.nowMs??Date.now(),d=t.stateFile??Mf,u=await $S(d),p=c.filter(({channel:k,raw:v})=>{if(t.force===!0)return!0;let E=u.files[Vc(k.path)];if(E===void 0||E.repo!==o.key)return!0;let S=Date.parse(E.checked_at);return Number.isNaN(S)||l-S>=PS?!0:E.content!==Bi(v)});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??((k,v)=>kr(v,k,{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:k,raw:v}of p){let E=mf(k,{repo:o.name,conventions:g},{nowMs:l,bridgeVersion:t.bridgeVersion??H});try{if(yo(v)===yo(E)){b++,u.files[Vc(k.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Bi(v)};continue}let S=await q(k.path);if(S===null||!_o(S))continue;await B(k.path,E),y.push(k.path),u.files[Vc(k.path)]={repo:o.key,checked_at:new Date(l).toISOString(),content:Bi(E)}}catch(S){_.push(`${k.path}: ${S instanceof Error?S.message:String(S)}`)}}return await LS(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 qc(e,t,n,r={}){try{let o=r.nowMs??Date.now(),i=r.stateFile??Mf,a=await $S(i);a.files[Vc(e)]={repo:n,checked_at:new Date(o).toISOString(),content:Bi(t)},await LS(i,a,o)}catch{}}async function N1(e,t={}){let n=ax(e);if(n===null)return null;let r=t.err??(o=>process.stderr.write(`${o}
880
+ `));try{let o=t.identity??Co,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 $f(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 O1(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(Wc),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
881
881
  ${Wc}`),2;o=p}else return r(`refresh-rules: unknown argument ${u}
882
- ${Wc}`),2}}let c=C1(t.cwd??process.cwd(),o??".");if(!O1(c))return r(`refresh-rules: ${c} is not a directory
883
- `),2;let l=await Mf(c,{...t,force:a});return n(i?JSON.stringify({outcome:l.outcome,repo:l.repo,files:l.files})+`
884
- `:N1(l)+`
882
+ ${Wc}`),2}}let c=A1(t.cwd??process.cwd(),o??".");if(!P1(c))return r(`refresh-rules: ${c} is not a directory
883
+ `),2;let l=await $f(c,{...t,force:a});return n(i?JSON.stringify({outcome:l.outcome,repo:l.repo,files:l.files})+`
884
+ `:D1(l)+`
885
885
  `),l.outcome==="failed"&&i&&r(`refresh-rules: ${l.error??"failed"}
886
- `),l.outcome==="failed"?1:0}function N1(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: ${Df} is set \u2014 nothing refreshed`;case"failed":return`maind: rule files not refreshed \u2014 ${e.error??"unknown error"}`}}function O1(e){try{return y1(e)&&_1(e).isDirectory()}catch{return!1}}function Vc(e){return g1("sha256").update(e).digest("hex")}async function MS(e){let t={version:1,files:{}};try{let n=JSON.parse(await w1(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 $S(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<T1&&(r[i]=a)}await b1(E1(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await v1(o,JSON.stringify({version:1,files:r},null,2),{mode:384}),await k1(o,e)}var Df,Pf,DS,T1,Wc,zc=w(()=>{"use strict";Gc();oe();ft();se();et();yc();me();Ue();Df="MAIND_NO_RULES_REFRESH",Pf=R1(Ie,"rules-refresh.json"),DS=12*60*60*1e3,T1=30*24*60*60*1e3;s(Co,"repoIdentity");s(PS,"repoDisplayName");s(Mf,"refreshUserRules");s(qc,"recordRulesCheck");s(A1,"refreshRulesForSession");Wc=["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(`
887
- `);s(I1,"runRefreshRules");s(N1,"humanLine");s(O1,"isDirectory");s(Vc,"fileKey");s(MS,"readState");s($S,"writeState")});import*as LS from"node:os";async function jS(e){let t=Date.now(),n;try{n=Qw(e)}catch(x){if(x instanceof tt)return process.stderr.write(`error: ${x.message}
888
- `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw x}if(n.help)return ek(),0;for(let x of n.notices)process.stdout.write(`${x}
889
- `);let o=!!process.stdin.isTTY&&!n.nonInteractive,i=LS.homedir();if(i.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
890
- `),2;if(n.hooksOnly)return F1({homeDir:i,isInteractive:o,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:Bt({projectRoot:i,homeDir:i,platform:process.platform,env:process.env}),probe:de,noRules:n.noRules,cwd:process.cwd()});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let x=await Da(process.cwd());if(x.length===0)a=await ik(process.cwd());else if(x.length===1||!n.team)a=x[0];else{let T=await ak(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.
886
+ `),l.outcome==="failed"?1:0}function D1(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: ${Pf} is set \u2014 nothing refreshed`;case"failed":return`maind: rule files not refreshed \u2014 ${e.error??"unknown error"}`}}function P1(e){try{return b1(e)&&w1(e).isDirectory()}catch{return!1}}function Vc(e){return _1("sha256").update(e).digest("hex")}async function $S(e){let t={version:1,files:{}};try{let n=JSON.parse(await v1(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 LS(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<I1&&(r[i]=a)}await k1(C1(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await S1(o,JSON.stringify({version:1,files:r},null,2),{mode:384}),await x1(o,e)}var Pf,Mf,PS,I1,Wc,zc=w(()=>{"use strict";Gc();ie();ft();ae();et();yc();me();Ue();Pf="MAIND_NO_RULES_REFRESH",Mf=T1(Ie,"rules-refresh.json"),PS=12*60*60*1e3,I1=30*24*60*60*1e3;s(Co,"repoIdentity");s(MS,"repoDisplayName");s($f,"refreshUserRules");s(qc,"recordRulesCheck");s(N1,"refreshRulesForSession");Wc=["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(`
887
+ `);s(O1,"runRefreshRules");s(D1,"humanLine");s(P1,"isDirectory");s(Vc,"fileKey");s($S,"readState");s(LS,"writeState")});import*as jS from"node:os";async function FS(e){let t=Date.now(),n;try{n=ek(e)}catch(x){if(x instanceof tt)return process.stderr.write(`error: ${x.message}
888
+ `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw x}if(n.help)return tk(),0;for(let x of n.notices)process.stdout.write(`${x}
889
+ `);let o=!!process.stdin.isTTY&&!n.nonInteractive,i=jS.homedir();if(i.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
890
+ `),2;if(n.hooksOnly)return U1({homeDir:i,isInteractive:o,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:Bt({projectRoot:i,homeDir:i,platform:process.platform,env:process.env}),probe:de,noRules:n.noRules,cwd:process.cwd()});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let x=await Da(process.cwd());if(x.length===0)a=await sk(process.cwd());else if(x.length===1||!n.team)a=x[0];else{let T=await ck(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.
891
891
  `);for(let D of x)process.stderr.write(` candidate: ${D}
892
- `);return 2}a=T}}let c=new Ei,l=(process.env.MAIND_MCP_URL??"").trim()||D1;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
892
+ `);return 2}a=T}}let c=new Ei,l=(process.env.MAIND_MCP_URL??"").trim()||M1;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
893
893
  `),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)"}
894
894
  `),process.stdout.write(` \u2014 mcp endpoint: ${l}
895
895
 
896
- `);let d=Bt({projectRoot:a,homeDir:i,platform:process.platform,env:process.env,bridgeEntry:ie()}),u=Si(d);if(u=Jw(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.
896
+ `);let d=Bt({projectRoot:a,homeDir:i,platform:process.platform,env:process.env,bridgeEntry:se()}),u=Si(d);if(u=Yw(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.
897
897
  `:`error: no client targets selected (did you skip all of them?)
898
- `),c.print(process.stdout),2;let p=await ux({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(`
898
+ `),c.print(process.stdout),2;let p=await px({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(`
899
899
  pairing failed: ${p.result.detail??"unknown"}
900
900
  Skipping remaining steps.
901
- `),c.print(process.stdout),2;let f=$e(Le(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=uk({target:x,explicitFamily:n.client,probe:de});if(T!==null){c.add(T);continue}let D=Uw({mcpUrl:l,clientFamily:x.clientFamilyEnv}),j;x.kind==="json"?j=await hk(x,D,n.dryRun):j=await Mk(x,D,n.dryRun),c.add(j)}let m=Co(a),g=HS(()=>kr(p.apiKey,m.projectKey,{allowFetch:!n.dryRun,clientFamily:"mcp-bridge"}));c.add(await Np(i,n.dryRun)),n.team?c.add(await qk({projectRoot:a,conventions:g,dryRun:n.dryRun})):c.add({target:P1,action:"skip",status:"skipped",detail:$1});let y={homeDir:i,isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},_=await FS(y,f);for(let x of _)c.add(x);let b=Gv(a,_);b!==null&&c.add(b),c.add(await af({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 k=u.some(x=>x.clientFamilyEnv==="cursor");if(k){let x=await uf({...y,explicit:n.client==="cursor",presence:{ctx:d,probe:de}});for(let T of x)c.add(T)}(n.client===null||n.client==="codex")&&c.add(await pf({...y,skipCodex:n.skipCodex,explicit:n.client==="codex",presence:{ctx:d,probe:de}}));let v=fr(d,de).filter(x=>n.client===null||x.family===n.client);if(v.length>0){let x=await mf({homeDir:i,isInteractive:o,full:n.full,skip:n.noRules,dryRun:n.dryRun,out:process.stdout,explicitFamily:n.client,probe:de,content:s(async()=>({repo:m.name,conventions:await g()}),"content"),onChecked:s((T,D)=>qc(T,D,m.key),"onChecked")},v);for(let T of x)c.add(T)}!n.team&&k&&(n.client==="cursor"||De(Ut(d),de))&&c.add({target:M1,action:"advise",status:"skipped",detail:L1});let E=Dc();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 fx({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(`
901
+ `),c.print(process.stdout),2;let f=$e(Le(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:ex(f)});continue}let T=pk({target:x,explicitFamily:n.client,probe:de});if(T!==null){c.add(T);continue}let D=Bw({mcpUrl:l,clientFamily:x.clientFamilyEnv}),j;x.kind==="json"?j=await gk(x,D,n.dryRun):j=await $k(x,D,n.dryRun),c.add(j)}let m=Co(a),g=US(()=>kr(p.apiKey,m.projectKey,{allowFetch:!n.dryRun,clientFamily:"mcp-bridge"}));c.add(await Op(i,n.dryRun)),n.team?c.add(await zk({projectRoot:a,conventions:g,dryRun:n.dryRun})):c.add({target:$1,action:"skip",status:"skipped",detail:j1});let y={homeDir:i,isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},_=await HS(y,f);for(let x of _)c.add(x);let b=Wv(a,_);b!==null&&c.add(b),c.add(await cf({isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout})),c.add(await tv({isInteractive:o,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let k=u.some(x=>x.clientFamilyEnv==="cursor");if(k){let x=await pf({...y,explicit:n.client==="cursor",presence:{ctx:d,probe:de}});for(let T of x)c.add(T)}(n.client===null||n.client==="codex")&&c.add(await ff({...y,skipCodex:n.skipCodex,explicit:n.client==="codex",presence:{ctx:d,probe:de}}));let v=fr(d,de).filter(x=>n.client===null||x.family===n.client);if(v.length>0){let x=await hf({homeDir:i,isInteractive:o,full:n.full,skip:n.noRules,dryRun:n.dryRun,out:process.stdout,explicitFamily:n.client,probe:de,content:s(async()=>({repo:m.name,conventions:await g()}),"content"),onChecked:s((T,D)=>qc(T,D,m.key),"onChecked")},v);for(let T of x)c.add(T)}!n.team&&k&&(n.client==="cursor"||De(Ut(d),de))&&c.add({target:L1,action:"advise",status:"skipped",detail:F1});let E=Dc();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 mx({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(`
902
902
  DRY RUN finished in ${R}s. No files were modified. Re-run without --dry-run to apply.
903
903
  `):process.stdout.write(`
904
904
  Finished in ${R}s. Restart your MCP client so it picks up the new server entry.
905
- `);let P=ve({entryPath:ie(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),K=P.fallbackReason===null?`${Qe(P)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${K}
905
+ `);let P=ve({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),K=P.fallbackReason===null?`${Qe(P)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${K}
906
906
  `),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.
907
- `),S}async function FS(e,t){if(t.enabled&&!e.skip)return[{target:Lf,action:"skip",status:"skipped",detail:gc(t)}];let n=await Zk(e);return e.dryRun||await Jk(Ge,n),n}function HS(e){let t=null;return()=>t??=e()}async function jf(e,t){let n=[];n.push(await Np(e.homeDir,e.dryRun)),n.push(...await uf({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(await pf({...e,skipCodex:!1,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let r=(t.identity??Co)(t.cwd),o=(t.apiKey??j1)(),i=HS(()=>kr(o,r.projectKey,{allowFetch:!e.dryRun,clientFamily:"mcp-bridge"}));return n.push(...await mf({...e,skip:t.noRules,explicitFamily:null,probe:t.probe,content:s(async()=>({repo:r.name,conventions:await i()}),"content"),onChecked:s((a,c)=>qc(a,c,r.key),"onChecked")},fr(t.ctx,t.probe))),n}function j1(){try{return z()}catch{return null}}async function F1(e,t){let n=new Ei;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
907
+ `),S}async function HS(e,t){if(t.enabled&&!e.skip)return[{target:jf,action:"skip",status:"skipped",detail:gc(t)}];let n=await Qk(e);return e.dryRun||await Yk(Ge,n),n}function US(e){let t=null;return()=>t??=e()}async function Ff(e,t){let n=[];n.push(await Op(e.homeDir,e.dryRun)),n.push(...await pf({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(await ff({...e,skipCodex:!1,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let r=(t.identity??Co)(t.cwd),o=(t.apiKey??H1)(),i=US(()=>kr(o,r.projectKey,{allowFetch:!e.dryRun,clientFamily:"mcp-bridge"}));return n.push(...await hf({...e,skip:t.noRules,explicitFamily:null,probe:t.probe,content:s(async()=>({repo:r.name,conventions:await i()}),"content"),onChecked:s((a,c)=>qc(a,c,r.key),"onChecked")},fr(t.ctx,t.probe))),n}function H1(){try{return z()}catch{return null}}async function U1(e,t){let n=new Ei;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
908
908
  `),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
909
- `);let r=$e(Le(e.homeDir,process.env,process.platform));for(let o of await FS(e,r))n.add(o);n.add(await af({isInteractive:e.isInteractive,full:e.full,skip:e.skip,dryRun:e.dryRun,out:e.out}));for(let o of await jf(e,t))n.add(o);return n.print(e.out),e.out.write(e.dryRun?`
909
+ `);let r=$e(Le(e.homeDir,process.env,process.platform));for(let o of await HS(e,r))n.add(o);n.add(await cf({isInteractive:e.isInteractive,full:e.full,skip:e.skip,dryRun:e.dryRun,out:e.out}));for(let o of await Ff(e,t))n.add(o);return n.print(e.out),e.out.write(e.dryRun?`
910
910
  DRY RUN finished. No files were modified.
911
911
  `:`
912
912
  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).
913
- `),n.exitCode()}var D1,P1,M1,$1,L1,Lf,Ff=w(()=>{"use strict";Ue();tk();nk();dp();et();St();se();io();gk();$k();Wk();zk();tc();Dp();he();tv();Bv();Wv();Jv();go();nx();yc();px();mx();Sn();Gc();oe();zc();D1="https://mcp.maind.dev/mcp",P1="repository",M1="team-option",$1="nothing written into the repository (ADR-364) \u2014 install --team writes the AGENTS.md conventions block and the project .mcp.json",L1="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(jS,"runInstall");Lf="hooks:~/.claude/settings.json";s(FS,"claudeCodeHooks");s(HS,"memo");s(jf,"setUpUserChannels");s(j1,"safeApiKey");s(F1,"runHooksOnly")});import{mkdirSync as WS,rmdirSync as VS,statSync as B1}from"node:fs";import{join as qS}from"node:path";import{setTimeout as K1}from"node:timers/promises";function zS(e){return qS(e,".maind","index-refresh.lock")}function Xc(e,t=Date.now()){let n=zS(e);try{if(t-B1(n).mtimeMs<G1)return!1;VS(n)}catch{}try{return WS(n,{recursive:!1}),!0}catch{return!1}}function es(e){try{VS(zS(e))}catch{}}async function JS(e,t,n={}){let r=n.now??Date.now,o=n.sleep??(a=>K1(a).then(()=>{})),i=r()+(n.waitMs??3e4);try{WS(qS(e,".maind"),{recursive:!0})}catch{}for(;!Xc(e,r());){if(r()>=i)return{locked:!1};await o(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{es(e)}}var G1,Hf=w(()=>{"use strict";G1=30*6e4;s(zS,"lockPath");s(Xc,"acquireLock");s(es,"releaseLock");s(JS,"withIndexLock")});import{execFile as uE}from"node:child_process";import{randomUUID as fH}from"node:crypto";function bH(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Vf.test(t)?t:fH()}function qf(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function wH(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 kH(e){return await new Promise(t=>{uE("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(vH(r))})})}function vH(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 xH(){return await new Promise(e=>{uE("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 SH(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function EH(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),o=Vf.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:o,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(i=>{Vf.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var dE,pE,mH,hH,gH,yH,_H,Vf,tl,zf=w(()=>{"use strict";Ve();dE=45e3,pE=3e4,mH=5,hH=120,gH=3e4,yH=15*6e4,_H=1500,Vf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(bH,"resolveClientSessionId");s(qf,"autoAnnounceDisabled");s(wH,"autoWorkingPathsEnabled");tl=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??ee)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??xH,this.gitBranchObject=t.gitBranchObject??kH,this.log=t.log??(o=>process.stderr.write(o+`
914
- `)),this.machineLabel=SH(r?.machine_label),this.enabled=this.projectKey!==null&&!qf(n,r),this.workingPathsEnabled=wH(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??EH(n,bH(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<dE||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<dE||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<mH||(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,_H).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(gH*2**(this.consecutiveFailures-1),yH);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:hH,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(kH,"defaultGitBranchObject");s(vH,"normalizeObjectId");s(xH,"defaultGitBranch");s(SH,"normalizeMachineLabel");s(EH,"staticIdentity")});import{mkdirSync as fE,readdirSync as yE,readFileSync as RH,renameSync as mE,statSync as CH,unlinkSync as Jf,writeFileSync as hE}from"node:fs";import{homedir as TH}from"node:os";import{join as To}from"node:path";function _E(){return To(TH(),".maind","presence")}function bE(e,t){return To(e,t)}function wE(e){let t=e.baseDir??_E(),n=bE(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{Jf(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=Cs(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};fE(n,{recursive:!0,mode:448});let m=To(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;hE(g,JSON.stringify(f),{mode:384}),mE(g,m),l(m),gE(n,a(),m)}catch{}},endSession(){try{c&&Jf(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};fE(n,{recursive:!0,mode:448});let f=To(n,`${u.sessionId}.json`),m=`${f}.tmp-${r}`;hE(m,JSON.stringify(p),{mode:384}),mE(m,f),l(f),gE(n,a(),f)}catch{}}}}function gE(e,t,n){try{for(let r of yE(e)){if(!r.endsWith(".json"))continue;let o=To(e,r);if(o!==n)try{t-CH(o).mtimeMs>AH&&Jf(o)}catch{}}}catch{}}function Sr(e,t=_E()){try{let n=bE(t,e),r=[];for(let o of yE(n))if(o.endsWith(".json"))try{let i=JSON.parse(RH(To(n,o),"utf8")),a=IH(i);a&&r.push(a)}catch{}return r.sort((o,i)=>i.written_at.localeCompare(o.written_at)),r}catch{return[]}}function IH(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=Cs(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var AH,ts=w(()=>{"use strict";Ko();AH=120*6e4;s(_E,"presenceSnapshotBaseDir");s(bE,"projectDir");s(wE,"createSnapshotStore");s(gE,"pruneStale");s(Sr,"readSnapshots");s(IH,"parseSnapshot")});import{execFileSync as UH}from"node:child_process";import{createHash as BH,randomUUID as KH}from"node:crypto";import{existsSync as GH,mkdirSync as WH,readdirSync as VH,readFileSync as xE,renameSync as qH,statSync as Xf,unlinkSync as SE,writeFileSync as zH}from"node:fs";import{homedir as JH}from"node:os";import{basename as YH,join as Tn}from"node:path";function Ao(e){return Tn(e??Tn(JH(),".maind","presence"),"identity")}function os(e,t){if(e){let n=YH(e).replace(/\.jsonl$/i,"");if(rs.test(n))return n.toLowerCase()}return t&&rs.test(t)?t.toLowerCase():null}function EE(e){let t=e.nowMs??Date.now();WH(e.dir,{recursive:!0,mode:448});let n=Tn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,o={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(xE(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}:{}};zH(r,JSON.stringify(c,null,2)+`
915
- `,{mode:384}),qH(r,n),tU(e.dir,t)}function RE(e,t,n,r=Date.now()){try{let o=Xf(Tn(e,`${t}.json`));return r-o.mtimeMs>n}catch{return!0}}function CE(e,t){try{SE(Tn(e,`${t}.json`))}catch{}}function tU(e,t){try{for(let n of VH(e))if(n.endsWith(".json"))try{let r=Xf(Tn(e,n));t-r.mtimeMs>ZH&&SE(Tn(e,n))}catch{}}catch{}}function nU(e){return TE(e)?.file??null}function TE(e){let t=Tn(e.dir,`${e.agentPid}.json`);try{if(!GH(t))return null;let n=Xf(t);if(n.mtimeMs<e.bridgeStartMs-QH)return null;let r=JSON.parse(xE(t,"utf8"));if(typeof r!="object"||r===null)return null;let o=r;return o.v!==1||typeof o.transcript_stem!="string"||!rs.test(o.transcript_stem)||typeof o.session_id!="string"||typeof o.cwd!="string"||o.agent_pid!==e.agentPid||!rU(o.cwd,e.cwd)?null:{file:o,mtimeMs:n.mtimeMs}}catch{return null}}function vE(e){return e.replace(/\/+$/,"")}function rU(e,t){let n=vE(e),r=vE(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function oU(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=BH("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 iU(e){if(process.platform==="win32")return null;try{let t=UH("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function sU(){try{return ce()}catch{return null}}var rs,XH,ZH,QH,eU,nl,rl=w(()=>{"use strict";oe();rs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,XH=8,ZH=48*60*6e4,QH=6e4,eU="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(Ao,"identityDirPath");s(os,"transcriptStemOf");s(EE,"writeAgentIdentityFile");s(RE,"identityFileStale");s(CE,"deleteAgentIdentityFile");s(tU,"pruneIdentityDir");s(nU,"readAgentIdentityFile");s(TE,"readAgentIdentityEntry");s(vE,"normDir");s(rU,"sameSessionTree");s(oU,"uuidV5");s(iU,"processStartTime");nl=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??Ao(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=rs.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??sU)(),i=(t.ppidStart??iU)(this.agentPid);if(o!==null&&i!==null&&t.projectKey!==null){this.id=oU(`${o}|${this.agentPid}|${i}|${t.projectKey}`,eU),this.source="derived";return}this.id=KH(),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(!rs.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>XH&&this.aliases.shift())}activityAtMs(){return TE({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 nU({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(sU,"defaultDeviceId")});import{applyEdits as yU,modify as _U,parse as bU}from"jsonc-parser";function em(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function OE(e){return em(e)&&typeof e.command=="string"}function tm(e){if(e===null||e.trim().length===0)return[];let t=[],n=bU(e,t,{allowTrailingComma:!0});if(t.length>0||!em(n))return[];let r=[];return em(n.mcpServers)&&OE(n.mcpServers.maind)&&r.push(["mcpServers","maind"]),OE(n.maind)&&r.push(["maind"]),r}function DE(e,t){let n=tm(e);if(e===null||n.length===0)return null;let r=e;for(let o of n)r=yU(r,_U(r,o,void 0,{}));return{file:t,raw:e,next:r,removed:n}}function PE(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.
913
+ `),n.exitCode()}var M1,$1,L1,j1,F1,jf,Hf=w(()=>{"use strict";Ue();nk();rk();dp();et();St();ae();io();yk();Lk();Vk();Jk();tc();Pp();he();nv();Kv();Vv();Yv();go();rx();yc();fx();hx();Sn();Gc();ie();zc();M1="https://mcp.maind.dev/mcp",$1="repository",L1="team-option",j1="nothing written into the repository (ADR-364) \u2014 install --team writes the AGENTS.md conventions block and the project .mcp.json",F1="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(FS,"runInstall");jf="hooks:~/.claude/settings.json";s(HS,"claudeCodeHooks");s(US,"memo");s(Ff,"setUpUserChannels");s(H1,"safeApiKey");s(U1,"runHooksOnly")});import{mkdirSync as VS,rmdirSync as qS,statSync as G1}from"node:fs";import{join as zS}from"node:path";import{setTimeout as W1}from"node:timers/promises";function JS(e){return zS(e,".maind","index-refresh.lock")}function Xc(e,t=Date.now()){let n=JS(e);try{if(t-G1(n).mtimeMs<V1)return!1;qS(n)}catch{}try{return VS(n,{recursive:!1}),!0}catch{return!1}}function es(e){try{qS(JS(e))}catch{}}async function YS(e,t,n={}){let r=n.now??Date.now,o=n.sleep??(a=>W1(a).then(()=>{})),i=r()+(n.waitMs??3e4);try{VS(zS(e,".maind"),{recursive:!0})}catch{}for(;!Xc(e,r());){if(r()>=i)return{locked:!1};await o(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{es(e)}}var V1,Uf=w(()=>{"use strict";V1=30*6e4;s(JS,"lockPath");s(Xc,"acquireLock");s(es,"releaseLock");s(YS,"withIndexLock")});import{execFile as pE}from"node:child_process";import{randomUUID as hH}from"node:crypto";function kH(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return qf.test(t)?t:hH()}function zf(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function vH(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 xH(e){return await new Promise(t=>{pE("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(SH(r))})})}function SH(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 EH(){return await new Promise(e=>{pE("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 RH(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function CH(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),o=qf.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:o,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(i=>{qf.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var uE,fE,gH,yH,_H,bH,wH,qf,tl,Jf=w(()=>{"use strict";Ve();uE=45e3,fE=3e4,gH=5,yH=120,_H=3e4,bH=15*6e4,wH=1500,qf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(kH,"resolveClientSessionId");s(zf,"autoAnnounceDisabled");s(vH,"autoWorkingPathsEnabled");tl=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??te)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??EH,this.gitBranchObject=t.gitBranchObject??xH,this.log=t.log??(o=>process.stderr.write(o+`
914
+ `)),this.machineLabel=RH(r?.machine_label),this.enabled=this.projectKey!==null&&!zf(n,r),this.workingPathsEnabled=vH(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??CH(n,kH(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<uE||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<uE||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<gH||(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,wH).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(_H*2**(this.consecutiveFailures-1),bH);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:yH,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(xH,"defaultGitBranchObject");s(SH,"normalizeObjectId");s(EH,"defaultGitBranch");s(RH,"normalizeMachineLabel");s(CH,"staticIdentity")});import{mkdirSync as mE,readdirSync as _E,readFileSync as TH,renameSync as hE,statSync as AH,unlinkSync as Yf,writeFileSync as gE}from"node:fs";import{homedir as IH}from"node:os";import{join as To}from"node:path";function bE(){return To(IH(),".maind","presence")}function wE(e,t){return To(e,t)}function kE(e){let t=e.baseDir??bE(),n=wE(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{Yf(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=Cs(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};mE(n,{recursive:!0,mode:448});let m=To(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;gE(g,JSON.stringify(f),{mode:384}),hE(g,m),l(m),yE(n,a(),m)}catch{}},endSession(){try{c&&Yf(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};mE(n,{recursive:!0,mode:448});let f=To(n,`${u.sessionId}.json`),m=`${f}.tmp-${r}`;gE(m,JSON.stringify(p),{mode:384}),hE(m,f),l(f),yE(n,a(),f)}catch{}}}}function yE(e,t,n){try{for(let r of _E(e)){if(!r.endsWith(".json"))continue;let o=To(e,r);if(o!==n)try{t-AH(o).mtimeMs>NH&&Yf(o)}catch{}}}catch{}}function Sr(e,t=bE()){try{let n=wE(t,e),r=[];for(let o of _E(n))if(o.endsWith(".json"))try{let i=JSON.parse(TH(To(n,o),"utf8")),a=OH(i);a&&r.push(a)}catch{}return r.sort((o,i)=>i.written_at.localeCompare(o.written_at)),r}catch{return[]}}function OH(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=Cs(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var NH,ts=w(()=>{"use strict";Ko();NH=120*6e4;s(bE,"presenceSnapshotBaseDir");s(wE,"projectDir");s(kE,"createSnapshotStore");s(yE,"pruneStale");s(Sr,"readSnapshots");s(OH,"parseSnapshot")});import{execFileSync as KH}from"node:child_process";import{createHash as GH,randomUUID as WH}from"node:crypto";import{existsSync as VH,mkdirSync as qH,readdirSync as zH,readFileSync as SE,renameSync as JH,statSync as Zf,unlinkSync as EE,writeFileSync as YH}from"node:fs";import{homedir as XH}from"node:os";import{basename as ZH,join as Tn}from"node:path";function Ao(e){return Tn(e??Tn(XH(),".maind","presence"),"identity")}function os(e,t){if(e){let n=ZH(e).replace(/\.jsonl$/i,"");if(rs.test(n))return n.toLowerCase()}return t&&rs.test(t)?t.toLowerCase():null}function RE(e){let t=e.nowMs??Date.now();qH(e.dir,{recursive:!0,mode:448});let n=Tn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,o={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(SE(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}:{}};YH(r,JSON.stringify(c,null,2)+`
915
+ `,{mode:384}),JH(r,n),rU(e.dir,t)}function CE(e,t,n,r=Date.now()){try{let o=Zf(Tn(e,`${t}.json`));return r-o.mtimeMs>n}catch{return!0}}function TE(e,t){try{EE(Tn(e,`${t}.json`))}catch{}}function rU(e,t){try{for(let n of zH(e))if(n.endsWith(".json"))try{let r=Zf(Tn(e,n));t-r.mtimeMs>eU&&EE(Tn(e,n))}catch{}}catch{}}function oU(e){return AE(e)?.file??null}function AE(e){let t=Tn(e.dir,`${e.agentPid}.json`);try{if(!VH(t))return null;let n=Zf(t);if(n.mtimeMs<e.bridgeStartMs-tU)return null;let r=JSON.parse(SE(t,"utf8"));if(typeof r!="object"||r===null)return null;let o=r;return o.v!==1||typeof o.transcript_stem!="string"||!rs.test(o.transcript_stem)||typeof o.session_id!="string"||typeof o.cwd!="string"||o.agent_pid!==e.agentPid||!iU(o.cwd,e.cwd)?null:{file:o,mtimeMs:n.mtimeMs}}catch{return null}}function xE(e){return e.replace(/\/+$/,"")}function iU(e,t){let n=xE(e),r=xE(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function sU(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=GH("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 aU(e){if(process.platform==="win32")return null;try{let t=KH("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function cU(){try{return le()}catch{return null}}var rs,QH,eU,tU,nU,nl,rl=w(()=>{"use strict";ie();rs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,QH=8,eU=48*60*6e4,tU=6e4,nU="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(Ao,"identityDirPath");s(os,"transcriptStemOf");s(RE,"writeAgentIdentityFile");s(CE,"identityFileStale");s(TE,"deleteAgentIdentityFile");s(rU,"pruneIdentityDir");s(oU,"readAgentIdentityFile");s(AE,"readAgentIdentityEntry");s(xE,"normDir");s(iU,"sameSessionTree");s(sU,"uuidV5");s(aU,"processStartTime");nl=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??Ao(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=rs.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??cU)(),i=(t.ppidStart??aU)(this.agentPid);if(o!==null&&i!==null&&t.projectKey!==null){this.id=sU(`${o}|${this.agentPid}|${i}|${t.projectKey}`,nU),this.source="derived";return}this.id=WH(),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(!rs.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>QH&&this.aliases.shift())}activityAtMs(){return AE({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 oU({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(cU,"defaultDeviceId")});import{applyEdits as bU,modify as wU,parse as kU}from"jsonc-parser";function tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DE(e){return tm(e)&&typeof e.command=="string"}function nm(e){if(e===null||e.trim().length===0)return[];let t=[],n=kU(e,t,{allowTrailingComma:!0});if(t.length>0||!tm(n))return[];let r=[];return tm(n.mcpServers)&&DE(n.mcpServers.maind)&&r.push(["mcpServers","maind"]),DE(n.maind)&&r.push(["maind"]),r}function PE(e,t){let n=nm(e);if(e===null||n.length===0)return null;let r=e;for(let o of n)r=bU(r,wU(r,o,void 0,{}));return{file:t,raw:e,next:r,removed:n}}function ME(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.
916
916
  `:[`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(`
917
917
  `)+`
918
918
  `:`The maind plugin is not enabled \u2014 the maind server in ~/.claude.json is the one Claude Code runs; nothing to remove.
919
- `}var nm=w(()=>{"use strict";s(em,"isObject");s(OE,"isServerEntry");s(tm,"claudeUserMaindPaths");s(DE,"planDuplicateMcpRemoval");s(PE,"renderDuplicateMcpPlan")});import{createHash as wU}from"node:crypto";function xU(e){let t=new Set;return e.filter(n=>!t.has(n.sha256)&&(t.add(n.sha256),!0))}function rm(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
919
+ `}var rm=w(()=>{"use strict";s(tm,"isObject");s(DE,"isServerEntry");s(nm,"claudeUserMaindPaths");s(PE,"planDuplicateMcpRemoval");s(ME,"renderDuplicateMcpPlan")});import{createHash as vU}from"node:crypto";function EU(e){let t=new Set;return e.filter(n=>!t.has(n.sha256)&&(t.add(n.sha256),!0))}function om(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
920
920
  `,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
921
921
  `:`
922
- `}),n=r+1}return t}function SU(e){let t=rm(e),n=[],r=null;for(let o=0;o<t.length;o++){if(!t[o].text.startsWith(cr))continue;let i=vU.find(a=>o+a.lines<=t.length&&$E(t.slice(o,o+a.lines).map(c=>c.text).join(`
923
- `))===a.sha256);if(i===void 0){r=`a "${cr}" 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()!==za)continue;let i=t.findIndex((c,l)=>l>o&&c.text.trim()===Ja);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(Oi));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 EU(e,t){let n=rm(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]&&il(n[c]);c--)r[c]=!0}let o=0;for(;o<n.length&&r[o];)o++;if(o>0)for(;o<n.length&&il(n[o]);o++)r[o]=!0;let i=n.filter((a,c)=>!r[c]);return i.every(il)?null:i.map(a=>a.text+a.eol).join("")}function LE(e,t,n){let r=SU(n);if(r.blocks.length===0&&r.manual===null)return null;let o=s(p=>`${RU[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=EU(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=rm(c).filter(p=>!il(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 Er(e){return e.some(t=>t.action==="edit"||t.action==="delete"||t.action==="manual")}function sl(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 ME,$E,kU,vU,il,RU,is=w(()=>{"use strict";qa();lo();ME=["CLAUDE.md","AGENTS.md",".github/copilot-instructions.md",".cursorrules",".windsurfrules"],$E=s(e=>wU("sha256").update(e).digest("hex"),"sha256"),kU={lines:70,sha256:"2c7687dc2fd58b7c96d7f31c7b530c06c3fffe8710c6404a7e421ca7c8bf7714"},vU=xU([{lines:Et.split(`
924
- `).length,sha256:$E(Et)},kU,{lines:57,sha256:"72f5d6423e98eb01b2854b44dff290f2d8be1af1c8995f059dba5118530aafce"},{lines:56,sha256:"bf77aeeed9e96b8d0bfcba1feee0592256e2d49d64b53977bbd8f5b8323e5387"},{lines:21,sha256:"afdaf4a151cfd6fc9258392d86593e0604dae7518ffa8918cfc92bab9d5fd41b"}]);s(xU,"dedupe");s(rm,"splitLines");il=s(e=>e.text.trim()==="","isBlank");s(SU,"scanRepoFile");s(EU,"cutBlocks");RU={preamble:"maind preamble",conventions:"conventions block","team-conventions":"team conventions block (install --team)"};s(LE,"planRepoFile");s(Er,"hasMigratableBlocks");s(sl,"summarizeRepoBlocks")});import{parse as CU}from"jsonc-parser";function om(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 sm(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=ut(e.raw);if("value"in a){let u=Wt(a.value,["mcp_servers","maind"]);if(!J(u)||typeof u.command!="string")return null;let p=Array.isArray(u.args)?u.args.filter(f=>typeof f=="string"):[];return{command:u.command,args:p}}let c=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!c)return null;let l=/^\s*command\s*=\s*"([^"]*)"/m.exec(c[1]),d=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(c[1]);return l?{command:l[1],args:d?[...d[1].matchAll(/"([^"]*)"/g)].map(u=>u[1]):[]}:null}let t=[],n=CU(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 Io(e,t){let n=`npm i -g ${An}@${e}`;return t?`nvm use ${t} && ${n}`:n}function al(e){let t=[],n=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${An}`),r=[e.runningVersion,...e.nodeTrees.map(y=>y.bridgeVersion).filter(y=>y!==null)],o=e.latestVersion??r.sort(om).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(k=>k.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 k=e.nodeTrees.find(v=>v.node===e.nvmDefault);k&&k.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${k.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Io(o,k.node)})}if(new Set(i.map(k=>k.bridgeVersion)).size>1)for(let k of i.filter(v=>om(v.bridgeVersion,o)<0))t.push({check:"node-trees",level:"warn",message:`${k.node} carries bridge ${k.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Io(o,k.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 _=sm(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(v=>v.includes(An))){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:`${Io(o)}, then set "command": "maind-mcp-bridge" (no args) in ${y.path}`});continue}let k=/(^|[\\/])node(\.exe)?$/.test(_.command);if(k&&_.args.length>0){let v=_.args[0];if(!e.fileExists(v)){t.push({check:"client-config",level:"error",message:`${y.label} runs ${v}, which does not exist.`,fix:`re-run \`npx -y ${An}@${o} install\` to rewrite the entry`});continue}l(v,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 ${Io(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:Io(o,e.nvmDefault)});continue}k||(_.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 ${An} 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(om(_.version,e.latestVersion)<0){let k=/[\\/]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:k?Io(e.latestVersion,k):`npx -y ${An}@${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||!jE.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"}):AU.test(d)?t.push({check:"credentials",level:e.deviceId!==null&&jE.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=Me(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 k=b.command?/(\S+\/build\/index\.js)/.exec(b.command)?.[1]??null:null,v=k?e.installVersionOf(k):null;v!==null&&_!==null&&v!==_&&t.push({check:"hooks",level:"warn",message:`${b.event}/${b.subcommand} runs bridge ${v}, 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(Y),_=e.guardMode??"off",b=y&&e.claudeSettings!==null&&Xi(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 ${_}): ${Y} was declined at install, and the maind plugin keeps it off too.`}:{check:"session-start",level:"info",message:`no session-start briefing \u2014 ${Y} 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 (${Y}).`});let k=e.plugin?.file?` (${e.plugin.file})`:"",v=e.clientConfigs.find(S=>S.key==="claude-code-user");v!==void 0&&tm(v.raw).length>0&&t.push({check:"claude-plugin",level:"warn",message:`the maind plugin is enabled${k} and brings its own MCP server, and ${v.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?[]:Me(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${k}, 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",_=Xi(e.claudeSettings,{guardMode:y,fileExists:s(E=>e.fileExists(E),"fileExists")}),k=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${An}`)} install --hooks-only`,v=(e.declinedHooks??[]).includes(Y);_.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${Y} hook).`}):_.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${Y} 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 ${Y} hook it stops when the guard is switched off.`,fix:k}):v?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${Y} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:k}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${Y}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:k})}if(e.claudeSettings!==null){let y=Me(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")},[TU])[0];if(y.status==="superseded"){let _=e.foreignHookHosts??[],b=_.includes("cursor"),k=(e.declinedHooks??[]).includes(Vt),v=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${An}`),E=y.remedy==="run-install"?`${v} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${v} ${Vt}`,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&&!k?"warn":"info",message:`the SessionStart reminder hook still runs \`${y.command}\` \u2014 ${S}. ${Vt} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:E})}}let f=e.repoBlocks??null,m=f?.plans.find(y=>y.keeps.some(_=>_.startsWith("team conventions block")))??null;f!==null&&Er(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 ${sl(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)`}),m!==null&&t.push({check:"repo-blocks",level:"ok",message:`${m.rel} carries the team conventions block (install --team); the bridge keeps it current.`}),f!==null&&f.inRepo&&m===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&&Er(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=Me(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 FE(e){let t=e.filter(o=>o.level==="error"&&im.includes(o.check)).sort((o,i)=>im.indexOf(o.check)-im.indexOf(i.check)),n=t[0];if(n===void 0)return IU(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 IU(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?NU(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 NU(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?OU(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 OU(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 HE(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(`
922
+ `}),n=r+1}return t}function RU(e){let t=om(e),n=[],r=null;for(let o=0;o<t.length;o++){if(!t[o].text.startsWith(cr))continue;let i=SU.find(a=>o+a.lines<=t.length&&LE(t.slice(o,o+a.lines).map(c=>c.text).join(`
923
+ `))===a.sha256);if(i===void 0){r=`a "${cr}" 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()!==za)continue;let i=t.findIndex((c,l)=>l>o&&c.text.trim()===Ja);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(Oi));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 CU(e,t){let n=om(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]&&il(n[c]);c--)r[c]=!0}let o=0;for(;o<n.length&&r[o];)o++;if(o>0)for(;o<n.length&&il(n[o]);o++)r[o]=!0;let i=n.filter((a,c)=>!r[c]);return i.every(il)?null:i.map(a=>a.text+a.eol).join("")}function jE(e,t,n){let r=RU(n);if(r.blocks.length===0&&r.manual===null)return null;let o=s(p=>`${TU[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=CU(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=om(c).filter(p=>!il(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 Er(e){return e.some(t=>t.action==="edit"||t.action==="delete"||t.action==="manual")}function sl(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 $E,LE,xU,SU,il,TU,is=w(()=>{"use strict";qa();lo();$E=["CLAUDE.md","AGENTS.md",".github/copilot-instructions.md",".cursorrules",".windsurfrules"],LE=s(e=>vU("sha256").update(e).digest("hex"),"sha256"),xU={lines:70,sha256:"2c7687dc2fd58b7c96d7f31c7b530c06c3fffe8710c6404a7e421ca7c8bf7714"},SU=EU([{lines:Et.split(`
924
+ `).length,sha256:LE(Et)},xU,{lines:57,sha256:"72f5d6423e98eb01b2854b44dff290f2d8be1af1c8995f059dba5118530aafce"},{lines:56,sha256:"bf77aeeed9e96b8d0bfcba1feee0592256e2d49d64b53977bbd8f5b8323e5387"},{lines:21,sha256:"afdaf4a151cfd6fc9258392d86593e0604dae7518ffa8918cfc92bab9d5fd41b"}]);s(EU,"dedupe");s(om,"splitLines");il=s(e=>e.text.trim()==="","isBlank");s(RU,"scanRepoFile");s(CU,"cutBlocks");TU={preamble:"maind preamble",conventions:"conventions block","team-conventions":"team conventions block (install --team)"};s(jE,"planRepoFile");s(Er,"hasMigratableBlocks");s(sl,"summarizeRepoBlocks")});import{parse as AU}from"jsonc-parser";function im(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 am(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=ut(e.raw);if("value"in a){let u=Wt(a.value,["mcp_servers","maind"]);if(!J(u)||typeof u.command!="string")return null;let p=Array.isArray(u.args)?u.args.filter(f=>typeof f=="string"):[];return{command:u.command,args:p}}let c=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!c)return null;let l=/^\s*command\s*=\s*"([^"]*)"/m.exec(c[1]),d=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(c[1]);return l?{command:l[1],args:d?[...d[1].matchAll(/"([^"]*)"/g)].map(u=>u[1]):[]}:null}let t=[],n=AU(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 Io(e,t){let n=`npm i -g ${An}@${e}`;return t?`nvm use ${t} && ${n}`:n}function al(e){let t=[],n=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${An}`),r=[e.runningVersion,...e.nodeTrees.map(y=>y.bridgeVersion).filter(y=>y!==null)],o=e.latestVersion??r.sort(im).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(k=>k.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 k=e.nodeTrees.find(v=>v.node===e.nvmDefault);k&&k.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${k.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Io(o,k.node)})}if(new Set(i.map(k=>k.bridgeVersion)).size>1)for(let k of i.filter(v=>im(v.bridgeVersion,o)<0))t.push({check:"node-trees",level:"warn",message:`${k.node} carries bridge ${k.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Io(o,k.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 _=am(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(v=>v.includes(An))){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:`${Io(o)}, then set "command": "maind-mcp-bridge" (no args) in ${y.path}`});continue}let k=/(^|[\\/])node(\.exe)?$/.test(_.command);if(k&&_.args.length>0){let v=_.args[0];if(!e.fileExists(v)){t.push({check:"client-config",level:"error",message:`${y.label} runs ${v}, which does not exist.`,fix:`re-run \`npx -y ${An}@${o} install\` to rewrite the entry`});continue}l(v,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 ${Io(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:Io(o,e.nvmDefault)});continue}k||(_.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 ${An} 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(im(_.version,e.latestVersion)<0){let k=/[\\/]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:k?Io(e.latestVersion,k):`npx -y ${An}@${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||!FE.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"}):NU.test(d)?t.push({check:"credentials",level:e.deviceId!==null&&FE.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=Me(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 k=b.command?/(\S+\/build\/index\.js)/.exec(b.command)?.[1]??null:null,v=k?e.installVersionOf(k):null;v!==null&&_!==null&&v!==_&&t.push({check:"hooks",level:"warn",message:`${b.event}/${b.subcommand} runs bridge ${v}, 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(Y),_=e.guardMode??"off",b=y&&e.claudeSettings!==null&&Xi(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 ${_}): ${Y} was declined at install, and the maind plugin keeps it off too.`}:{check:"session-start",level:"info",message:`no session-start briefing \u2014 ${Y} 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 (${Y}).`});let k=e.plugin?.file?` (${e.plugin.file})`:"",v=e.clientConfigs.find(S=>S.key==="claude-code-user");v!==void 0&&nm(v.raw).length>0&&t.push({check:"claude-plugin",level:"warn",message:`the maind plugin is enabled${k} and brings its own MCP server, and ${v.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?[]:Me(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${k}, 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",_=Xi(e.claudeSettings,{guardMode:y,fileExists:s(E=>e.fileExists(E),"fileExists")}),k=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${An}`)} install --hooks-only`,v=(e.declinedHooks??[]).includes(Y);_.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${Y} hook).`}):_.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${Y} 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 ${Y} hook it stops when the guard is switched off.`,fix:k}):v?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${Y} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:k}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${Y}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:k})}if(e.claudeSettings!==null){let y=Me(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")},[IU])[0];if(y.status==="superseded"){let _=e.foreignHookHosts??[],b=_.includes("cursor"),k=(e.declinedHooks??[]).includes(Vt),v=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${An}`),E=y.remedy==="run-install"?`${v} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${v} ${Vt}`,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&&!k?"warn":"info",message:`the SessionStart reminder hook still runs \`${y.command}\` \u2014 ${S}. ${Vt} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:E})}}let f=e.repoBlocks??null,m=f?.plans.find(y=>y.keeps.some(_=>_.startsWith("team conventions block")))??null;f!==null&&Er(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 ${sl(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)`}),m!==null&&t.push({check:"repo-blocks",level:"ok",message:`${m.rel} carries the team conventions block (install --team); the bridge keeps it current.`}),f!==null&&f.inRepo&&m===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&&Er(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=Me(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 HE(e){let t=e.filter(o=>o.level==="error"&&sm.includes(o.check)).sort((o,i)=>sm.indexOf(o.check)-sm.indexOf(i.check)),n=t[0];if(n===void 0)return OU(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 OU(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?DU(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 DU(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?PU(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 PU(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 UE(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(`
925
925
  `)+`
926
- `}var An,TU,AU,jE,im,cl=w(()=>{"use strict";Lc();co();Ga();nm();is();he();An="@maind-dev/mcp-bridge",TU=Ge.find(e=>e.subcommand===Vt),AU=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,jE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(om,"compareVersions");s(sm,"maindEntry");s(Io,"installFix");s(al,"diagnose");im=["connection","client-config","npx-cache","hooks"];s(FE,"sessionStartLine");s(IU,"briefingGapLine");s(NU,"hookHostsGapLine");s(OU,"pluginDuplicateLine");s(HE,"renderFindings")});function BE(e){let t=ut(e);if(!("value"in t))return null;let n=t.value;if(!J(n.mcp_servers)||!J(n.mcp_servers.maind))return null;let r=Dk(e,{token:Y});if(r.kind!=="write")return{action:"manual",next:null,stays:UE(n,e),removes:["[mcp_servers.maind]"]};let o=ut(r.next),i="value"in o?UE(o.value,r.next):[],a=Ri(r.next);return a!==null&&a.statements.every(l=>l.kind==="blank")?{action:"delete",next:null,stays:[],removes:r.removed}:{action:"edit",next:r.next,stays:i,removes:r.removed}}function UE(e,t){let n=J(e.mcp_servers)?Object.keys(e.mcp_servers).filter(a=>a!=="maind").length:0,r=Object.keys(e).filter(a=>a!=="mcp_servers"),o=Ri(t),i=o===null||o.statements.some(a=>a.kind==="comment"||(a.kind==="keyval"||a.kind==="header")&&a.comment!==null);return[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[],...i?["comments"]:[]]}var KE=w(()=>{"use strict";Ga();La();co();he();s(BE,"planTomlPhantomRemoval");s(UE,"foreign")});import{findNodeAtLocation as DU,parse as GE,parseTree as PU,stripComments as MU}from"jsonc-parser";function WE(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||sm(n)===null)continue;if(n.kind==="toml"){let f=$U(n,n.raw);f!==null&&t.push(f);continue}let r=[],o=GE(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!am(o))continue;let i=am(o.servers)&&"maind"in o.servers?"servers":"mcpServers",a=o[i];if(!am(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(o).filter(f=>f!==i),d=MU(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=LU(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 $U(e,t){let n=BE(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(", ")}`:"",i=n.removes.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 ${i}${o}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove ${i} by hand \u2014 it cannot be cut out cleanly${o}`}}}function LU(e,t){let n=PU(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:DU(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 GE(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function VE(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
926
+ `}var An,IU,NU,FE,sm,cl=w(()=>{"use strict";Lc();co();Ga();rm();is();he();An="@maind-dev/mcp-bridge",IU=Ge.find(e=>e.subcommand===Vt),NU=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,FE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(im,"compareVersions");s(am,"maindEntry");s(Io,"installFix");s(al,"diagnose");sm=["connection","client-config","npx-cache","hooks"];s(HE,"sessionStartLine");s(OU,"briefingGapLine");s(DU,"hookHostsGapLine");s(PU,"pluginDuplicateLine");s(UE,"renderFindings")});function KE(e){let t=ut(e);if(!("value"in t))return null;let n=t.value;if(!J(n.mcp_servers)||!J(n.mcp_servers.maind))return null;let r=Pk(e,{token:Y});if(r.kind!=="write")return{action:"manual",next:null,stays:BE(n,e),removes:["[mcp_servers.maind]"]};let o=ut(r.next),i="value"in o?BE(o.value,r.next):[],a=Ri(r.next);return a!==null&&a.statements.every(l=>l.kind==="blank")?{action:"delete",next:null,stays:[],removes:r.removed}:{action:"edit",next:r.next,stays:i,removes:r.removed}}function BE(e,t){let n=J(e.mcp_servers)?Object.keys(e.mcp_servers).filter(a=>a!=="maind").length:0,r=Object.keys(e).filter(a=>a!=="mcp_servers"),o=Ri(t),i=o===null||o.statements.some(a=>a.kind==="comment"||(a.kind==="keyval"||a.kind==="header")&&a.comment!==null);return[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[],...i?["comments"]:[]]}var GE=w(()=>{"use strict";Ga();La();co();he();s(KE,"planTomlPhantomRemoval");s(BE,"foreign")});import{findNodeAtLocation as MU,parse as WE,parseTree as $U,stripComments as LU}from"jsonc-parser";function VE(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||am(n)===null)continue;if(n.kind==="toml"){let f=jU(n,n.raw);f!==null&&t.push(f);continue}let r=[],o=WE(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!cm(o))continue;let i=cm(o.servers)&&"maind"in o.servers?"servers":"mcpServers",a=o[i];if(!cm(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(o).filter(f=>f!==i),d=LU(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=FU(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 jU(e,t){let n=KE(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(", ")}`:"",i=n.removes.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 ${i}${o}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove ${i} by hand \u2014 it cannot be cut out cleanly${o}`}}}function FU(e,t){let n=$U(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:MU(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 WE(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function qE(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
927
927
  `;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(`
928
928
  `)+`
929
- `}function am(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qE=w(()=>{"use strict";cl();KE();s(WE,"planPhantomRemovals");s($U,"tomlRemoval");s(LU,"withoutProperty");s(VE,"renderPhantomPlan");s(am,"isObject")});import{execFileSync as jU}from"node:child_process";import{existsSync as FU,readFileSync as HU,realpathSync as UU}from"node:fs";import{dirname as BU,join as KU,relative as zE,resolve as GU}from"node:path";function cm(e){try{return FU(e)?HU(e,"utf8"):null}catch{return null}}function WU(e){try{let t=jU("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 JE(e){try{return UU(e)}catch{return GU(e)}}function No(e,t={}){let n=JE(e),r=(t.toplevel??WU)(n),o=r===null?null:JE(r),i=t.read??cm,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=zE(o,d);if(p===""||p.startsWith(".."))break;let f=BU(d);if(f===d)break;d=f}c.includes(o)||c.push(o)}let l=[];for(let d of c)for(let u of ME){let p=KU(d,u),f=i(p);if(f===null)continue;let m=LE(zE(a,p).split("\\").join("/")||u,p,f);m!==null&&l.push(m)}return{root:a,inRepo:o!==null,plans:l}}var ll=w(()=>{"use strict";is();s(cm,"readOrNull");s(WU,"gitToplevelSync");s(JE,"realOrResolve");s(No,"scanRepoBlocks")});function dl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function VU(e){for(let t of Ge)if(new RegExp(`(^|[\\s/"'])${t.subcommand}(\\s|$|["'])`).test(e)||t.supersedes!==void 0&&t.supersedes.replaceable.test(e))return t.subcommand;return null}function YE(e,t){if(e===null||e.trim().length===0)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!dl(n)||!dl(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(!dl(d)||!Array.isArray(d.hooks)){l.push(d);continue}let u=d.hooks.filter(p=>{if(!dl(p)||typeof p.command!="string")return!0;let f=VU(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)+`
930
- `,removed:r}}function XE(e,t,n){return n?e===null?`No bridge hooks in settings.json next to the maind plugin \u2014 the plugin runs them.
929
+ `}function cm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zE=w(()=>{"use strict";cl();GE();s(VE,"planPhantomRemovals");s(jU,"tomlRemoval");s(FU,"withoutProperty");s(qE,"renderPhantomPlan");s(cm,"isObject")});import{execFileSync as HU}from"node:child_process";import{existsSync as UU,readFileSync as BU,realpathSync as KU}from"node:fs";import{dirname as GU,join as WU,relative as JE,resolve as VU}from"node:path";function lm(e){try{return UU(e)?BU(e,"utf8"):null}catch{return null}}function qU(e){try{let t=HU("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 YE(e){try{return KU(e)}catch{return VU(e)}}function No(e,t={}){let n=YE(e),r=(t.toplevel??qU)(n),o=r===null?null:YE(r),i=t.read??lm,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=JE(o,d);if(p===""||p.startsWith(".."))break;let f=GU(d);if(f===d)break;d=f}c.includes(o)||c.push(o)}let l=[];for(let d of c)for(let u of $E){let p=WU(d,u),f=i(p);if(f===null)continue;let m=jE(JE(a,p).split("\\").join("/")||u,p,f);m!==null&&l.push(m)}return{root:a,inRepo:o!==null,plans:l}}var ll=w(()=>{"use strict";is();s(lm,"readOrNull");s(qU,"gitToplevelSync");s(YE,"realOrResolve");s(No,"scanRepoBlocks")});function dl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zU(e){for(let t of Ge)if(new RegExp(`(^|[\\s/"'])${t.subcommand}(\\s|$|["'])`).test(e)||t.supersedes!==void 0&&t.supersedes.replaceable.test(e))return t.subcommand;return null}function XE(e,t){if(e===null||e.trim().length===0)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!dl(n)||!dl(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(!dl(d)||!Array.isArray(d.hooks)){l.push(d);continue}let u=d.hooks.filter(p=>{if(!dl(p)||typeof p.command!="string")return!0;let f=zU(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)+`
930
+ `,removed:r}}function ZE(e,t,n){return n?e===null?`No bridge hooks in settings.json next to the maind plugin \u2014 the plugin runs them.
931
931
  `:[`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(`
932
932
  `)+`
933
933
  `:`The maind plugin is not enabled \u2014 the hooks in settings.json are the ones Claude Code runs; nothing to remove.
934
- `}var ZE=w(()=>{"use strict";he();s(dl,"isObject");s(VU,"ourSubcommand");s(YE,"planDuplicateHookRemoval");s(XE,"renderDuplicateHooksPlan")});var t0={};Q(t0,{renderMigrationPlan:()=>e0,runMigrateRepoBlocks:()=>XU});import{unlinkSync as qU}from"node:fs";import{homedir as zU,platform as QE}from"node:os";function e0(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(` ${YU(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(`
934
+ `}var QE=w(()=>{"use strict";he();s(dl,"isObject");s(zU,"ourSubcommand");s(XE,"planDuplicateHookRemoval");s(ZE,"renderDuplicateHooksPlan")});var n0={};ee(n0,{renderMigrationPlan:()=>t0,runMigrateRepoBlocks:()=>QU});import{unlinkSync as JU}from"node:fs";import{homedir as YU,platform as e0}from"node:os";function t0(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(` ${ZU(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(`
935
935
  `)+`
936
- `}function YU(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 XU(e,t={}){let n=t.out??process.stdout,r=t.cwd??process.cwd(),o=(t.scan??No)(r);if(o===null||o.plans.length===0)return n.write(`No maind blocks in ${o?.root??r} \u2014 nothing to migrate.
936
+ `}function ZU(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 QU(e,t={}){let n=t.out??process.stdout,r=t.cwd??process.cwd(),o=(t.scan??No)(r);if(o===null||o.plans.length===0)return n.write(`No maind blocks in ${o?.root??r} \u2014 nothing to migrate.
937
937
  `),0;if(!Er(o.plans))return n.write(`Only the team conventions block (install --team) in ${o.root} \u2014 it stays; nothing to migrate.
938
- `),0;let i=t.setUpChannels??(d=>ZU(d,t.homeDir??zU(),r,n));if(n.write(e0(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}
938
+ `),0;let i=t.setUpChannels??(d=>eB(d,t.homeDir??YU(),r,n));if(n.write(t0(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}
939
939
  `);if(c.length>0){for(let d of c){n.write(` failed ${d.target}: ${d.detail??"unknown error"}
940
940
  `);for(let u of d.manual??[])n.write(u===""?`
941
941
  `:` ${u}
942
942
  `)}return n.write(`Nothing was removed \u2014 a channel could not be set up, and removing the blocks first would lose them.
943
943
  `),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
944
- `);continue}if(cm(d.path)!==d.raw){n.write(` skipped ${d.rel} \u2014 changed since it was read
945
- `),l++;continue}try{d.action==="delete"?qU(d.path):await B(d.path,d.next??d.raw),n.write(` ${d.action==="delete"?"deleted":"edited "} ${d.rel}
944
+ `);continue}if(lm(d.path)!==d.raw){n.write(` skipped ${d.rel} \u2014 changed since it was read
945
+ `),l++;continue}try{d.action==="delete"?JU(d.path):await B(d.path,d.next??d.raw),n.write(` ${d.action==="delete"?"deleted":"edited "} ${d.rel}
946
946
  `)}catch(u){n.write(` failed ${d.rel}: ${u instanceof Error?u.message:String(u)}
947
947
  `),l++}}return n.write(`Commit the changed files when you are ready; your user-level channels carry the same content from now on.
948
- `),l>0?1:0}async function ZU(e,t,n,r){let o={homeDir:t,isInteractive:!1,full:!0,skip:!1,dryRun:e,out:r},i=[],a=$e(Le(t,process.env,QE()));if(a.enabled)i.push({target:Lf,action:"skip",status:"skipped",detail:gc(a)});else for(let c of JU)i.push(await Mi(o,c));return i.push(...await jf(o,{ctx:Bt({projectRoot:n,homeDir:t,platform:QE(),env:process.env,bridgeEntry:ie()}),probe:de,noRules:!1,cwd:n})),i}var JU,n0=w(()=>{"use strict";se();St();et();tc();he();Ff();go();is();ll();JU=Ge.filter(e=>e.subcommand===Vt||e.subcommand===Y);s(e0,"renderMigrationPlan");s(YU,"channelVerb");s(XU,"runMigrateRepoBlocks");s(ZU,"defaultChannelSetup")});var c0={};Q(c0,{channelProbe:()=>a0,contextProbe:()=>s0,realProbe:()=>as,resolveNvmAlias:()=>i0,runDoctor:()=>gB});import{execFileSync as QU}from"node:child_process";import{existsSync as ss,readFileSync as eB,readdirSync as lm,realpathSync as tB,statSync as nB,unlinkSync as rB}from"node:fs";import{homedir as Tt,platform as Rr}from"node:os";import{delimiter as oB,dirname as r0,join as ae}from"node:path";function Ce(e){try{return ss(e)?eB(e,"utf8"):null}catch{return null}}function iB(){try{let e=QU(Rr()==="win32"?"npm.cmd":"npm",["view",o0,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function dm(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ae(Tt(),".nvm")}function sB(){let e=ae(dm(),"versions","node"),t=[];try{t=lm(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Ce(ae(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 i0(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 aB(e){let t=Ce(ae(dm(),"alias","default"));return t===null?null:i0(t,e.map(n=>n.node),n=>{let r=Ce(ae(dm(),"alias",n));return r===null?null:r})}function cB(){let e=Rr()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(oB))if(t)for(let n of e){let r=ae(t,n);if(ss(r)){let o=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:o?o[1]:null,path:r}}}return null}function lB(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Rr()==="win32"?ae(process.env.LOCALAPPDATA??ae(Tt(),"AppData","Local"),"npm-cache"):ae(Tt(),".npm"),t=ae(e,"_npx"),n=[],r=[];try{r=lm(t)}catch{return[]}for(let o of r)try{let i=lm(ae(t,o,"node_modules"));i.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:ae(t,o),maind:i.includes("@maind-dev")})}catch{}return n}function dB(e){let t;try{t=r0(tB(e))}catch{return null}for(let n=0;n<6;n++){let r=Ce(ae(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===o0)return i.version??null}catch{}let o=r0(t);if(o===t)break;t=o}return null}function s0(e){let t=_n(e),n=!1;try{let o=Ce(Eo);n=o!==null&&typeof JSON.parse(o).conventions=="string"}catch{n=!1}let r=Dc();return{repoRoot:t,indexPresent:t!==null&&ss(ae(t,yn)),conventionsCached:n||t!==null&&ss(ae(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function as(e=process.cwd(),t={}){let n=sB(),r=Ce(ae(dt(),"device-id")),o=Bt({projectRoot:e,homeDir:Tt(),platform:Rr(),env:process.env,bridgeEntry:ie()}),i=null;try{i=z()}catch{i=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=ee(),l=ve({entryPath:ie(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:H,latestVersion:t.offline===!0?null:iB(),nodeTrees:n,nvmDefault:aB(n),pathWinner:cB(),clientConfigs:Si(o).map(d=>({key:d.key,label:d.label,path:d.path,kind:d.kind,raw:Ce(d.path),present:d.presence===void 0?null:De(d.presence,de)})),npxStaleDirs:lB(),connection:Mw(),claudeSettings:Ce(ae(Tt(),".claude","settings.json")),fileExists:s(d=>ss(d),"fileExists"),installVersionOf:dB,deviceId:r===null?null:r.trim(),apiKey:i,envApiKey:a.length>0?a:null,guardMode:ye(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?Qe(l):null,context:t.offline===!0?null:s0(e),foreignHookHosts:pB(o),repoBlocks:t.offline===!0?null:uB(e),channels:t.offline===!0?[]:a0(o),plugin:$e(Le(Tt(),process.env,Rr()))}}function uB(e){try{return No(e)}catch{return null}}function a0(e){let t=[];try{if(De(oo(e),de)){let n=xi(e),r=null,o=Ce(n),i=o===null?null:ut(o);if(r=i!==null&&"value"in i?ao(i.value,Y):null,r===null)try{let a=Ce(ae(ro(e),"hooks.json"));r=a===null?null:ao(JSON.parse(a),Y)}catch{r=null}t.push({client:"codex",label:"Codex SessionStart hook",path:n,state:r===null?"missing":"ok"})}for(let n of fr(e,de)){if(!De(n.presence,de))continue;let r=Ce(n.path);t.push({client:n.id,label:n.label,path:n.path,state:r===null?"missing":_o(r)?"ok":"foreign"})}}catch{}return t}function pB(e){let t=[];try{De(Ut(e),de)&&t.push("cursor"),De(Aa(e),de)&&t.push("devin")}catch{}return t}async function fB(e){let t=WE(as(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(VE(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
948
+ `),l>0?1:0}async function eB(e,t,n,r){let o={homeDir:t,isInteractive:!1,full:!0,skip:!1,dryRun:e,out:r},i=[],a=$e(Le(t,process.env,e0()));if(a.enabled)i.push({target:jf,action:"skip",status:"skipped",detail:gc(a)});else for(let c of XU)i.push(await Mi(o,c));return i.push(...await Ff(o,{ctx:Bt({projectRoot:n,homeDir:t,platform:e0(),env:process.env,bridgeEntry:se()}),probe:de,noRules:!1,cwd:n})),i}var XU,r0=w(()=>{"use strict";ae();St();et();tc();he();Hf();go();is();ll();XU=Ge.filter(e=>e.subcommand===Vt||e.subcommand===Y);s(t0,"renderMigrationPlan");s(ZU,"channelVerb");s(QU,"runMigrateRepoBlocks");s(eB,"defaultChannelSetup")});var l0={};ee(l0,{channelProbe:()=>c0,contextProbe:()=>a0,realProbe:()=>as,resolveNvmAlias:()=>s0,runDoctor:()=>_B});import{execFileSync as tB}from"node:child_process";import{existsSync as ss,readFileSync as nB,readdirSync as dm,realpathSync as rB,statSync as oB,unlinkSync as iB}from"node:fs";import{homedir as Tt,platform as Rr}from"node:os";import{delimiter as sB,dirname as o0,join as ce}from"node:path";function Ce(e){try{return ss(e)?nB(e,"utf8"):null}catch{return null}}function aB(){try{let e=tB(Rr()==="win32"?"npm.cmd":"npm",["view",i0,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function um(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ce(Tt(),".nvm")}function cB(){let e=ce(um(),"versions","node"),t=[];try{t=dm(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Ce(ce(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 s0(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 lB(e){let t=Ce(ce(um(),"alias","default"));return t===null?null:s0(t,e.map(n=>n.node),n=>{let r=Ce(ce(um(),"alias",n));return r===null?null:r})}function dB(){let e=Rr()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(sB))if(t)for(let n of e){let r=ce(t,n);if(ss(r)){let o=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:o?o[1]:null,path:r}}}return null}function uB(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Rr()==="win32"?ce(process.env.LOCALAPPDATA??ce(Tt(),"AppData","Local"),"npm-cache"):ce(Tt(),".npm"),t=ce(e,"_npx"),n=[],r=[];try{r=dm(t)}catch{return[]}for(let o of r)try{let i=dm(ce(t,o,"node_modules"));i.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:ce(t,o),maind:i.includes("@maind-dev")})}catch{}return n}function pB(e){let t;try{t=o0(rB(e))}catch{return null}for(let n=0;n<6;n++){let r=Ce(ce(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===i0)return i.version??null}catch{}let o=o0(t);if(o===t)break;t=o}return null}function a0(e){let t=_n(e),n=!1;try{let o=Ce(Eo);n=o!==null&&typeof JSON.parse(o).conventions=="string"}catch{n=!1}let r=Dc();return{repoRoot:t,indexPresent:t!==null&&ss(ce(t,yn)),conventionsCached:n||t!==null&&ss(ce(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function as(e=process.cwd(),t={}){let n=cB(),r=Ce(ce(dt(),"device-id")),o=Bt({projectRoot:e,homeDir:Tt(),platform:Rr(),env:process.env,bridgeEntry:se()}),i=null;try{i=z()}catch{i=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=te(),l=ve({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:H,latestVersion:t.offline===!0?null:aB(),nodeTrees:n,nvmDefault:lB(n),pathWinner:dB(),clientConfigs:Si(o).map(d=>({key:d.key,label:d.label,path:d.path,kind:d.kind,raw:Ce(d.path),present:d.presence===void 0?null:De(d.presence,de)})),npxStaleDirs:uB(),connection:$w(),claudeSettings:Ce(ce(Tt(),".claude","settings.json")),fileExists:s(d=>ss(d),"fileExists"),installVersionOf:pB,deviceId:r===null?null:r.trim(),apiKey:i,envApiKey:a.length>0?a:null,guardMode:ye(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?Qe(l):null,context:t.offline===!0?null:a0(e),foreignHookHosts:mB(o),repoBlocks:t.offline===!0?null:fB(e),channels:t.offline===!0?[]:c0(o),plugin:$e(Le(Tt(),process.env,Rr()))}}function fB(e){try{return No(e)}catch{return null}}function c0(e){let t=[];try{if(De(oo(e),de)){let n=xi(e),r=null,o=Ce(n),i=o===null?null:ut(o);if(r=i!==null&&"value"in i?ao(i.value,Y):null,r===null)try{let a=Ce(ce(ro(e),"hooks.json"));r=a===null?null:ao(JSON.parse(a),Y)}catch{r=null}t.push({client:"codex",label:"Codex SessionStart hook",path:n,state:r===null?"missing":"ok"})}for(let n of fr(e,de)){if(!De(n.presence,de))continue;let r=Ce(n.path);t.push({client:n.id,label:n.label,path:n.path,state:r===null?"missing":_o(r)?"ok":"foreign"})}}catch{}return t}function mB(e){let t=[];try{De(Ut(e),de)&&t.push("cursor"),De(Aa(e),de)&&t.push("devin")}catch{}return t}async function hB(e){let t=VE(as(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(qE(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
949
949
  `);continue}if(Ce(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
950
- `),n++;continue}try{r.action==="delete"?rB(r.path):await B(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
950
+ `),n++;continue}try{r.action==="delete"?iB(r.path):await B(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
951
951
  `)}catch(o){process.stdout.write(` failed ${r.path}: ${o instanceof Error?o.message:String(o)}
952
- `),n++}}return n>0?1:0}async function mB(e){let t=ae(Tt(),".claude","settings.json"),n=$e(Le(Tt(),process.env,Rr())),r=Ce(t),o=n.enabled?YE(r,t):null;if(process.stdout.write(XE(o,e,n.enabled)),!e||o===null)return 0;if(Ce(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
952
+ `),n++}}return n>0?1:0}async function gB(e){let t=ce(Tt(),".claude","settings.json"),n=$e(Le(Tt(),process.env,Rr())),r=Ce(t),o=n.enabled?XE(r,t):null;if(process.stdout.write(ZE(o,e,n.enabled)),!e||o===null)return 0;if(Ce(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
953
953
  `),1;try{return await B(t,o.next,384),process.stdout.write(` edited ${t} \u2014 ${o.removed.length} hook entr${o.removed.length===1?"y":"ies"} removed
954
954
  `),0}catch(i){return process.stdout.write(` failed ${t}: ${i instanceof Error?i.message:String(i)}
955
- `),1}}async function hB(e){let t=ae(Tt(),".claude.json"),n=$e(Le(Tt(),process.env,Rr())),r=Ce(t),o=n.enabled?DE(r,t):null;if(process.stdout.write(PE(o,e,n.enabled)),!e||o===null)return 0;if(Ce(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
956
- `),1;try{let i;try{i=nB(t).mode&511}catch{i=384}return await B(t,o.next,i),process.stdout.write(` edited ${t} \u2014 removed ${o.removed.map(a=>a.join(".")).join(", ")}
955
+ `),1}}async function yB(e){let t=ce(Tt(),".claude.json"),n=$e(Le(Tt(),process.env,Rr())),r=Ce(t),o=n.enabled?PE(r,t):null;if(process.stdout.write(ME(o,e,n.enabled)),!e||o===null)return 0;if(Ce(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
956
+ `),1;try{let i;try{i=oB(t).mode&511}catch{i=384}return await B(t,o.next,i),process.stdout.write(` edited ${t} \u2014 removed ${o.removed.map(a=>a.join(".")).join(", ")}
957
957
  `),0}catch(i){return process.stdout.write(` failed ${t}: ${i instanceof Error?i.message:String(i)}
958
- `),1}}async function gB(e){if(e.includes("--remove-phantoms"))return fB(e.includes("--yes"));if(e.includes("--remove-duplicate-hooks"))return mB(e.includes("--yes"));if(e.includes("--remove-duplicate-mcp"))return hB(e.includes("--yes"));if(e.includes("--migrate-repo-blocks")){let{runMigrateRepoBlocks:n}=await Promise.resolve().then(()=>(n0(),t0));return n(e.includes("--yes"))}let t=al(as());return e.includes("--json")?process.stdout.write(JSON.stringify({version:H,findings:t},null,2)+`
959
- `):process.stdout.write(HE(t)),t.some(n=>n.level==="error")?1:0}var o0,um=w(()=>{"use strict";Ve();np();wr();hc();Sn();oe();Ct();St();se();et();io();co();yc();he();Ue();cl();qE();ll();ZE();nm();go();o0="@maind-dev/mcp-bridge";s(Ce,"readOrNull");s(iB,"latestVersion");s(dm,"nvmDir");s(sB,"nodeTrees");s(i0,"resolveNvmAlias");s(aB,"nvmDefault");s(cB,"pathWinner");s(lB,"npxStaleDirs");s(dB,"installVersionOf");s(s0,"contextProbe");s(as,"realProbe");s(uB,"safeScan");s(a0,"channelProbe");s(pB,"foreignHookHosts");s(fB,"removePhantoms");s(mB,"removeDuplicateHooks");s(hB,"removeDuplicateMcp");s(gB,"runDoctor")});function l0(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function u0(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 Cr(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 cs(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function p0(e,t,n){let r=n.maxAgeMs??d0,o=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let i=o/1e3,a=u0(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)l0(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 ${cs(l.last_seen_seconds+i)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${cs(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(l0(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${cs(l.last_seen_seconds+i)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${cs(i)} ago, advisory \u2014 never a lock):
958
+ `),1}}async function _B(e){if(e.includes("--remove-phantoms"))return hB(e.includes("--yes"));if(e.includes("--remove-duplicate-hooks"))return gB(e.includes("--yes"));if(e.includes("--remove-duplicate-mcp"))return yB(e.includes("--yes"));if(e.includes("--migrate-repo-blocks")){let{runMigrateRepoBlocks:n}=await Promise.resolve().then(()=>(r0(),n0));return n(e.includes("--yes"))}let t=al(as());return e.includes("--json")?process.stdout.write(JSON.stringify({version:H,findings:t},null,2)+`
959
+ `):process.stdout.write(UE(t)),t.some(n=>n.level==="error")?1:0}var i0,pm=w(()=>{"use strict";Ve();np();wr();hc();Sn();ie();Ct();St();ae();et();io();co();yc();he();Ue();cl();zE();ll();QE();rm();go();i0="@maind-dev/mcp-bridge";s(Ce,"readOrNull");s(aB,"latestVersion");s(um,"nvmDir");s(cB,"nodeTrees");s(s0,"resolveNvmAlias");s(lB,"nvmDefault");s(dB,"pathWinner");s(uB,"npxStaleDirs");s(pB,"installVersionOf");s(a0,"contextProbe");s(as,"realProbe");s(fB,"safeScan");s(c0,"channelProbe");s(mB,"foreignHookHosts");s(hB,"removePhantoms");s(gB,"removeDuplicateHooks");s(yB,"removeDuplicateMcp");s(_B,"runDoctor")});function d0(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function p0(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 Cr(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 cs(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function f0(e,t,n){let r=n.maxAgeMs??u0,o=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let i=o/1e3,a=p0(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)d0(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 ${cs(l.last_seen_seconds+i)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${cs(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(d0(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${cs(l.last_seen_seconds+i)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${cs(i)} ago, advisory \u2014 never a lock):
960
960
  `+c.map(l=>` \u2022 ${l}`).join(`
961
961
  `)+`
962
- 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 f0(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 m0(e,t,n,r=d0,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=u0(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`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${cs(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
963
- ${m}`:m}var d0,ul=w(()=>{"use strict";s(l0,"prefixConflict");d0=10*6e4;s(u0,"parsePeers");s(Cr,"selectOwnSnapshot");s(cs,"ageDisplay");s(p0,"adviseOnPath");s(f0,"claimedIdentity");s(m0,"sessionStartSummary")});function g0(e){let t=[];for(let n of y0(e)){let r=xB(n);r&&!t.includes(r)&&t.push(r)}return t}function y0(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===`
962
+ 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 m0(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 h0(e,t,n,r=u0,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=p0(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`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${cs(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
963
+ ${m}`:m}var u0,ul=w(()=>{"use strict";s(d0,"prefixConflict");u0=10*6e4;s(p0,"parsePeers");s(Cr,"selectOwnSnapshot");s(cs,"ageDisplay");s(f0,"adviseOnPath");s(m0,"claimedIdentity");s(h0,"sessionStartSummary")});function y0(e){let t=[];for(let n of _0(e)){let r=EB(n);r&&!t.includes(r)&&t.push(r)}return t}function _0(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===`
964
964
  `){if(i.length>0){let d=e.slice(o+1).split(`
965
- `),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 xB(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(_B.test(a)){n+=1;continue}if(wB.has(a)){n+=1;continue}if(kB.has(a))return null;let c=a.split("/").pop()??a;if(bB.has(c)){n+=1;continue}break}let r=t[n],o=r.split("/").pop()??r;if(!h0.test(o))return null;if(!yB.test(o))return pm;if(!vB.has(o))return o;let i=t[n+1];return i&&h0.test(i)?`${o} ${i}`:o}function fm(e){let t=g0(e).filter(n=>n!==pm&&!_0.has(n));return t.length>0?t[t.length-1]:null}var h0,yB,pm,_B,bB,wB,kB,vB,_0,mm=w(()=>{"use strict";h0=/^[A-Za-z][A-Za-z0-9._-]*$/,yB=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,pm="?",_B=/^[A-Za-z_][A-Za-z0-9_]*=/,bB=new Set(["sudo","env","time","nohup","nice","command","exec"]),wB=new Set(["do","then","else","elif","if","while","until","!","{","("]),kB=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),vB=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(g0,"shellPrograms");s(y0,"commandSegments");s(xB,"programOf");_0=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(fm,"primaryVerb")});function b0(e){let t=e.length>hm?e.slice(-hm):e;return SB.some(n=>n.test(t))}function gm(e){return e.includes("maind")?EB.some(t=>e.includes(t)):!1}function w0(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!RB.some(t=>e.startsWith(t))}function k0(e,t){if(!w0(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?fm(n):null}function ym(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=k0(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&b0(e.output)?"fail":"ok",verb:t}}var hm,SB,EB,RB,v0=w(()=>{"use strict";mm();hm=8192,SB=[/\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(b0,"outputShowsFailure");EB=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];s(gm,"isConsultationTool");RB=["mcp__maind__","mcp__plugin_maind_maind__"];s(w0,"isCountedTool");s(k0,"verbOfCall");s(ym,"observe")});function x0(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 _m(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(x0(o)),o=[]),o.push(i);return o.length>0&&r.push(x0(o)),r}function bm(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 S0(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function Oo(e,t,n){let r=S0(e,t),o=_m(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=bm(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 wm(e){return e.open&&!e.nudged}function km(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=_m(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=bm(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function ls(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 vm=w(()=>{"use strict";s(x0,"chainOf");s(_m,"failureChains");s(bm,"succeededAfter");s(S0,"resetPoint");s(Oo,"difficultyStatus");s(wm,"shouldNudge");s(km,"captureCandidate");s(ls,"verbSummary")});function TB(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"&&CB.has(o)?o:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:i,enabled:a}}function fl(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return us;let n=null,r=null;for(let o of t){if(o===null||typeof o!="object")continue;let i=TB(o);i!==null&&(i.id===ds?n=i:i.id===pl&&(r=i))}return{difficulty:n,capture:r}}function Do(e){return e!==null&&e.enabled}function xm(e){return Do(e)&&e.severity==="required"}var ds,pl,us,CB,Sm=w(()=>{"use strict";ds="conv_consult_on_difficulty",pl="conv_learning_capture_offer",us={difficulty:null,capture:null},CB=new Set(["required","recommended","info"]);s(TB,"ruleOf");s(fl,"extractTriggerPolicy");s(Do,"isActive");s(xm,"isDenyCapable")});function AB(e){return Math.max(1,Math.round(e/6e4))}function ps(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${ls(e)}) and no maind consultation since they started (${ds}). 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 Em(e){return`difficulty episode (${e.failures.length} failed attempts: ${ls(e)}) without a maind consultation since it started (${ds}, required)`}function Rm(e,t="guard"){let n=AB(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${pl}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${ls(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 E0=w(()=>{"use strict";vm();Sm();s(AB,"minutes");s(ps,"nudgeText");s(Em,"difficultyDenyHead");s(Rm,"captureText")});var Po=w(()=>{"use strict";mm();v0();vm();Sm();E0()});import{existsSync as IB,mkdirSync as NB,readFileSync as OB,readdirSync as DB,renameSync as PB,statSync as MB,unlinkSync as $B,writeFileSync as LB}from"node:fs";import{join as T0}from"node:path";function HB(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function UB(e){try{let t=JSON.parse(OB(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 C0(e,t,n){NB(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;LB(r,JSON.stringify({...n,ids:n.ids.slice(-200)}),{mode:384}),PB(r,t)}function BB(e,t,n){try{for(let r of DB(e)){let o=T0(e,r);o!==n&&t-MB(o).mtimeMs>FB&&$B(o)}}catch{}}function fs(e,t,n={}){try{if(!e||e==="unknown")return null;let r=(n.now??Date.now)(),o=n.toldDir??Sh(),i=T0(o,`${HB(e)}.json`),a=IB(i)?UB(i):{ids:[]},c=a.project_key??(n.projectKey??re)();if(c===null)return null;let l=(n.readSnapshots??Sr)(c),u=Cr(l,{hostPids:n.hostPids??[],cwd:t})?.snap??null??l.find(m=>!m.announce_error&&r-Date.parse(m.written_at)<jB)??null;if(u===null)return a.project_key===void 0&&C0(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(m=>!a.ids.includes(m.id));return C0(o,i,{ids:[...a.ids,...f.map(m=>m.id)],project_key:c,seen_written_at:u.written_at}),BB(o,r,i),Ll(f)}catch{return null}}var jB,FB,Cm=w(()=>{"use strict";Ko();ts();me();ul();jB=5*6e4,FB=7*24*60*60*1e3;s(HB,"safeName");s(UB,"readTold");s(C0,"writeTold");s(BB,"pruneTold");s(fs,"pendingAssignedNotice")});function KB(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":ce()}}async function A0(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:KB(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 ml,Tm=w(()=>{"use strict";oe();to();ml=process.env.MAIND_ENDPOINT??eo("mcp-client-metrics-ingest");s(KB,"ingestHeaders");s(A0,"postMetrics")});import{realpathSync as GB}from"node:fs";import{basename as I0,dirname as N0,join as WB}from"node:path";function Tr(e){let t=N0(e),n=[I0(e)];for(;;)try{let r=GB(t);return WB(r,...n.reverse())}catch{let r=N0(t);if(r===t)return e;n.push(I0(t)),t=r}}var hl=w(()=>{"use strict";s(Tr,"realpathOfUnwritten")});import{createHash as VB}from"node:crypto";import{mkdirSync as qB,readFileSync as zB,renameSync as JB,writeFileSync as YB}from"node:fs";import{dirname as XB,join as ZB}from"node:path";function eK(e){try{let t=JSON.parse(zB(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 tK(e,t){qB(XB(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;YB(n,JSON.stringify(t,null,2),{mode:384}),JB(n,e)}function nK(e){return`[maind] setup note \u2014 this repository still carries the maind blocks earlier installs wrote into it: ${sl(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 O0(e,t={}){try{let n=(t.scan??No)(e);if(n===null||!n.inRepo||!Er(n.plans))return null;let r=t.stateFile??QB,o=eK(r),i=VB("sha256").update(n.root).digest("hex");return o.repos[i]!==void 0?null:(o.repos[i]=new Date(t.nowMs??Date.now()).toISOString(),tK(r,o),nK(n))}catch{return null}}var QB,D0=w(()=>{"use strict";ft();is();ll();QB=ZB(Ie,"repo-blocks-notice.json");s(eK,"readNoticeState");s(tK,"writeNoticeState");s(nK,"repoBlocksNoticeText");s(O0,"repoBlocksNotice")});import{existsSync as rK,realpathSync as oK,statSync as iK}from"node:fs";import{dirname as P0,isAbsolute as sK,join as aK}from"node:path";function dK(e,t){let n=e.filter(o=>M0.includes(o.id));if(n.length===0)return null;let r=n.map(o=>{let i=o.hint?`
965
+ `),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 EB(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(wB.test(a)){n+=1;continue}if(vB.has(a)){n+=1;continue}if(xB.has(a))return null;let c=a.split("/").pop()??a;if(kB.has(c)){n+=1;continue}break}let r=t[n],o=r.split("/").pop()??r;if(!g0.test(o))return null;if(!bB.test(o))return fm;if(!SB.has(o))return o;let i=t[n+1];return i&&g0.test(i)?`${o} ${i}`:o}function mm(e){let t=y0(e).filter(n=>n!==fm&&!b0.has(n));return t.length>0?t[t.length-1]:null}var g0,bB,fm,wB,kB,vB,xB,SB,b0,hm=w(()=>{"use strict";g0=/^[A-Za-z][A-Za-z0-9._-]*$/,bB=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,fm="?",wB=/^[A-Za-z_][A-Za-z0-9_]*=/,kB=new Set(["sudo","env","time","nohup","nice","command","exec"]),vB=new Set(["do","then","else","elif","if","while","until","!","{","("]),xB=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),SB=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(y0,"shellPrograms");s(_0,"commandSegments");s(EB,"programOf");b0=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(mm,"primaryVerb")});function w0(e){let t=e.length>gm?e.slice(-gm):e;return RB.some(n=>n.test(t))}function ym(e){return e.includes("maind")?CB.some(t=>e.includes(t)):!1}function k0(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!TB.some(t=>e.startsWith(t))}function v0(e,t){if(!k0(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?mm(n):null}function _m(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=v0(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&w0(e.output)?"fail":"ok",verb:t}}var gm,RB,CB,TB,x0=w(()=>{"use strict";hm();gm=8192,RB=[/\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(w0,"outputShowsFailure");CB=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];s(ym,"isConsultationTool");TB=["mcp__maind__","mcp__plugin_maind_maind__"];s(k0,"isCountedTool");s(v0,"verbOfCall");s(_m,"observe")});function S0(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 bm(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(S0(o)),o=[]),o.push(i);return o.length>0&&r.push(S0(o)),r}function wm(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 E0(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function Oo(e,t,n){let r=E0(e,t),o=bm(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=wm(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 km(e){return e.open&&!e.nudged}function vm(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=bm(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=wm(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function ls(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 xm=w(()=>{"use strict";s(S0,"chainOf");s(bm,"failureChains");s(wm,"succeededAfter");s(E0,"resetPoint");s(Oo,"difficultyStatus");s(km,"shouldNudge");s(vm,"captureCandidate");s(ls,"verbSummary")});function IB(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"&&AB.has(o)?o:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:i,enabled:a}}function fl(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return us;let n=null,r=null;for(let o of t){if(o===null||typeof o!="object")continue;let i=IB(o);i!==null&&(i.id===ds?n=i:i.id===pl&&(r=i))}return{difficulty:n,capture:r}}function Do(e){return e!==null&&e.enabled}function Sm(e){return Do(e)&&e.severity==="required"}var ds,pl,us,AB,Em=w(()=>{"use strict";ds="conv_consult_on_difficulty",pl="conv_learning_capture_offer",us={difficulty:null,capture:null},AB=new Set(["required","recommended","info"]);s(IB,"ruleOf");s(fl,"extractTriggerPolicy");s(Do,"isActive");s(Sm,"isDenyCapable")});function NB(e){return Math.max(1,Math.round(e/6e4))}function ps(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${ls(e)}) and no maind consultation since they started (${ds}). 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 Rm(e){return`difficulty episode (${e.failures.length} failed attempts: ${ls(e)}) without a maind consultation since it started (${ds}, required)`}function Cm(e,t="guard"){let n=NB(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${pl}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${ls(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 R0=w(()=>{"use strict";xm();Em();s(NB,"minutes");s(ps,"nudgeText");s(Rm,"difficultyDenyHead");s(Cm,"captureText")});var Po=w(()=>{"use strict";hm();x0();xm();Em();R0()});import{existsSync as OB,mkdirSync as DB,readFileSync as PB,readdirSync as MB,renameSync as $B,statSync as LB,unlinkSync as jB,writeFileSync as FB}from"node:fs";import{join as A0}from"node:path";function BB(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function KB(e){try{let t=JSON.parse(PB(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 T0(e,t,n){DB(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;FB(r,JSON.stringify({...n,ids:n.ids.slice(-200)}),{mode:384}),$B(r,t)}function GB(e,t,n){try{for(let r of MB(e)){let o=A0(e,r);o!==n&&t-LB(o).mtimeMs>UB&&jB(o)}}catch{}}function fs(e,t,n={}){try{if(!e||e==="unknown")return null;let r=(n.now??Date.now)(),o=n.toldDir??Eh(),i=A0(o,`${BB(e)}.json`),a=OB(i)?KB(i):{ids:[]},c=a.project_key??(n.projectKey??oe)();if(c===null)return null;let l=(n.readSnapshots??Sr)(c),u=Cr(l,{hostPids:n.hostPids??[],cwd:t})?.snap??null??l.find(m=>!m.announce_error&&r-Date.parse(m.written_at)<HB)??null;if(u===null)return a.project_key===void 0&&T0(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(m=>!a.ids.includes(m.id));return T0(o,i,{ids:[...a.ids,...f.map(m=>m.id)],project_key:c,seen_written_at:u.written_at}),GB(o,r,i),Ll(f)}catch{return null}}var HB,UB,Tm=w(()=>{"use strict";Ko();ts();me();ul();HB=5*6e4,UB=7*24*60*60*1e3;s(BB,"safeName");s(KB,"readTold");s(T0,"writeTold");s(GB,"pruneTold");s(fs,"pendingAssignedNotice")});function WB(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":le()}}async function I0(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:WB(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 ml,Am=w(()=>{"use strict";ie();to();ml=process.env.MAIND_ENDPOINT??eo("mcp-client-metrics-ingest");s(WB,"ingestHeaders");s(I0,"postMetrics")});import{realpathSync as VB}from"node:fs";import{basename as N0,dirname as O0,join as qB}from"node:path";function Tr(e){let t=O0(e),n=[N0(e)];for(;;)try{let r=VB(t);return qB(r,...n.reverse())}catch{let r=O0(t);if(r===t)return e;n.push(N0(t)),t=r}}var hl=w(()=>{"use strict";s(Tr,"realpathOfUnwritten")});import{createHash as zB}from"node:crypto";import{mkdirSync as JB,readFileSync as YB,renameSync as XB,writeFileSync as ZB}from"node:fs";import{dirname as QB,join as eK}from"node:path";function nK(e){try{let t=JSON.parse(YB(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 rK(e,t){JB(QB(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;ZB(n,JSON.stringify(t,null,2),{mode:384}),XB(n,e)}function oK(e){return`[maind] setup note \u2014 this repository still carries the maind blocks earlier installs wrote into it: ${sl(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 D0(e,t={}){try{let n=(t.scan??No)(e);if(n===null||!n.inRepo||!Er(n.plans))return null;let r=t.stateFile??tK,o=nK(r),i=zB("sha256").update(n.root).digest("hex");return o.repos[i]!==void 0?null:(o.repos[i]=new Date(t.nowMs??Date.now()).toISOString(),rK(r,o),oK(n))}catch{return null}}var tK,P0=w(()=>{"use strict";ft();is();ll();tK=eK(Ie,"repo-blocks-notice.json");s(nK,"readNoticeState");s(rK,"writeNoticeState");s(oK,"repoBlocksNoticeText");s(D0,"repoBlocksNotice")});import{existsSync as iK,realpathSync as sK,statSync as aK}from"node:fs";import{dirname as M0,isAbsolute as cK,join as lK}from"node:path";function pK(e,t){let n=e.filter(o=>$0.includes(o.id));if(n.length===0)return null;let r=n.map(o=>{let i=o.hint?`
966
966
  \u2192 ${o.hint}`:"";return` \u2022 ${o.title}
967
967
  ${o.detail}${i}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
968
968
 
@@ -970,49 +970,49 @@ ${m}`:m}var d0,ul=w(()=>{"use strict";s(l0,"prefixConflict");d0=10*6e4;s(u0,"par
970
970
 
971
971
  `)+`
972
972
 
973
- 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 uK(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function pK(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 Am(e){let t=P0(e);for(;;){try{if(iK(t).isDirectory())return t}catch{}let n=P0(t);if(n===t)return t;t=n}}async function fK(e,t,n){let r=await n.load();if(uK(r,e,t))return null;pK(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=>M0.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:cK,metric_value:1},{session_id:e,metric_key:lK,metric_value:i}),await n.save(a),dK(o,t)}async function $0(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=pe(e);if(!Re(n,{kind:"context",event:"PreToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return 0;let o=rt(e);if(!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=sK(o)?o:aK(i,o),c=rK(a)?oK(a):Tr(a),l=lt(Am(c));try{fc()&&Hv(l,{memoryPath:ho})}catch{}let d=await fK(r,l,{load:te,save:Rt,check:s(async u=>(await ii(u,{includeRelease:!1})).findings,"check")});if(d!==null){let u=ge(n,{kind:"context",event:"PreToolUse",text:d});u!==null&&process.stdout.write(u)}return 0}catch{return 0}}var M0,cK,lK,Im=w(()=>{"use strict";dn();Ht();mc();Fe();Ee();hl();qe();M0=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],cK="repo_health_hook_runs",lK="repo_health_hook_findings";s(dK,"formatRepoHealth");s(uK,"alreadySeen");s(pK,"markSeen");s(Am,"nearestExistingDir");s(fK,"repoHealthForEdit");s($0,"runOnRepoHealth")});import{existsSync as mK,readFileSync as hK,realpathSync as gK}from"node:fs";import{isAbsolute as j0,join as F0,posix as yK,relative as _K,sep as bK}from"node:path";function L0(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function SK(e,t){return{contracts:t.filter(r=>L0(r.spec)===e||L0(r.impl)===e).map(r=>r.id),theme:vK.test(e),acl:xK.test(e)}}function EK(e){return e.contracts.length===0&&!e.theme&&!e.acl}function RK(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 CK(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:
973
+ 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 fK(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function mK(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 Im(e){let t=M0(e);for(;;){try{if(aK(t).isDirectory())return t}catch{}let n=M0(t);if(n===t)return t;t=n}}async function hK(e,t,n){let r=await n.load();if(fK(r,e,t))return null;mK(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=>$0.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:dK,metric_value:1},{session_id:e,metric_key:uK,metric_value:i}),await n.save(a),pK(o,t)}async function L0(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=pe(e);if(!Re(n,{kind:"context",event:"PreToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return 0;let o=rt(e);if(!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=cK(o)?o:lK(i,o),c=iK(a)?sK(a):Tr(a),l=lt(Im(c));try{fc()&&Uv(l,{memoryPath:ho})}catch{}let d=await hK(r,l,{load:ne,save:Rt,check:s(async u=>(await ii(u,{includeRelease:!1})).findings,"check")});if(d!==null){let u=ge(n,{kind:"context",event:"PreToolUse",text:d});u!==null&&process.stdout.write(u)}return 0}catch{return 0}}var $0,dK,uK,Nm=w(()=>{"use strict";dn();Ht();mc();Fe();Ee();hl();qe();$0=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],dK="repo_health_hook_runs",uK="repo_health_hook_findings";s(pK,"formatRepoHealth");s(fK,"alreadySeen");s(mK,"markSeen");s(Im,"nearestExistingDir");s(hK,"repoHealthForEdit");s(L0,"runOnRepoHealth")});import{existsSync as gK,readFileSync as yK,realpathSync as _K}from"node:fs";import{isAbsolute as F0,join as H0,posix as bK,relative as wK,sep as kK}from"node:path";function j0(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function RK(e,t){return{contracts:t.filter(r=>j0(r.spec)===e||j0(r.impl)===e).map(r=>r.id),theme:SK.test(e),acl:EK.test(e)}}function CK(e){return e.contracts.length===0&&!e.theme&&!e.acl}function TK(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 AK(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:
974
974
 
975
975
  `+e.map(n=>` \u2022 ${n.line}`).join(`
976
976
  `)+`
977
977
 
978
- 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 TK(e,t){let n=_K(e,t);return!n||n.startsWith("..")||j0(n)?null:n.split(bK).join(yK.sep)}function AK(e){try{let t=hK(F0(e,ra),"utf8"),{manifest:n}=aa(t);return n?.contracts??[]}catch{return[]}}async function H0(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=pe(e);if(!Re(n,{kind:"context",event:"PostToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"",o=rt(e);if(!r||!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=j0(o)?o:F0(i,o),c=mK(a)?gK(a):Tr(a),l=lt(Am(c)),d=TK(l,c);if(d===null)return 0;let u=SK(d,AK(l));if(EK(u))return 0;let p=[];if(u.contracts.length>0)try{let y=await Qn(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=tr(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=er(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 te(),m=RK(f,r,l,p);f.pending_metrics.push({session_id:r,metric_key:wK,metric_value:1},{session_id:r,metric_key:kK,metric_value:m.length}),await Rt(f);let g=CK(m,d);if(g!==null){let y=ge(n,{kind:"context",event:"PostToolUse",text:g});y!==null&&process.stdout.write(y)}return 0}catch{return 0}}var wK,kK,vK,xK,U0=w(()=>{"use strict";dn();Ht();Fe();Ee();Im();hl();qe();wK="write_health_hook_runs",kK="write_health_hook_findings",vK=/\.(tsx?|jsx?|css)$/,xK=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(L0,"declPath");s(SK,"routesForPath");s(EK,"routesAreEmpty");s(RK,"takeUnreported");s(CK,"formatWriteHealth");s(TK,"repoRelative");s(AK,"readContracts");s(H0,"runOnWriteHealth")});var Q0={};Q(Q0,{agentHostPidCandidates:()=>ht,closeSessionMetrics:()=>wl,closeTrackedSession:()=>z0,effectiveConfig:()=>In,flushSessionMetrics:()=>kl,grandparentPid:()=>Y0,isCaptureTool:()=>Nm,recordGuardSignals:()=>q0,runFlush:()=>qK,runHookStatus:()=>zK,runOnFileEdit:()=>KK,runOnFileWrite:()=>BK,runOnRepoHealth:()=>$0,runOnSessionStart:()=>$K,runOnToolUse:()=>HK,runOnWriteHealth:()=>H0,runSessionEndMetrics:()=>VK,runSyncConfig:()=>YK,writeIdentitySideChannel:()=>Om});import{execFileSync as K0}from"node:child_process";import{existsSync as _l,readFileSync as G0,realpathSync as IK}from"node:fs";import{writeFile as NK}from"node:fs/promises";import{homedir as bl}from"node:os";import{isAbsolute as yl,join as ms,relative as W0}from"node:path";function q0(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let o=gm(n),i=n.includes("review_changes")||n.includes("review_verdict"),a=Nm(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 Nm(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 z0(e,t,n=Date.now()){PK(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 PK(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>gl&&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>gl&&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>gl&&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>gl&&delete e.sessions[n]}}function In(e){if(e.config)return e.config;let t=z();return t===null?null:{api_key:t,endpoint:ml}}function J0(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 MK(e){let t=Re(e,{kind:"text",event:"SessionStart"});if(!Cn(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=ge(e,{kind:"text",event:"SessionStart",text:n.join("")});r!==null&&await Mc(r)},"flush")}}async function $K(){let e=await V(),t=pe(e),n=MK(t);try{return await LK(e,t,n)}finally{await n.flush()}}async function LK(e,t,n){if(n.speaks)try{let i=FE(al(as(process.cwd(),{offline:!0})));if(i!==null)n.line(i+`
979
- `);else{let a=O0(process.cwd());a!==null&&n.line(a+`
980
- `)}}catch{}let r=await te();if(In(r)===null)return 0;let o=Z0(e);if(o===null)return 0;J0(r,o),await Rt(r);try{Om(e,o)}catch{}try{let i=n.speaks?re():null;if(i!==null){let a=Sr(i),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=Cr(a,{hostPids:ht(),cwd:c}),d=f0(l?.snap??null,os(So(e)||null,o)),u=m0(l?.snap??a[0]??null,d.id,Date.now(),void 0,d.announceError);u!==null&&n.line(u+`
978
+ 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 IK(e,t){let n=wK(e,t);return!n||n.startsWith("..")||F0(n)?null:n.split(kK).join(bK.sep)}function NK(e){try{let t=yK(H0(e,ra),"utf8"),{manifest:n}=aa(t);return n?.contracts??[]}catch{return[]}}async function U0(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=pe(e);if(!Re(n,{kind:"context",event:"PostToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"",o=rt(e);if(!r||!o)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=F0(o)?o:H0(i,o),c=gK(a)?_K(a):Tr(a),l=lt(Im(c)),d=IK(l,c);if(d===null)return 0;let u=RK(d,NK(l));if(CK(u))return 0;let p=[];if(u.contracts.length>0)try{let y=await Qn(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=tr(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=er(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 ne(),m=TK(f,r,l,p);f.pending_metrics.push({session_id:r,metric_key:vK,metric_value:1},{session_id:r,metric_key:xK,metric_value:m.length}),await Rt(f);let g=AK(m,d);if(g!==null){let y=ge(n,{kind:"context",event:"PostToolUse",text:g});y!==null&&process.stdout.write(y)}return 0}catch{return 0}}var vK,xK,SK,EK,B0=w(()=>{"use strict";dn();Ht();Fe();Ee();Nm();hl();qe();vK="write_health_hook_runs",xK="write_health_hook_findings",SK=/\.(tsx?|jsx?|css)$/,EK=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(j0,"declPath");s(RK,"routesForPath");s(CK,"routesAreEmpty");s(TK,"takeUnreported");s(AK,"formatWriteHealth");s(IK,"repoRelative");s(NK,"readContracts");s(U0,"runOnWriteHealth")});var eR={};ee(eR,{agentHostPidCandidates:()=>ht,closeSessionMetrics:()=>wl,closeTrackedSession:()=>J0,effectiveConfig:()=>In,flushSessionMetrics:()=>kl,grandparentPid:()=>X0,isCaptureTool:()=>Om,recordGuardSignals:()=>z0,runFlush:()=>JK,runHookStatus:()=>YK,runOnFileEdit:()=>WK,runOnFileWrite:()=>GK,runOnRepoHealth:()=>L0,runOnSessionStart:()=>jK,runOnToolUse:()=>BK,runOnWriteHealth:()=>U0,runSessionEndMetrics:()=>zK,runSyncConfig:()=>ZK,writeIdentitySideChannel:()=>Dm});import{execFileSync as G0}from"node:child_process";import{existsSync as _l,readFileSync as W0,realpathSync as OK}from"node:fs";import{writeFile as DK}from"node:fs/promises";import{homedir as bl}from"node:os";import{isAbsolute as yl,join as ms,relative as V0}from"node:path";function z0(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let o=ym(n),i=n.includes("review_changes")||n.includes("review_verdict"),a=Om(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 Om(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 J0(e,t,n=Date.now()){$K(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 $K(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>gl&&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>gl&&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>gl&&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>gl&&delete e.sessions[n]}}function In(e){if(e.config)return e.config;let t=z();return t===null?null:{api_key:t,endpoint:ml}}function Y0(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 LK(e){let t=Re(e,{kind:"text",event:"SessionStart"});if(!Cn(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=ge(e,{kind:"text",event:"SessionStart",text:n.join("")});r!==null&&await Mc(r)},"flush")}}async function jK(){let e=await V(),t=pe(e),n=LK(t);try{return await FK(e,t,n)}finally{await n.flush()}}async function FK(e,t,n){if(n.speaks)try{let i=HE(al(as(process.cwd(),{offline:!0})));if(i!==null)n.line(i+`
979
+ `);else{let a=D0(process.cwd());a!==null&&n.line(a+`
980
+ `)}}catch{}let r=await ne();if(In(r)===null)return 0;let o=Q0(e);if(o===null)return 0;Y0(r,o),await Rt(r);try{Dm(e,o)}catch{}try{let i=n.speaks?oe():null;if(i!==null){let a=Sr(i),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=Cr(a,{hostPids:ht(),cwd:c}),d=m0(l?.snap??null,os(So(e)||null,o)),u=h0(l?.snap??a[0]??null,d.id,Date.now(),void 0,d.announceError);u!==null&&n.line(u+`
981
981
  `);let p=fs(o,c,{projectKey:s(()=>i,"projectKey"),hostPids:ht()});p!==null&&n.line(`[maind] ${p}
982
- `)}}catch{}try{let i=$e(Le(bl(),process.env,process.platform)),a=Cn(t.host)||i.enabled?[]:Me(jK());if(Ip(a)&&Qa(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\`).
983
- `)}}catch{}return 0}function jK(){try{let e=ms(bl(),".claude","settings.json");return _l(e)?G0(e,"utf8"):null}catch{return null}}function Om(e,t,n,r=Ao()){let o=n??ht();if(o.length===0)return;let i=os(So(e)||null,t);if(i===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=So(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of o)EE({dir:r,agentPid:d,sessionId:t,transcriptStem:i,cwd:a,transcriptPath:c,model:l})}function Y0(){try{if(process.platform==="win32")return null;let e=K0("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 ht(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Y0();return n!==null&&n>1&&n!==t&&e.push(n),e}async function HK(){let e=await te();if(In(e)===null)return 0;let t=await V(),n=Z0(t)??"unknown",r=J0(e,n);r.tool_call_count+=1;try{let c=ht().filter(l=>RE(Ao(),l,FK));n!=="unknown"&&c.length>0&&Om(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),q0(e,n,o),Nm(o)&&n!=="unknown"&&await ne({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 Lp(r.transcript_path);c&&(r.token_count=c.total_tokens,await WK(e,r))}await Rt(e);let a=pe(t);try{if(n!=="unknown"&&Re(a,{kind:"context",event:"PreToolUse"})){let c=fs(n,typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),{hostPids:ht()}),l=c===null?null:ge(a,{kind:"context",event:"PreToolUse",text:`[maind] ${c}`});l!==null&&process.stdout.write(l+`
984
- `)}}catch{}return 0}function UK(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
982
+ `)}}catch{}try{let i=$e(Le(bl(),process.env,process.platform)),a=Cn(t.host)||i.enabled?[]:Me(HK());if(Np(a)&&Qa(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\`).
983
+ `)}}catch{}return 0}function HK(){try{let e=ms(bl(),".claude","settings.json");return _l(e)?W0(e,"utf8"):null}catch{return null}}function Dm(e,t,n,r=Ao()){let o=n??ht();if(o.length===0)return;let i=os(So(e)||null,t);if(i===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=So(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of o)RE({dir:r,agentPid:d,sessionId:t,transcriptStem:i,cwd:a,transcriptPath:c,model:l})}function X0(){try{if(process.platform==="win32")return null;let e=G0("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 ht(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=X0();return n!==null&&n>1&&n!==t&&e.push(n),e}async function BK(){let e=await ne();if(In(e)===null)return 0;let t=await V(),n=Q0(t)??"unknown",r=Y0(e,n);r.tool_call_count+=1;try{let c=ht().filter(l=>CE(Ao(),l,UK));n!=="unknown"&&c.length>0&&Dm(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),z0(e,n,o),Om(o)&&n!=="unknown"&&await re({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 jp(r.transcript_path);c&&(r.token_count=c.total_tokens,await qK(e,r))}await Rt(e);let a=pe(t);try{if(n!=="unknown"&&Re(a,{kind:"context",event:"PreToolUse"})){let c=fs(n,typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),{hostPids:ht()}),l=c===null?null:ge(a,{kind:"context",event:"PreToolUse",text:`[maind] ${c}`});l!==null&&process.stdout.write(l+`
984
+ `)}}catch{}return 0}function KK(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
985
985
  `);return`${t.prefix}${e.number} is already taken:
986
986
  ${n}
987
987
 
988
988
  Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
989
989
 
990
- 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 BK(){try{let e=await V();if((e.tool_name??"")!=="Write")return 0;let t=pe(e);if(!Re(t,{kind:"deny"}))return 0;let n=rt(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=yl(n)?n:ms(r,n);if(_l(o))return 0;let i=lt(r),a=W0(i,Tr(o));if(a.length===0||a.startsWith("..")||yl(a))return 0;let c=await Zn(i,a);if(!c.taken||c.namespace===null)return 0;let l=ge(t,{kind:"deny",reason:UK(c,c.namespace)});return l!==null&&process.stdout.write(l),0}catch{return 0}}async function KK(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=pe(e);if(!Re(n,{kind:"context",event:"PreToolUse"}))return 0;let r=rt(e);if(!r)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=yl(r)?r:ms(o,r),a=re();if(a===null)return 0;let c=Sr(a);if(c.length===0)return 0;let l=Cr(c,{hostPids:ht(),cwd:o});if(l===null)return 0;let d=lt(o),u=_l(i)?IK(i):Tr(i),p=W0(d,u).replace(/\\/g,"/");if(p.length===0||p.startsWith("..")||yl(p))return 0;let f=p0(l.snap,p,{via:l.via,currentBranch:l.via==="cwd"?GK(o):null,nowMs:Date.now()});if(f===null)return 0;let m=ge(n,{kind:"context",event:"PreToolUse",text:f});return m!==null&&process.stdout.write(m),0}catch{return 0}}function GK(e){try{let n=K0("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 WK(e,t){let n=sf(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 NK(ms(Ae,`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)}
990
+ 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 GK(){try{let e=await V();if((e.tool_name??"")!=="Write")return 0;let t=pe(e);if(!Re(t,{kind:"deny"}))return 0;let n=rt(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=yl(n)?n:ms(r,n);if(_l(o))return 0;let i=lt(r),a=V0(i,Tr(o));if(a.length===0||a.startsWith("..")||yl(a))return 0;let c=await Zn(i,a);if(!c.taken||c.namespace===null)return 0;let l=ge(t,{kind:"deny",reason:KK(c,c.namespace)});return l!==null&&process.stdout.write(l),0}catch{return 0}}async function WK(){try{let e=await V(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=pe(e);if(!Re(n,{kind:"context",event:"PreToolUse"}))return 0;let r=rt(e);if(!r)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=yl(r)?r:ms(o,r),a=oe();if(a===null)return 0;let c=Sr(a);if(c.length===0)return 0;let l=Cr(c,{hostPids:ht(),cwd:o});if(l===null)return 0;let d=lt(o),u=_l(i)?OK(i):Tr(i),p=V0(d,u).replace(/\\/g,"/");if(p.length===0||p.startsWith("..")||yl(p))return 0;let f=f0(l.snap,p,{via:l.via,currentBranch:l.via==="cwd"?VK(o):null,nowMs:Date.now()});if(f===null)return 0;let m=ge(n,{kind:"context",event:"PreToolUse",text:f});return m!==null&&process.stdout.write(m),0}catch{return 0}}function VK(e){try{let n=G0("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 qK(e,t){let n=af(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 DK(ms(Ae,`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)}
991
991
  `)}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.
992
992
  `):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.
993
- `)}async function VK(e){await wl(e)&&await kl(V0)}async function wl(e){try{let t=await te();if(In(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(z0(t,r),await Rt(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
994
- `),!1}}async function kl(e=V0){try{let t=await te(),n=In(t);return n===null?null:await X0(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function qK(){let e=await te(),t=In(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 X0(t,DK);return process.stdout.write(JSON.stringify(n,null,2)+`
995
- `),n.ok?0:1}async function X0(e,t){let n=await te();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),o=A0(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 te();return c.pending_metrics=c.pending_metrics.slice(r.length),await Rt(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 zK(){let e=await te(),t=In(e),n=JK(),r=$e(Le(bl(),process.env,process.platform)),o=!r.enabled&&Ip(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:sf(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 (${Ui}, ${r.source??"?"})`}:{},hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...!r.enabled&&Qa(n.findings)?{remedy:B0}:{}}},null,2)+`
993
+ `)}async function zK(e){await wl(e)&&await kl(q0)}async function wl(e){try{let t=await ne();if(In(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(J0(t,r),await Rt(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
994
+ `),!1}}async function kl(e=q0){try{let t=await ne(),n=In(t);return n===null?null:await Z0(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function JK(){let e=await ne(),t=In(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 Z0(t,MK);return process.stdout.write(JSON.stringify(n,null,2)+`
995
+ `),n.ok?0:1}async function Z0(e,t){let n=await ne();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),o=I0(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 ne();return c.pending_metrics=c.pending_metrics.slice(r.length),await Rt(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 YK(){let e=await ne(),t=In(e),n=XK(),r=$e(Le(bl(),process.env,process.platform)),o=!r.enabled&&Np(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:af(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 (${Ui}, ${r.source??"?"})`}:{},hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...!r.enabled&&Qa(n.findings)?{remedy:K0}:{}}},null,2)+`
996
996
  `),o){process.stderr.write(`
997
997
  [maind] Claude Code hook wiring is incomplete:
998
998
  `);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
999
- `);Qa(n.findings)&&process.stderr.write(` ${B0}
1000
- `)}return 0}function JK(){let e=ms(bl(),".claude","settings.json"),t=null;try{_l(e)&&(t=G0(e,"utf8"))}catch{}return{settingsPath:e,findings:Me(t)}}async function YK(){let e=await te(),t=In(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??OK,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)}
999
+ `);Qa(n.findings)&&process.stderr.write(` ${K0}
1000
+ `)}return 0}function XK(){let e=ms(bl(),".claude","settings.json"),t=null;try{_l(e)&&(t=W0(e,"utf8"))}catch{}return{settingsPath:e,findings:Me(t)}}async function ZK(){let e=await ne(),t=In(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??PK,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)}
1001
1001
  `),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
1002
1002
  `);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
1003
1003
  `),1}let o;try{o=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
1004
1004
  `),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
1005
1005
  `),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 Rt(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
1006
- `),0)}function Z0(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var OK,V0,DK,gl,FK,B0,hs=w(()=>{"use strict";ur();Po();dn();Ht();Jt();oe();he();ts();Cm();me();Tm();ul();rl();Ee();Fe();hl();qe();to();cl();um();go();D0();Im();U0();OK=process.env.MAIND_THRESHOLDS_ENDPOINT??eo("get-context-thresholds"),V0=1500,DK=1e4,gl=7*24*60*60*1e3;s(q0,"recordGuardSignals");s(Nm,"isCaptureTool");s(z0,"closeTrackedSession");s(PK,"gcState");s(In,"effectiveConfig");s(J0,"getOrCreateSession");s(MK,"sessionStartOut");s($K,"runOnSessionStart");s(LK,"sessionStartBody");s(jK,"readSettingsRaw");s(Om,"writeIdentitySideChannel");FK=6e4;s(Y0,"grandparentPid");s(ht,"agentHostPidCandidates");s(HK,"runOnToolUse");s(UK,"denyReason");s(BK,"runOnFileWrite");s(KK,"runOnFileEdit");s(GK,"currentGitBranch");s(WK,"maybeEmitAdvisory");s(VK,"runSessionEndMetrics");s(wl,"closeSessionMetrics");s(kl,"flushSessionMetrics");s(qK,"runFlush");s(X0,"flushPending");s(zK,"runHookStatus");B0="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(JK,"readHookWiring");s(YK,"runSyncConfig");s(Z0,"sessionIdOf")});function tR(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!eR.test(n))return null;let r=n.toLowerCase();return t!==null&&eR.test(t)&&r!==t.toLowerCase()?null:r}var eR,nR=w(()=>{"use strict";eR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(tR,"snapshotSessionId")});import{appendFileSync as XK,existsSync as vl,mkdirSync as rR,readFileSync as ZK,readdirSync as QK,renameSync as Dm,rmdirSync as oR,statSync as Pm,unlinkSync as iR,writeFileSync as eG}from"node:fs";import{join as Mo}from"node:path";function Mm(e){return e&&aR.test(e)?e:"no-session"}function gs(e,t){return Mo(e,`${t}.job.json`)}function $m(e,t){return Mo(e,`${t}.running.json`)}function cR(e,t){return Mo(e,`${t}.lock`)}function Lm(e){vl(e)||rR(e,{recursive:!0,mode:448})}function lR(e,t){Lm(e);let n=Mm(t.session_id),r=`${gs(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;eG(r,JSON.stringify(t),{mode:384}),Dm(r,gs(e,n))}function oG(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 dR(e,t){return vl(gs(e,t))}function uR(e,t){let n=gs(e,t),r=$m(e,t);try{if(vl(n)&&Dm(n,r),!vl(r))return null;let o=oG(ZK(r,"utf8"));return o===null?(iR(r),null):o}catch{return null}}function pR(e,t){try{iR($m(e,t))}catch{}}function jm(e,t,n=Date.now()){Lm(e);let r=cR(e,t);try{if(n-Pm(r).mtimeMs<tG)return!1;oR(r)}catch{}try{return rR(r,{recursive:!1}),!0}catch{return!1}}function Fm(e,t){try{oR(cR(e,t))}catch{}}function fR(e){try{let t=new Set;for(let n of QK(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&aR.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function mR(e,t){for(let n of[gs(e,t),$m(e,t)])try{return Pm(n).mtimeMs}catch{}return null}function $o(e,t,n=nG){try{Lm(e);let r=Mo(e,rG);try{Pm(r).size>n&&Dm(r,Mo(e,"runs.1.jsonl"))}catch{}XK(r,JSON.stringify(t)+`
1007
- `,{mode:384})}catch{}}var Yt,tG,sR,nG,rG,aR,Hm=w(()=>{"use strict";qe();Yt=Mo(Ae,"session-end"),tG=10*6e4,sR=7*24*60*6e4,nG=256*1024,rG="runs.jsonl",aR=/^[A-Za-z0-9_-]{1,80}$/;s(Mm,"jobKey");s(gs,"jobPath");s($m,"runningPath");s(cR,"lockPath");s(Lm,"ensureDir");s(lR,"writeJob");s(oG,"parseJob");s(dR,"hasJob");s(uR,"takeJob");s(pR,"finishJob");s(jm,"acquireLock");s(Fm,"releaseLock");s(fR,"pendingKeys");s(mR,"pendingSince");s($o,"appendRunLog")});function hR(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var gR=w(()=>{"use strict";s(hR,"resolveConnection")});function yR(e,t,n,r=Date.now()){let o=t===null?null:ji(t),i=typeof n=="object"&&n!==null?n:{repoRoot:n},a=qp(e,o,{repoRoot:i.repoRoot,...i.relativize?{relativize:i.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:o!==null}}var _R=w(()=>{"use strict";ur();s(yR,"buildCostPayload")});function sG(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();iG.test(r)&&!t.includes(r)&&t.push(r)}return t}async function bR(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:o}=await Li(e.transcriptPath),i=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?Yp({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:aG(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,c=a?Xp(r,a):null,l=c??e.projectKey,d=sG([e.coordSessionId,e.sessionId,...o]),u=performance.now(),[p,f,m]=await Promise.all([Fp(e.transcriptPath,{turns:r}),tf(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:m!==null,sentSlices:!1,timings:g};let y=c&&a?Zp(c,a):null,_=yR(r,m,{repoRoot:e.repoRoot,relativize:y},t()),b=m===null?null:ji(m)?.canonical_session_id??null,k=e.coordSessionId??b,v=Bp(p,f,{client_session_id:k,client:"claude-code",coordination_session_ids:d},"live_bridge",_);return await e.post(v,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:g}}function aG(e,t){try{return e()}catch{return t}}var iG,wR=w(()=>{"use strict";ur();_R();iG=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(sG,"sessionIdsFor");s(bR,"ingestSessionEnd");s(aG,"safe")});var IR={};Q(IR,{FLUSH_LOCK_KEY:()=>Gm,INLINE_BUDGET:()=>Vm,SESSION_END_WORKER:()=>Wm,SWEEP_MAX_KEYS:()=>SR,SWEEP_MIN_AGE_MS:()=>xR,WORKER_BUDGET:()=>vR,WORKER_DEADLINE_MS:()=>Bm,drainSession:()=>qm,fetchCostContext:()=>ER,flushUnderLock:()=>AR,gitResolvers:()=>CR,liveJobDeps:()=>Sl,postIngest:()=>RR,postIngestOnce:()=>Km,processJob:()=>xl,runSessionEndWorker:()=>dG,sweepPending:()=>TR});import{execFileSync as cG}from"node:child_process";import{existsSync as kR,statSync as lG}from"node:fs";async function ER(e,t,n,r,o){if(n===null)return null;let[i,...a]=r;try{return await qt("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 Km(e,t,n,r,o,i=fetch){let a=new AbortController,c=setTimeout(()=>a.abort(),r);try{let l=await i(ml,{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=Up(Hp(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 RR(e,t,n,r,o,i={}){let a=i.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=await Km(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 Km(e,t,n,o.postMs,r,i.fetchImpl),l=2),{...c,attempts:l}}function Um(e,t){try{let n=cG("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function CR(){let e=new Map,t=new Map;return{repoRootOf:s(n=>kR(n)?Um(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let o=Um(["-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=Um(["-C",n,"config","--get","remote.origin.url"]),i=o?un(o):null;return t.set(n,i),i},"projectKeyOfRoot"),isDir:s(n=>{try{return lG(n).isDirectory()}catch{return!1}},"isDir")}}async function xl(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(!kR(e.transcript_path))a.outcome="transcript_gone";else{let l=CR(),d=t.memoryPath??ho,u=null,p=await bR({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(()=>Fi(d),"knownCheckouts"),rememberCheckouts:s(m=>Hi(d,m),"rememberCheckouts")}:{},fetchContext:s(async(m,g)=>{let y=n();try{return await t.fetchContext(m,g)}finally{i.context=n()-y}},"fetchContext"),post:s(async(m,g)=>{let y=n();u=await t.post(m,g),i.post=n()-y},"post"),connection:s(m=>hR({ownSnapshotAgeMs:e.presence.own_snapshot_age_ms,sawMaindCall:m,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 qm(e,t,n,r={}){let o=r.now??Date.now,i=r.maxRounds??20,a=0;for(;a<i&&jm(e,t,o());){try{let c=uR(e,t);if(c===null)break;let l=Date.parse(c.queued_at),d=Number.isFinite(l)&&o()-l>sR?{ts:new Date(o()).toISOString(),bridge:H,session_id:c.session_id,outcome:"expired",ms:{queued:o()-l}}:await n(c);$o(e,d),pR(e,t),a++}finally{Fm(e,t)}if(!dR(e,t))break}return a}async function TR(e,t,n,r={}){let o=r.now??Date.now,i=0;for(let a of fR(e)){if(i>=SR)break;if(a===t)continue;let c=mR(e,a);c===null||o()-c<xR||await qm(e,a,n,{...r,maxRounds:1})>0&&i++}return i}async function AR(e,t,n=Date.now){if(!jm(e,Gm,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{Fm(e,Gm)}}function Sl(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,o)=>ER(e,t,r,o,n.contextMs),"fetchContext"),post:s((r,o)=>RR(e,t,r,o,n),"post"),flush:s(()=>AR(Yt,()=>kl(n.flushMs)),"flush"),memoryAllowed:fc()}}async function dG(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{$o(Yt,{ts:new Date().toISOString(),bridge:H,session_id:t,outcome:"deadline",ms:{total:Bm}}),process.exit(0)},Bm);n.unref();try{let r=z();if(!r)return 0;let o=ce(),i=s(a=>xl(a,Sl(r,o,vR)),"run");await qm(Yt,t,i),await TR(Yt,t,i)}catch(r){$o(Yt,{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 Wm,vR,Vm,Bm,xR,SR,Gm,zm=w(()=>{"use strict";ur();oe();En();Tm();hs();me();Ue();mc();gR();wR();Hm();Wm="session-end-run",vR={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},Vm={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},Bm=3*6e4,xR=2*6e4,SR=3;s(ER,"fetchCostContext");s(Km,"postIngestOnce");s(RR,"postIngest");s(Um,"git");s(CR,"gitResolvers");s(xl,"processJob");s(qm,"drainSession");s(TR,"sweepPending");Gm="metrics-flush";s(AR,"flushUnderLock");s(Sl,"liveJobDeps");s(dG,"runSessionEndWorker")});var MR={};Q(MR,{buildJob:()=>DR,enqueueAndSpawn:()=>PR,presenceLookup:()=>NR,runOnSessionEnd:()=>yG,transcriptToIngest:()=>OR});import{spawn as uG}from"node:child_process";import{existsSync as pG,unlinkSync as fG}from"node:fs";import{join as mG}from"node:path";function NR(e,t,n,r){let o=null,i={own_snapshot_age_ms:null,presence_usable:!1};try{if(i.presence_usable=e!==null&&!qf(process.env,ee()),e!==null){let a=Cr(Sr(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=tR(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 OR(e,t=process.env){let n=So(e);return n&&!Cn(Yi(e,t))?n:""}function DR(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,os(t.transcriptPath,n),t.nowMs);return{...r,project_key:o,coord_session_id:i.coordSessionId,presence:i.evidence}}function PR(e,t={}){let n=t.dir??Yt,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let o=Mm(e.session_id);try{lR(n,e)}catch{return!1}try{return(t.spawnWorker??hG)(r,o,e.cwd),!0}catch{try{fG(mG(n,`${o}.job.json`))}catch{}return!1}}function hG(e,t,n){uG(process.execPath,[e,Wm,t],{detached:!0,stdio:"ignore",cwd:pG(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function gG(e,t){try{let n=await xl(e,Sl(t,ce(),Vm));$o(Yt,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
1008
- `)}}async function yG(){let e=[];try{e=ht()}catch{e=[]}try{for(let i of e)CE(Ao(),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 wl(r);let o;try{o=DR(n,{transcriptPath:OR(n),cwd:process.cwd(),nowMs:Date.now(),projectKey:re,presence:s((i,a,c)=>NR(i,a,c,e),"presence")})}catch{return 0}return PR(o)||await gG(o,t),0}var $R=w(()=>{"use strict";Ve();oe();ul();Ee();Fe();hs();zf();ts();me();rl();nR();Hm();zm();s(NR,"presenceLookup");s(OR,"transcriptToIngest");s(DR,"buildJob");s(PR,"enqueueAndSpawn");s(hG,"spawnDetachedWorker");s(gG,"runInline");s(yG,"runOnSessionEnd")});var LR={};Q(LR,{runOnSessionBriefing:()=>_G});async function _G(e=process.argv.slice(2)){try{return await Bc("core",await V(),{hostHint:aS(e)})}catch{return 0}}var jR=w(()=>{"use strict";wr();Ee();Fe();s(_G,"runOnSessionBriefing")});var HR={};Q(HR,{deliverSessionReminder:()=>FR,runOnSessionReminder:()=>vG});import{readFile as bG}from"node:fs/promises";import{homedir as wG}from"node:os";import{join as kG}from"node:path";async function FR(e,t={}){let n=t.target??pe(e);if(!Re(n,{kind:"text",event:"SessionStart"}))return 0;let r;try{r=await bG(kG(t.homeDir??wG(),Di),"utf8")}catch{return 0}if(r.length===0)return 0;let o=ge(n,{kind:"text",event:"SessionStart",text:r});return o!==null&&await(t.write??Mc)(o),0}async function vG(){try{return await FR(await V())}catch{return 0}}var UR=w(()=>{"use strict";he();Ee();Fe();s(FR,"deliverSessionReminder");s(vG,"runOnSessionReminder")});var JR={};Q(JR,{CURSOR_BRIEFING_MARKER:()=>Jm,CURSOR_DELIVERY_LOG:()=>BR,CURSOR_UNAVAILABLE_TEXT:()=>GR,appendDelivery:()=>qR,cursorProjectDir:()=>KR,deliverCursorSessionStart:()=>VR,formatCursorBriefing:()=>WR,runOnCursorSessionStart:()=>OG});import{appendFile as xG,mkdir as SG,readFile as EG,stat as RG,writeFile as CG}from"node:fs/promises";import{dirname as TG,join as AG}from"node:path";function KR(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 WR(e,t,n){let o=`${Jm}${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 Hc(o,n,e)}async function VR(e,t={}){let n=t.write??zR,r=t.env??process.env,o=(t.apiKey??z)();if(o===null)return await n(`{}
1009
- `),0;let i=KR(e,r),a=i===null?null:(t.projectKeyFor??xt)(i),c=await Ro(a,o,{fetcher:s(p=>hr({...p,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=GR,d="none";else{let p=WR(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})+`
1010
- `),await qR(t.logFile??BR,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Lo(e.conversation_id)??Lo(e.session_id),transcript_path:Lo(e.transcript_path)??Lo(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Lo(e.cursor_version)??Lo(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function OG(){try{return await VR(await V())}catch{try{await zR(`{}
1011
- `)}catch{}return 0}}async function qR(e,t){try{if(await SG(TG(e),{recursive:!0,mode:448}),await xG(e,JSON.stringify(t)+`
1012
- `,{mode:384}),(await RG(e)).size>IG){let n=(await EG(e,"utf8")).split(`
1013
- `).filter(r=>r.trim().length>0);await CG(e,n.slice(-NG).join(`
1006
+ `),0)}function Q0(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var PK,q0,MK,gl,UK,K0,hs=w(()=>{"use strict";ur();Po();dn();Ht();Jt();ie();he();ts();Tm();me();Am();ul();rl();Ee();Fe();hl();qe();to();cl();pm();go();P0();Nm();B0();PK=process.env.MAIND_THRESHOLDS_ENDPOINT??eo("get-context-thresholds"),q0=1500,MK=1e4,gl=7*24*60*60*1e3;s(z0,"recordGuardSignals");s(Om,"isCaptureTool");s(J0,"closeTrackedSession");s($K,"gcState");s(In,"effectiveConfig");s(Y0,"getOrCreateSession");s(LK,"sessionStartOut");s(jK,"runOnSessionStart");s(FK,"sessionStartBody");s(HK,"readSettingsRaw");s(Dm,"writeIdentitySideChannel");UK=6e4;s(X0,"grandparentPid");s(ht,"agentHostPidCandidates");s(BK,"runOnToolUse");s(KK,"denyReason");s(GK,"runOnFileWrite");s(WK,"runOnFileEdit");s(VK,"currentGitBranch");s(qK,"maybeEmitAdvisory");s(zK,"runSessionEndMetrics");s(wl,"closeSessionMetrics");s(kl,"flushSessionMetrics");s(JK,"runFlush");s(Z0,"flushPending");s(YK,"runHookStatus");K0="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(XK,"readHookWiring");s(ZK,"runSyncConfig");s(Q0,"sessionIdOf")});function nR(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!tR.test(n))return null;let r=n.toLowerCase();return t!==null&&tR.test(t)&&r!==t.toLowerCase()?null:r}var tR,rR=w(()=>{"use strict";tR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(nR,"snapshotSessionId")});import{appendFileSync as QK,existsSync as vl,mkdirSync as oR,readFileSync as eG,readdirSync as tG,renameSync as Pm,rmdirSync as iR,statSync as Mm,unlinkSync as sR,writeFileSync as nG}from"node:fs";import{join as Mo}from"node:path";function $m(e){return e&&cR.test(e)?e:"no-session"}function gs(e,t){return Mo(e,`${t}.job.json`)}function Lm(e,t){return Mo(e,`${t}.running.json`)}function lR(e,t){return Mo(e,`${t}.lock`)}function jm(e){vl(e)||oR(e,{recursive:!0,mode:448})}function dR(e,t){jm(e);let n=$m(t.session_id),r=`${gs(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;nG(r,JSON.stringify(t),{mode:384}),Pm(r,gs(e,n))}function sG(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 uR(e,t){return vl(gs(e,t))}function pR(e,t){let n=gs(e,t),r=Lm(e,t);try{if(vl(n)&&Pm(n,r),!vl(r))return null;let o=sG(eG(r,"utf8"));return o===null?(sR(r),null):o}catch{return null}}function fR(e,t){try{sR(Lm(e,t))}catch{}}function Fm(e,t,n=Date.now()){jm(e);let r=lR(e,t);try{if(n-Mm(r).mtimeMs<rG)return!1;iR(r)}catch{}try{return oR(r,{recursive:!1}),!0}catch{return!1}}function Hm(e,t){try{iR(lR(e,t))}catch{}}function mR(e){try{let t=new Set;for(let n of tG(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&cR.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function hR(e,t){for(let n of[gs(e,t),Lm(e,t)])try{return Mm(n).mtimeMs}catch{}return null}function $o(e,t,n=oG){try{jm(e);let r=Mo(e,iG);try{Mm(r).size>n&&Pm(r,Mo(e,"runs.1.jsonl"))}catch{}QK(r,JSON.stringify(t)+`
1007
+ `,{mode:384})}catch{}}var Yt,rG,aR,oG,iG,cR,Um=w(()=>{"use strict";qe();Yt=Mo(Ae,"session-end"),rG=10*6e4,aR=7*24*60*6e4,oG=256*1024,iG="runs.jsonl",cR=/^[A-Za-z0-9_-]{1,80}$/;s($m,"jobKey");s(gs,"jobPath");s(Lm,"runningPath");s(lR,"lockPath");s(jm,"ensureDir");s(dR,"writeJob");s(sG,"parseJob");s(uR,"hasJob");s(pR,"takeJob");s(fR,"finishJob");s(Fm,"acquireLock");s(Hm,"releaseLock");s(mR,"pendingKeys");s(hR,"pendingSince");s($o,"appendRunLog")});function gR(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var yR=w(()=>{"use strict";s(gR,"resolveConnection")});function _R(e,t,n,r=Date.now()){let o=t===null?null:ji(t),i=typeof n=="object"&&n!==null?n:{repoRoot:n},a=zp(e,o,{repoRoot:i.repoRoot,...i.relativize?{relativize:i.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:o!==null}}var bR=w(()=>{"use strict";ur();s(_R,"buildCostPayload")});function cG(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();aG.test(r)&&!t.includes(r)&&t.push(r)}return t}async function wR(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:o}=await Li(e.transcriptPath),i=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?Xp({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:lG(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,c=a?Zp(r,a):null,l=c??e.projectKey,d=cG([e.coordSessionId,e.sessionId,...o]),u=performance.now(),[p,f,m]=await Promise.all([Hp(e.transcriptPath,{turns:r}),nf(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:m!==null,sentSlices:!1,timings:g};let y=c&&a?Qp(c,a):null,_=_R(r,m,{repoRoot:e.repoRoot,relativize:y},t()),b=m===null?null:ji(m)?.canonical_session_id??null,k=e.coordSessionId??b,v=Kp(p,f,{client_session_id:k,client:"claude-code",coordination_session_ids:d},"live_bridge",_);return await e.post(v,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:g}}function lG(e,t){try{return e()}catch{return t}}var aG,kR=w(()=>{"use strict";ur();bR();aG=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(cG,"sessionIdsFor");s(wR,"ingestSessionEnd");s(lG,"safe")});var NR={};ee(NR,{FLUSH_LOCK_KEY:()=>Wm,INLINE_BUDGET:()=>qm,SESSION_END_WORKER:()=>Vm,SWEEP_MAX_KEYS:()=>ER,SWEEP_MIN_AGE_MS:()=>SR,WORKER_BUDGET:()=>xR,WORKER_DEADLINE_MS:()=>Km,drainSession:()=>zm,fetchCostContext:()=>RR,flushUnderLock:()=>IR,gitResolvers:()=>TR,liveJobDeps:()=>Sl,postIngest:()=>CR,postIngestOnce:()=>Gm,processJob:()=>xl,runSessionEndWorker:()=>pG,sweepPending:()=>AR});import{execFileSync as dG}from"node:child_process";import{existsSync as vR,statSync as uG}from"node:fs";async function RR(e,t,n,r,o){if(n===null)return null;let[i,...a]=r;try{return await qt("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 Gm(e,t,n,r,o,i=fetch){let a=new AbortController,c=setTimeout(()=>a.abort(),r);try{let l=await i(ml,{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=Bp(Up(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 CR(e,t,n,r,o,i={}){let a=i.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=await Gm(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 Gm(e,t,n,o.postMs,r,i.fetchImpl),l=2),{...c,attempts:l}}function Bm(e,t){try{let n=dG("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function TR(){let e=new Map,t=new Map;return{repoRootOf:s(n=>vR(n)?Bm(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let o=Bm(["-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=Bm(["-C",n,"config","--get","remote.origin.url"]),i=o?un(o):null;return t.set(n,i),i},"projectKeyOfRoot"),isDir:s(n=>{try{return uG(n).isDirectory()}catch{return!1}},"isDir")}}async function xl(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(!vR(e.transcript_path))a.outcome="transcript_gone";else{let l=TR(),d=t.memoryPath??ho,u=null,p=await wR({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(()=>Fi(d),"knownCheckouts"),rememberCheckouts:s(m=>Hi(d,m),"rememberCheckouts")}:{},fetchContext:s(async(m,g)=>{let y=n();try{return await t.fetchContext(m,g)}finally{i.context=n()-y}},"fetchContext"),post:s(async(m,g)=>{let y=n();u=await t.post(m,g),i.post=n()-y},"post"),connection:s(m=>gR({ownSnapshotAgeMs:e.presence.own_snapshot_age_ms,sawMaindCall:m,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 zm(e,t,n,r={}){let o=r.now??Date.now,i=r.maxRounds??20,a=0;for(;a<i&&Fm(e,t,o());){try{let c=pR(e,t);if(c===null)break;let l=Date.parse(c.queued_at),d=Number.isFinite(l)&&o()-l>aR?{ts:new Date(o()).toISOString(),bridge:H,session_id:c.session_id,outcome:"expired",ms:{queued:o()-l}}:await n(c);$o(e,d),fR(e,t),a++}finally{Hm(e,t)}if(!uR(e,t))break}return a}async function AR(e,t,n,r={}){let o=r.now??Date.now,i=0;for(let a of mR(e)){if(i>=ER)break;if(a===t)continue;let c=hR(e,a);c===null||o()-c<SR||await zm(e,a,n,{...r,maxRounds:1})>0&&i++}return i}async function IR(e,t,n=Date.now){if(!Fm(e,Wm,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{Hm(e,Wm)}}function Sl(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,o)=>RR(e,t,r,o,n.contextMs),"fetchContext"),post:s((r,o)=>CR(e,t,r,o,n),"post"),flush:s(()=>IR(Yt,()=>kl(n.flushMs)),"flush"),memoryAllowed:fc()}}async function pG(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{$o(Yt,{ts:new Date().toISOString(),bridge:H,session_id:t,outcome:"deadline",ms:{total:Km}}),process.exit(0)},Km);n.unref();try{let r=z();if(!r)return 0;let o=le(),i=s(a=>xl(a,Sl(r,o,xR)),"run");await zm(Yt,t,i),await AR(Yt,t,i)}catch(r){$o(Yt,{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 Vm,xR,qm,Km,SR,ER,Wm,Jm=w(()=>{"use strict";ur();ie();En();Am();hs();me();Ue();mc();yR();kR();Um();Vm="session-end-run",xR={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},qm={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},Km=3*6e4,SR=2*6e4,ER=3;s(RR,"fetchCostContext");s(Gm,"postIngestOnce");s(CR,"postIngest");s(Bm,"git");s(TR,"gitResolvers");s(xl,"processJob");s(zm,"drainSession");s(AR,"sweepPending");Wm="metrics-flush";s(IR,"flushUnderLock");s(Sl,"liveJobDeps");s(pG,"runSessionEndWorker")});var $R={};ee($R,{buildJob:()=>PR,enqueueAndSpawn:()=>MR,presenceLookup:()=>OR,runOnSessionEnd:()=>bG,transcriptToIngest:()=>DR});import{spawn as fG}from"node:child_process";import{existsSync as mG,unlinkSync as hG}from"node:fs";import{join as gG}from"node:path";function OR(e,t,n,r){let o=null,i={own_snapshot_age_ms:null,presence_usable:!1};try{if(i.presence_usable=e!==null&&!zf(process.env,te()),e!==null){let a=Cr(Sr(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=nR(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 DR(e,t=process.env){let n=So(e);return n&&!Cn(Yi(e,t))?n:""}function PR(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,os(t.transcriptPath,n),t.nowMs);return{...r,project_key:o,coord_session_id:i.coordSessionId,presence:i.evidence}}function MR(e,t={}){let n=t.dir??Yt,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let o=$m(e.session_id);try{dR(n,e)}catch{return!1}try{return(t.spawnWorker??yG)(r,o,e.cwd),!0}catch{try{hG(gG(n,`${o}.job.json`))}catch{}return!1}}function yG(e,t,n){fG(process.execPath,[e,Vm,t],{detached:!0,stdio:"ignore",cwd:mG(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function _G(e,t){try{let n=await xl(e,Sl(t,le(),qm));$o(Yt,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
1008
+ `)}}async function bG(){let e=[];try{e=ht()}catch{e=[]}try{for(let i of e)TE(Ao(),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 wl(r);let o;try{o=PR(n,{transcriptPath:DR(n),cwd:process.cwd(),nowMs:Date.now(),projectKey:oe,presence:s((i,a,c)=>OR(i,a,c,e),"presence")})}catch{return 0}return MR(o)||await _G(o,t),0}var LR=w(()=>{"use strict";Ve();ie();ul();Ee();Fe();hs();Jf();ts();me();rl();rR();Um();Jm();s(OR,"presenceLookup");s(DR,"transcriptToIngest");s(PR,"buildJob");s(MR,"enqueueAndSpawn");s(yG,"spawnDetachedWorker");s(_G,"runInline");s(bG,"runOnSessionEnd")});var jR={};ee(jR,{runOnSessionBriefing:()=>wG});async function wG(e=process.argv.slice(2)){try{return await Bc("core",await V(),{hostHint:cS(e)})}catch{return 0}}var FR=w(()=>{"use strict";wr();Ee();Fe();s(wG,"runOnSessionBriefing")});var UR={};ee(UR,{deliverSessionReminder:()=>HR,runOnSessionReminder:()=>SG});import{readFile as kG}from"node:fs/promises";import{homedir as vG}from"node:os";import{join as xG}from"node:path";async function HR(e,t={}){let n=t.target??pe(e);if(!Re(n,{kind:"text",event:"SessionStart"}))return 0;let r;try{r=await kG(xG(t.homeDir??vG(),Di),"utf8")}catch{return 0}if(r.length===0)return 0;let o=ge(n,{kind:"text",event:"SessionStart",text:r});return o!==null&&await(t.write??Mc)(o),0}async function SG(){try{return await HR(await V())}catch{return 0}}var BR=w(()=>{"use strict";he();Ee();Fe();s(HR,"deliverSessionReminder");s(SG,"runOnSessionReminder")});var YR={};ee(YR,{CURSOR_BRIEFING_MARKER:()=>Ym,CURSOR_DELIVERY_LOG:()=>KR,CURSOR_UNAVAILABLE_TEXT:()=>WR,appendDelivery:()=>zR,cursorProjectDir:()=>GR,deliverCursorSessionStart:()=>qR,formatCursorBriefing:()=>VR,runOnCursorSessionStart:()=>PG});import{appendFile as EG,mkdir as RG,readFile as CG,stat as TG,writeFile as AG}from"node:fs/promises";import{dirname as IG,join as NG}from"node:path";function GR(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 VR(e,t,n){let o=`${Ym}${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 Hc(o,n,e)}async function qR(e,t={}){let n=t.write??JR,r=t.env??process.env,o=(t.apiKey??z)();if(o===null)return await n(`{}
1009
+ `),0;let i=GR(e,r),a=i===null?null:(t.projectKeyFor??xt)(i),c=await Ro(a,o,{fetcher:s(p=>hr({...p,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=WR,d="none";else{let p=VR(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})+`
1010
+ `),await zR(t.logFile??KR,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Lo(e.conversation_id)??Lo(e.session_id),transcript_path:Lo(e.transcript_path)??Lo(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Lo(e.cursor_version)??Lo(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function PG(){try{return await qR(await V())}catch{try{await JR(`{}
1011
+ `)}catch{}return 0}}async function zR(e,t){try{if(await RG(IG(e),{recursive:!0,mode:448}),await EG(e,JSON.stringify(t)+`
1012
+ `,{mode:384}),(await TG(e)).size>OG){let n=(await CG(e,"utf8")).split(`
1013
+ `).filter(r=>r.trim().length>0);await AG(e,n.slice(-DG).join(`
1014
1014
  `)+`
1015
- `,{mode:384})}}catch{}}function zR(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var Jm,BR,IG,NG,Lo,GR,YR=w(()=>{"use strict";oe();wr();En();Uc();me();Ee();qe();Jm="[maind] Cursor session briefing",BR=AG(Ae,"cursor","deliveries.jsonl"),IG=512*1024,NG=2e3,Lo=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(KR,"cursorProjectDir");GR=`${Jm} 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(WR,"formatCursorBriefing");s(VR,"deliverCursorSessionStart");s(OG,"runOnCursorSessionStart");s(qR,"appendDelivery");s(zR,"writeStdout")});function DG(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 XR(e,t,n=process.stdout){let r=DG(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
1015
+ `,{mode:384})}}catch{}}function JR(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var Ym,KR,OG,DG,Lo,WR,XR=w(()=>{"use strict";ie();wr();En();Uc();me();Ee();qe();Ym="[maind] Cursor session briefing",KR=NG(Ae,"cursor","deliveries.jsonl"),OG=512*1024,DG=2e3,Lo=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(GR,"cursorProjectDir");WR=`${Ym} 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(VR,"formatCursorBriefing");s(qR,"deliverCursorSessionStart");s(PG,"runOnCursorSessionStart");s(zR,"appendDelivery");s(JR,"writeStdout")});function MG(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 ZR(e,t,n=process.stdout){let r=MG(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
1016
1016
  `),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 uo)i.push(await Mi(o,l));for(let l of i)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
1017
1017
  `);let a=i.some(l=>l.detail==="user declined"),c=i.some(l=>l.status==="failed");return r.dryRun?(n.write(`
1018
1018
  [dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
@@ -1023,9 +1023,9 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
1023
1023
  check: maind-mcp-bridge guard status
1024
1024
  Takes effect for NEW Claude Code sessions (hooks are read at session start).
1025
1025
  `),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
1026
- `),c?1:0)}var ZR=w(()=>{"use strict";he();tc();Ct();s(DG,"parseGuardInstallFlags");s(XR,"runGuardInstall")});import{existsSync as QR}from"node:fs";import{appendFile as PG,mkdir as MG,readFile as $G}from"node:fs/promises";import{join as LG}from"node:path";function Ym(e,t=El){return LG(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function jo(e,t=El){return QR(Ym(e,t))}async function Nn(e,t,n=El){try{await MG(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await PG(Ym(e,n),r+`
1027
- `,{mode:384})}catch{}}async function Ar(e,t=El){try{let n=Ym(e,t);if(!QR(n))return[];let r=[];for(let o of(await $G(n,"utf8")).split(`
1028
- `))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"||!jG.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var El,jG,ys=w(()=>{"use strict";ft();El=Af,jG=new Set(["fail","ok","nudge","skip","prompt"]);s(Ym,"triggerLogPath");s(jo,"hasTriggerLog");s(Nn,"appendTriggerEvent");s(Ar,"loadTriggerEvents")});import{existsSync as FG}from"node:fs";import{mkdir as HG,readFile as UG,rename as BG,writeFile as KG}from"node:fs/promises";import{dirname as GG,join as WG}from"node:path";function _s(e=process.env){let t=z();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??qi,keyFp:Zr(t)}}async function Xm(e,t=Date.now(),n=Rl){try{if(!FG(n))return null;let r=JSON.parse(await UG(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:fl([i?.difficulty,i?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-o<VG}}catch{return null}}async function zG(e,t,n,r){try{await HG(GG(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 KG(i,JSON.stringify(o,null,2),{mode:384}),await BG(i,r)}catch{}}async function JG(){let e=z();if(e===null)return null;let t=null;try{t=re()}catch{t=null}let n=await qt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:YG(),projectKey:t,bridgeVersion:H,timeoutMs:qG});if(n===null)return null;try{return fl(JSON.parse(n))}catch{return null}}async function Fo(e,t={}){let n=t.nowMs??Date.now(),r=t.file??Rl,o=t.identity===void 0?_s():t.identity;if(o===null)return us;let i=await Xm(o,n,r);if(i?.fresh)return i.policy;if(e){let a=await(t.fetcher??JG)();if(a!==null)return await zG(o,a,n,r),a}return i?.policy??us}function YG(){try{return ce()}catch{return null}}var Rl,VG,qG,Ho=w(()=>{"use strict";Po();Ht();oe();me();Ue();En();ft();Rl=WG(Ie,"trigger-policy.json"),VG=12*60*60*1e3,qG=3e3;s(_s,"currentIdentity");s(Xm,"readCachedPolicy");s(zG,"writeCachedPolicy");s(JG,"fetchTriggerPolicy");s(Fo,"resolveTriggerPolicy");s(YG,"safeDeviceId")});var tC={};Q(tC,{runGuard:()=>tW});import{existsSync as XG,readFileSync as ZG}from"node:fs";import{homedir as eC}from"node:os";import{join as QG}from"node:path";async function tW(e){let t=e[0],n=e.slice(1);switch(t){case"install":return XR(n,eC());case"status":return rW();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
1026
+ `),c?1:0)}var QR=w(()=>{"use strict";he();tc();Ct();s(MG,"parseGuardInstallFlags");s(ZR,"runGuardInstall")});import{existsSync as eC}from"node:fs";import{appendFile as $G,mkdir as LG,readFile as jG}from"node:fs/promises";import{join as FG}from"node:path";function Xm(e,t=El){return FG(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function jo(e,t=El){return eC(Xm(e,t))}async function Nn(e,t,n=El){try{await LG(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await $G(Xm(e,n),r+`
1027
+ `,{mode:384})}catch{}}async function Ar(e,t=El){try{let n=Xm(e,t);if(!eC(n))return[];let r=[];for(let o of(await jG(n,"utf8")).split(`
1028
+ `))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"||!HG.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var El,HG,ys=w(()=>{"use strict";ft();El=If,HG=new Set(["fail","ok","nudge","skip","prompt"]);s(Xm,"triggerLogPath");s(jo,"hasTriggerLog");s(Nn,"appendTriggerEvent");s(Ar,"loadTriggerEvents")});import{existsSync as UG}from"node:fs";import{mkdir as BG,readFile as KG,rename as GG,writeFile as WG}from"node:fs/promises";import{dirname as VG,join as qG}from"node:path";function _s(e=process.env){let t=z();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??qi,keyFp:Zr(t)}}async function Zm(e,t=Date.now(),n=Rl){try{if(!UG(n))return null;let r=JSON.parse(await KG(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:fl([i?.difficulty,i?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-o<zG}}catch{return null}}async function YG(e,t,n,r){try{await BG(VG(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 WG(i,JSON.stringify(o,null,2),{mode:384}),await GG(i,r)}catch{}}async function XG(){let e=z();if(e===null)return null;let t=null;try{t=oe()}catch{t=null}let n=await qt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:ZG(),projectKey:t,bridgeVersion:H,timeoutMs:JG});if(n===null)return null;try{return fl(JSON.parse(n))}catch{return null}}async function Fo(e,t={}){let n=t.nowMs??Date.now(),r=t.file??Rl,o=t.identity===void 0?_s():t.identity;if(o===null)return us;let i=await Zm(o,n,r);if(i?.fresh)return i.policy;if(e){let a=await(t.fetcher??XG)();if(a!==null)return await YG(o,a,n,r),a}return i?.policy??us}function ZG(){try{return le()}catch{return null}}var Rl,zG,JG,Ho=w(()=>{"use strict";Po();Ht();ie();me();Ue();En();ft();Rl=qG(Ie,"trigger-policy.json"),zG=12*60*60*1e3,JG=3e3;s(_s,"currentIdentity");s(Zm,"readCachedPolicy");s(YG,"writeCachedPolicy");s(XG,"fetchTriggerPolicy");s(Fo,"resolveTriggerPolicy");s(ZG,"safeDeviceId")});var nC={};ee(nC,{runGuard:()=>rW});import{existsSync as QG,readFileSync as eW}from"node:fs";import{homedir as tC}from"node:os";import{join as tW}from"node:path";async function rW(e){let t=e[0],n=e.slice(1);switch(t){case"install":return ZR(n,tC());case"status":return iW();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
1029
1029
  `),1):(await _r({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
1030
1030
  `),0)}case"off":return await _r({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
1031
1031
  `),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>
@@ -1033,71 +1033,71 @@ Takes effect for NEW Claude Code sessions (hooks are read at session start).
1033
1033
  `),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>
1034
1034
  `),1):(await _r(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.
1035
1035
  `:`${t} trigger disabled on this machine (your convention prefs are unchanged).
1036
- `),0)}case"skip":return nW(n);default:return process.stdout.write(eW),t===void 0||t==="--help"||t==="-h"?0:1}}async function nW(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]
1037
- `),1;let o=n.trim().slice(0,500);if(r!=="consult")return await Nn(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await ne({event:"override",session_id:t,reason:o,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
1036
+ `),0)}case"skip":return oW(n);default:return process.stdout.write(nW),t===void 0||t==="--help"||t==="-h"?0:1}}async function oW(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]
1037
+ `),1;let o=n.trim().slice(0,500);if(r!=="consult")return await Nn(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await re({event:"override",session_id:t,reason:o,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
1038
1038
  logged (auditable) in ${br}
1039
- `),0;let i=await zt(t);return await He(t,{...i,override_reason:o}),await ne({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.
1039
+ `),0;let i=await zt(t);return await He(t,{...i,override_reason:o}),await re({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.
1040
1040
  logged (auditable) in ${br}
1041
- `),0}async function rW(){let e=ye(),t=QG(eC(),".claude","settings.json"),n=null;try{XG(t)&&(n=ZG(t,"utf8"))}catch{}let r=Me(n,{},uo),o=await _S(),i=_s(),a=i?await Xm(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:Xi(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:Rl},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:o,events_file:br},null,2)+`
1041
+ `),0}async function iW(){let e=ye(),t=tW(tC(),".claude","settings.json"),n=null;try{QG(t)&&(n=eW(t,"utf8"))}catch{}let r=Me(n,{},uo),o=await bS(),i=_s(),a=i?await Zm(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:Xi(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:Rl},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:o,events_file:br},null,2)+`
1042
1042
  `);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(`
1043
1043
  [maind] guard hook wiring is incomplete:
1044
1044
  `);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
1045
- `);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 eW,nC=w(()=>{"use strict";Lc();he();Ct();ZR();Jt();ft();ys();Ho();eW=["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(`
1046
- `);s(tW,"runGuard");s(nW,"runGuardSkip");s(rW,"runGuardStatus")});var iC={};Q(iC,{bashOutputOf:()=>rC,consultedAtOf:()=>Cl,outcomeFromHook:()=>oC,runGuardDifficulty:()=>iW});function rC(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(`
1047
- `):null,interrupted:t.interrupted===!0}}function oC(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"?rC(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 Cl(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 oW(e,t,n){if(!jo(e))return;let r=await Ar(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let o=Oo(r,null,n);await Nn(e,{t:n,k:"ok",v:t});let i=o.chain;i!==null&&i.failures.length>=4&&!o.resolved&&i.lastVerb===t&&await ne({event:"difficulty_resolved",session_id:e,detail:String(i.failures.length)})}async function iW(){try{let e=ye();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await V();if(pt(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=oC(t);if(r===null)return 0;let o=ym(r.outcome);if(o===null)return 0;let i=Date.now();if(o.kind==="ok")return await oW(n,o.verb,i),0;await Nn(n,{t:i,k:"fail",v:o.verb});let a=await Ar(n),c=Oo(a,Cl(await te(),n),i);if(!wm(c)||c.chain===null)return 0;let l=await Fo(!0);if(!e.difficulty||!Do(l.difficulty))return 0;await Nn(n,{t:i,k:"nudge"});let d=ps(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?Pc(d):zi(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await ne({event:"difficulty_nudge",session_id:n,cwd:u,project_key:re()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Zm=w(()=>{"use strict";Po();Ee();Fe();Ji();qe();me();Ct();Jt();ys();Ho();s(rC,"bashOutputOf");s(oC,"outcomeFromHook");s(Cl,"consultedAtOf");s(oW,"recordSuccess");s(iW,"runGuardDifficulty")});var lC={};Q(lC,{decideDifficultyGate:()=>cC,decideGate:()=>aC,runGuardGate:()=>cW});function aC(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:sC(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. "+sC(n)}:{kind:"deny",reason:sW(e.sessionId,n)}}function sC(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 sW(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:
1045
+ `);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 nW,rC=w(()=>{"use strict";Lc();he();Ct();QR();Jt();ft();ys();Ho();nW=["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(`
1046
+ `);s(rW,"runGuard");s(oW,"runGuardSkip");s(iW,"runGuardStatus")});var sC={};ee(sC,{bashOutputOf:()=>oC,consultedAtOf:()=>Cl,outcomeFromHook:()=>iC,runGuardDifficulty:()=>aW});function oC(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(`
1047
+ `):null,interrupted:t.interrupted===!0}}function iC(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"?oC(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 Cl(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 sW(e,t,n){if(!jo(e))return;let r=await Ar(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let o=Oo(r,null,n);await Nn(e,{t:n,k:"ok",v:t});let i=o.chain;i!==null&&i.failures.length>=4&&!o.resolved&&i.lastVerb===t&&await re({event:"difficulty_resolved",session_id:e,detail:String(i.failures.length)})}async function aW(){try{let e=ye();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await V();if(pt(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=iC(t);if(r===null)return 0;let o=_m(r.outcome);if(o===null)return 0;let i=Date.now();if(o.kind==="ok")return await sW(n,o.verb,i),0;await Nn(n,{t:i,k:"fail",v:o.verb});let a=await Ar(n),c=Oo(a,Cl(await ne(),n),i);if(!km(c)||c.chain===null)return 0;let l=await Fo(!0);if(!e.difficulty||!Do(l.difficulty))return 0;await Nn(n,{t:i,k:"nudge"});let d=ps(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?Pc(d):zi(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await re({event:"difficulty_nudge",session_id:n,cwd:u,project_key:oe()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Qm=w(()=>{"use strict";Po();Ee();Fe();Ji();qe();me();Ct();Jt();ys();Ho();s(oC,"bashOutputOf");s(iC,"outcomeFromHook");s(Cl,"consultedAtOf");s(sW,"recordSuccess");s(aW,"runGuardDifficulty")});var dC={};ee(dC,{decideDifficultyGate:()=>lC,decideGate:()=>cC,runGuardGate:()=>dW});function cC(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:aC(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. "+aC(n)}:{kind:"deny",reason:cW(e.sessionId,n)}}function aC(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 cW(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:
1048
1048
  1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
1049
1049
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
1050
- After ${Tl} denies this gate downgrades itself to warn.`}function cC(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. "+ps(n.chain)}:{kind:"deny",reason:aW(n,e.sessionId)}}function aW(e,t){return`[maind guard | block] Edit denied \u2014 ${Em(e.chain)}. Two exits:
1050
+ After ${Tl} denies this gate downgrades itself to warn.`}function lC(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. "+ps(n.chain)}:{kind:"deny",reason:lW(n,e.sessionId)}}function lW(e,t){return`[maind guard | block] Edit denied \u2014 ${Rm(e.chain)}. Two exits:
1051
1051
  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.
1052
1052
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
1053
- After ${Tl} denies this gate downgrades itself to warn.`}async function cW(){try{let e=ye();if(e.mode==="off")return 0;let t=await V();if(pt(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 zt(r),i=Cl(await te(),r),a=i!==null,c=aC({mode:e.mode,session:o,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=re()??void 0;if(c.kind==="deny")return process.stdout.write(gr(c.reason)),await He(r,{...o,deny_count:(o.deny_count??0)+1}),await ne({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(yr(c.context)),await He(r,{...o,warned:!0,edits_seen:(o.edits_seen??0)+1}),await ne({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&jo(r)){let u=Oo(await Ar(r),i,Date.now()),p=u.open?cC({mode:e.mode,enabled:e.difficulty,denyCapable:xm((await Fo(!1)).difficulty),status:u,session:o,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(gr(p.reason)),await He(r,{...o,difficulty_deny_count:(o.difficulty_deny_count??0)+1}),await ne({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(yr(p.context)),await He(r,{...o,difficulty_breaker_warned:!0,edits_seen:(o.edits_seen??0)+1}),0}return await He(r,{...o,edits_seen:(o.edits_seen??0)+1}),0}catch{return 0}}var Tl,dC=w(()=>{"use strict";Po();Ee();Fe();Ji();qe();me();Ct();Zm();Jt();ft();ys();Ho();Tl=3;s(aC,"decideGate");s(sC,"warnText");s(sW,"denyText");s(cC,"decideDifficultyGate");s(aW,"difficultyDenyText");s(cW,"runGuardGate")});var pC={};Q(pC,{decideStopGate:()=>uC,runGuardStop:()=>dW});function uC(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function dW(){try{let e=ye();if(e.mode==="off"||!e.stopGate)return 0;let t=await V();if(pt(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 zt(n),o=(await te()).guard_signals?.[n]?.reviewed_at!==void 0;return uC({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:lW})),await He(n,{...r,stop_blocked:!0}),await ne({event:"stop_block",session_id:n})),0}catch{return 0}}var lW,fC=w(()=>{"use strict";Ee();Fe();qe();Ct();Jt();ft();s(uC,"decideStopGate");lW="[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(dW,"runGuardStop")});var gC={};Q(gC,{capturedAtOf:()=>mC,decideCapture:()=>hC,runGuardCapture:()=>uW});function mC(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 hC(e){if(e.stopHookActive||!Do(e.policy.capture))return null;let t=km(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Rm(t)}}async function uW(){try{let e=ye();if(e.mode==="off"||!e.capture)return 0;let t=await V();if(pt(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!jo(n))return 0;let r=hC({events:await Ar(n),capturedAtMs:mC(await te(),n),policy:await Fo(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await Nn(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await ne({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var yC=w(()=>{"use strict";Po();Ee();Fe();qe();Ct();Jt();ys();Ho();s(mC,"capturedAtOf");s(hC,"decideCapture");s(uW,"runGuardCapture")});import{appendFile as pW,mkdir as fW,readFile as bC,rename as wC,writeFile as kC}from"node:fs/promises";import{homedir as vC}from"node:os";import{join as xC}from"node:path";function SC(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 Ir(){return xC(vC(),".maind","gateway","attest-spool.jsonl")}async function Qm(e){let t=z();if(t===null)return!1;let n=await qt("gateway_attest",{...e},{apiKey:t,deviceId:ce(),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 EC(e){try{await fW(xC(vC(),".maind","gateway"),{recursive:!0}),await pW(Ir(),JSON.stringify(e)+`
1054
- `,{mode:384}),await mW()}catch{}}async function mW(){try{let t=(await bC(Ir(),"utf8")).split(`
1055
- `).filter(r=>r.trim());if(t.length<=_C)return;let n=`${Ir()}.${process.pid}.tmp`;await kC(n,t.slice(-_C).join(`
1053
+ After ${Tl} denies this gate downgrades itself to warn.`}async function dW(){try{let e=ye();if(e.mode==="off")return 0;let t=await V();if(pt(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 zt(r),i=Cl(await ne(),r),a=i!==null,c=cC({mode:e.mode,session:o,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=oe()??void 0;if(c.kind==="deny")return process.stdout.write(gr(c.reason)),await He(r,{...o,deny_count:(o.deny_count??0)+1}),await re({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(yr(c.context)),await He(r,{...o,warned:!0,edits_seen:(o.edits_seen??0)+1}),await re({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&jo(r)){let u=Oo(await Ar(r),i,Date.now()),p=u.open?lC({mode:e.mode,enabled:e.difficulty,denyCapable:Sm((await Fo(!1)).difficulty),status:u,session:o,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(gr(p.reason)),await He(r,{...o,difficulty_deny_count:(o.difficulty_deny_count??0)+1}),await re({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(yr(p.context)),await He(r,{...o,difficulty_breaker_warned:!0,edits_seen:(o.edits_seen??0)+1}),0}return await He(r,{...o,edits_seen:(o.edits_seen??0)+1}),0}catch{return 0}}var Tl,uC=w(()=>{"use strict";Po();Ee();Fe();Ji();qe();me();Ct();Qm();Jt();ft();ys();Ho();Tl=3;s(cC,"decideGate");s(aC,"warnText");s(cW,"denyText");s(lC,"decideDifficultyGate");s(lW,"difficultyDenyText");s(dW,"runGuardGate")});var fC={};ee(fC,{decideStopGate:()=>pC,runGuardStop:()=>pW});function pC(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function pW(){try{let e=ye();if(e.mode==="off"||!e.stopGate)return 0;let t=await V();if(pt(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 zt(n),o=(await ne()).guard_signals?.[n]?.reviewed_at!==void 0;return pC({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:uW})),await He(n,{...r,stop_blocked:!0}),await re({event:"stop_block",session_id:n})),0}catch{return 0}}var uW,mC=w(()=>{"use strict";Ee();Fe();qe();Ct();Jt();ft();s(pC,"decideStopGate");uW="[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(pW,"runGuardStop")});var yC={};ee(yC,{capturedAtOf:()=>hC,decideCapture:()=>gC,runGuardCapture:()=>fW});function hC(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 gC(e){if(e.stopHookActive||!Do(e.policy.capture))return null;let t=vm(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Cm(t)}}async function fW(){try{let e=ye();if(e.mode==="off"||!e.capture)return 0;let t=await V();if(pt(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!jo(n))return 0;let r=gC({events:await Ar(n),capturedAtMs:hC(await ne(),n),policy:await Fo(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await Nn(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await re({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var _C=w(()=>{"use strict";Po();Ee();Fe();qe();Ct();Jt();ys();Ho();s(hC,"capturedAtOf");s(gC,"decideCapture");s(fW,"runGuardCapture")});import{appendFile as mW,mkdir as hW,readFile as wC,rename as kC,writeFile as vC}from"node:fs/promises";import{homedir as xC}from"node:os";import{join as SC}from"node:path";function EC(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 Ir(){return SC(xC(),".maind","gateway","attest-spool.jsonl")}async function eh(e){let t=z();if(t===null)return!1;let n=await qt("gateway_attest",{...e},{apiKey:t,deviceId:le(),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 RC(e){try{await hW(SC(xC(),".maind","gateway"),{recursive:!0}),await mW(Ir(),JSON.stringify(e)+`
1054
+ `,{mode:384}),await gW()}catch{}}async function gW(){try{let t=(await wC(Ir(),"utf8")).split(`
1055
+ `).filter(r=>r.trim());if(t.length<=bC)return;let n=`${Ir()}.${process.pid}.tmp`;await vC(n,t.slice(-bC).join(`
1056
1056
  `)+`
1057
- `,{mode:384}),await wC(n,Ir())}catch{}}async function RC(){let e;try{e=(await bC(Ir(),"utf8")).split(`
1058
- `).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 Qm(o)||(n=!0,t.push(r))}try{let r=`${Ir()}.${process.pid}.tmp`;await kC(r,t.length>0?t.join(`
1057
+ `,{mode:384}),await kC(n,Ir())}catch{}}async function CC(){let e;try{e=(await wC(Ir(),"utf8")).split(`
1058
+ `).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 eh(o)||(n=!0,t.push(r))}try{let r=`${Ir()}.${process.pid}.tmp`;await vC(r,t.length>0?t.join(`
1059
1059
  `)+`
1060
- `:"",{mode:384}),await wC(r,Ir())}catch{}}var _C,CC=w(()=>{"use strict";oe();En();Ue();_C=256;s(SC,"aggregateWindow");s(Ir,"attestSpoolPath");s(Qm,"postAttestation");s(EC,"spoolAttestation");s(mW,"capSpool");s(RC,"flushAttestSpool")});function bs(e=process.env,t=ee()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Al(e=process.env,t=ee()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function TC(e,t=We()){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 B(t,JSON.stringify(r,null,2)+`
1061
- `,384)}async function AC(e,t=We()){await TC({gateway_mode:e},t)}async function IC(e,t=We()){await TC({gateway_attest:e},t)}function NC(e=process.env,t=ee()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var eh=w(()=>{"use strict";Ve();se();s(bs,"resolveGatewayMode");s(Al,"resolveGatewayAttest");s(TC,"writeGatewayConfigPatch");s(AC,"writeGatewayMode");s(IC,"writeGatewayAttest");s(NC,"resolveShaProofMode")});function DC(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"&&hW.has(o.severity)?o.severity:"recommended",u=typeof o.summary=="string"?o.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function gW(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function PC(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)gW(i,e,t)&&(o===null||OC[i.severity]>OC[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function MC(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 hW,OC,th=w(()=>{"use strict";hW=new Set(["required","recommended","info"]);s(DC,"extractGatewayRules");OC={required:2,recommended:1,info:0};s(gW,"ruleMatches");s(PC,"decideToolCall");s(MC,"policyDenyText")});import{mkdirSync as yW,readFileSync as _W,renameSync as bW,writeFileSync as wW}from"node:fs";import{homedir as kW}from"node:os";import{dirname as vW,join as xW}from"node:path";function $C(){return xW(kW(),".maind","gateway","policy-cache.json")}function Il(e,t,n=new Date().toISOString()){try{let r={version:nh,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=$C();yW(vW(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;wW(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),bW(i,o)}catch{}}function Nl(e){try{let t=_W($C(),"utf8"),n=JSON.parse(t);return n.version!==nh||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:nh,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var nh,rh=w(()=>{"use strict";nh=1;s($C,"policyCachePath");s(Il,"writePolicyCache");s(Nl,"readPolicyCache")});function ws(e=process.env){let t=e.MAIND_MCP_URL??qi,n=z();return{mcpUrl:t,keyFp:n?Zr(n):"anon"}}async function Ol(e=6e3){let t=z();if(t===null)return null;let n=null;try{n=re()}catch{n=null}let r=await qt("get_conventions",{},{apiKey:t,deviceId:ce(),projectKey:n,bridgeVersion:H,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return DC(o)}var oh=w(()=>{"use strict";Ht();oe();En();me();Ue();th();s(ws,"policyIdentity");s(Ol,"fetchGatewayRules")});function ks(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 SW(e){if(ks(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 EW(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:ks(e)?{action:"skip",reason:"already-wrapped"}:SW(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function LC(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 jC(e){if(!ks(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 FC(e){return Object.entries(e).map(([t,n])=>{let r=EW(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var HC=w(()=>{"use strict";s(ks,"isGatewayWrapped");s(SW,"isMaindProxyEntry");s(EW,"classifyServer");s(LC,"wrapServerEntry");s(jC,"unwrapServerEntry");s(FC,"planRewrites")});var VC={};Q(VC,{runGatewayInstall:()=>NW,runGatewayUninstall:()=>OW});import{existsSync as RW,readFileSync as CW}from"node:fs";import{homedir as TW}from"node:os";import{join as UC}from"node:path";import{createInterface as AW}from"node:readline";function BC(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 KC(){return[{label:"Claude Code (project .mcp.json)",path:UC(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:UC(TW(),".claude.json")}]}async function GC(e){let t=AW({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 WC(e){let t=IW(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 IW(e){try{return RW(e)?CW(e,"utf8"):null}catch{return null}}async function NW(e){let t=BC(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1062
- `),2;let n=ve({entryPath:ie(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let o of KC()){let i=WC(o.path);if(i===null){process.stderr.write(` skipped ${o.label} \u2014 no mcpServers object
1063
- `);continue}let a=FC(i.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${o.label} \xB7 ${c.key} \u2014 ${c.reason}
1064
- `);continue}if(!(t.yes||await GC(`Wrap MCP server '${c.key}' in ${o.label} with the maind gateway?
1060
+ `:"",{mode:384}),await kC(r,Ir())}catch{}}var bC,TC=w(()=>{"use strict";ie();En();Ue();bC=256;s(EC,"aggregateWindow");s(Ir,"attestSpoolPath");s(eh,"postAttestation");s(RC,"spoolAttestation");s(gW,"capSpool");s(CC,"flushAttestSpool")});function bs(e=process.env,t=te()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Al(e=process.env,t=te()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function AC(e,t=We()){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 B(t,JSON.stringify(r,null,2)+`
1061
+ `,384)}async function IC(e,t=We()){await AC({gateway_mode:e},t)}async function NC(e,t=We()){await AC({gateway_attest:e},t)}function OC(e=process.env,t=te()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var th=w(()=>{"use strict";Ve();ae();s(bs,"resolveGatewayMode");s(Al,"resolveGatewayAttest");s(AC,"writeGatewayConfigPatch");s(IC,"writeGatewayMode");s(NC,"writeGatewayAttest");s(OC,"resolveShaProofMode")});function PC(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"&&yW.has(o.severity)?o.severity:"recommended",u=typeof o.summary=="string"?o.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function _W(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function MC(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)_W(i,e,t)&&(o===null||DC[i.severity]>DC[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function $C(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 yW,DC,nh=w(()=>{"use strict";yW=new Set(["required","recommended","info"]);s(PC,"extractGatewayRules");DC={required:2,recommended:1,info:0};s(_W,"ruleMatches");s(MC,"decideToolCall");s($C,"policyDenyText")});import{mkdirSync as bW,readFileSync as wW,renameSync as kW,writeFileSync as vW}from"node:fs";import{homedir as xW}from"node:os";import{dirname as SW,join as EW}from"node:path";function LC(){return EW(xW(),".maind","gateway","policy-cache.json")}function Il(e,t,n=new Date().toISOString()){try{let r={version:rh,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=LC();bW(SW(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;vW(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),kW(i,o)}catch{}}function Nl(e){try{let t=wW(LC(),"utf8"),n=JSON.parse(t);return n.version!==rh||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:rh,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var rh,oh=w(()=>{"use strict";rh=1;s(LC,"policyCachePath");s(Il,"writePolicyCache");s(Nl,"readPolicyCache")});function ws(e=process.env){let t=e.MAIND_MCP_URL??qi,n=z();return{mcpUrl:t,keyFp:n?Zr(n):"anon"}}async function Ol(e=6e3){let t=z();if(t===null)return null;let n=null;try{n=oe()}catch{n=null}let r=await qt("get_conventions",{},{apiKey:t,deviceId:le(),projectKey:n,bridgeVersion:H,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return PC(o)}var ih=w(()=>{"use strict";Ht();ie();En();me();Ue();nh();s(ws,"policyIdentity");s(Ol,"fetchGatewayRules")});function ks(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 RW(e){if(ks(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 CW(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:ks(e)?{action:"skip",reason:"already-wrapped"}:RW(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function jC(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 FC(e){if(!ks(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 HC(e){return Object.entries(e).map(([t,n])=>{let r=CW(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var UC=w(()=>{"use strict";s(ks,"isGatewayWrapped");s(RW,"isMaindProxyEntry");s(CW,"classifyServer");s(jC,"wrapServerEntry");s(FC,"unwrapServerEntry");s(HC,"planRewrites")});var qC={};ee(qC,{runGatewayInstall:()=>DW,runGatewayUninstall:()=>PW});import{existsSync as TW,readFileSync as AW}from"node:fs";import{homedir as IW}from"node:os";import{join as BC}from"node:path";import{createInterface as NW}from"node:readline";function KC(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 GC(){return[{label:"Claude Code (project .mcp.json)",path:BC(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:BC(IW(),".claude.json")}]}async function WC(e){let t=NW({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 VC(e){let t=OW(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 OW(e){try{return TW(e)?AW(e,"utf8"):null}catch{return null}}async function DW(e){let t=KC(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1062
+ `),2;let n=ve({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let o of GC()){let i=VC(o.path);if(i===null){process.stderr.write(` skipped ${o.label} \u2014 no mcpServers object
1063
+ `);continue}let a=HC(i.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${o.label} \xB7 ${c.key} \u2014 ${c.reason}
1064
+ `);continue}if(!(t.yes||await WC(`Wrap MCP server '${c.key}' in ${o.label} with the maind gateway?
1065
1065
  Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
1066
1066
  The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${o.label} \xB7 ${c.key}
1067
- `);continue}i.servers[c.key]=LC(i.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${o.label} \xB7 ${c.key}
1067
+ `);continue}i.servers[c.key]=jC(i.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${o.label} \xB7 ${c.key}
1068
1068
  `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await B(o.path,JSON.stringify(i.raw,null,2)+`
1069
1069
  `,384)}return process.stderr.write(r>0?`
1070
1070
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
1071
1071
  `:`
1072
1072
  Nothing to wrap.
1073
- `),0}async function OW(e){let t=BC(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1074
- `),2;let n=0;for(let r of KC()){let o=WC(r.path);if(o===null)continue;let i=!1;for(let[a,c]of Object.entries(o.servers)){if(!ks(c)||!(t.yes||await GC(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=jC(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
1073
+ `),0}async function PW(e){let t=KC(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1074
+ `),2;let n=0;for(let r of GC()){let o=VC(r.path);if(o===null)continue;let i=!1;for(let[a,c]of Object.entries(o.servers)){if(!ks(c)||!(t.yes||await WC(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=FC(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
1075
1075
  `);continue}o.servers[a]=d,i=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
1076
1076
  `)}!t.dryRun&&i&&await B(r.path,JSON.stringify(o.raw,null,2)+`
1077
1077
  `,384)}return process.stderr.write(n>0?`
1078
1078
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
1079
1079
  `:`
1080
1080
  Nothing wrapped \u2014 nothing to restore.
1081
- `),0}var qC=w(()=>{"use strict";se();St();HC();s(BC,"parseFlags");s(KC,"targets");s(GC,"confirm");s(WC,"loadConfig");s(IW,"readFileSafeSync");s(NW,"runGatewayInstall");s(OW,"runGatewayUninstall")});var zC={};Q(zC,{runGatewayAttest:()=>PW,runGatewayMode:()=>DW,runGatewayPolicy:()=>LW});async function DW(e){let t=e[0];if(t===void 0){let n=bs(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1081
+ `),0}var zC=w(()=>{"use strict";ae();St();UC();s(KC,"parseFlags");s(GC,"targets");s(WC,"confirm");s(VC,"loadConfig");s(OW,"readFileSafeSync");s(DW,"runGatewayInstall");s(PW,"runGatewayUninstall")});var JC={};ee(JC,{runGatewayAttest:()=>$W,runGatewayMode:()=>MW,runGatewayPolicy:()=>FW});async function MW(e){let t=e[0];if(t===void 0){let n=bs(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1082
1082
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
1083
- `),2):(await AC(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
1083
+ `),2):(await IC(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
1084
1084
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
1085
1085
  `:`Convention policy is off; only explicit --deny-tool flags apply.
1086
- `)),0)}async function PW(e){let t=e[0];if(t===void 0){let n=Al(),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)":""}.
1086
+ `)),0)}async function $W(e){let t=e[0];if(t===void 0){let n=Al(),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)":""}.
1087
1087
  `+(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.
1088
1088
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
1089
- `),2):(await IC(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.
1089
+ `),2):(await NC(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.
1090
1090
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
1091
- `),0)}function MW(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1091
+ `),0)}function LW(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1092
1092
  `;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})
1093
- `}return t}function $W(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 LW(e){let t=e.includes("--refresh"),n=bs(),r=ws();if(t){let i=await Ol();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1093
+ `}return t}function jW(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 FW(e){let t=e.includes("--refresh"),n=bs(),r=ws();if(t){let i=await Ol();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1094
1094
  `):(Il(r,i),process.stdout.write(`maind: policy refreshed (${i.length} rule(s)).
1095
1095
  `))}let o=Nl(r);return process.stdout.write(`maind: gateway mode '${n}'
1096
1096
  `),o===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
1097
- `),0):(process.stdout.write(`maind: policy from cache (${$W(o)}, ${r.mcpUrl}):
1098
- `),process.stdout.write(MW(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.
1099
- `),0)}var JC=w(()=>{"use strict";eh();rh();oh();s(DW,"runGatewayMode");s(PW,"runGatewayAttest");s(MW,"renderRules");s($W,"cacheAge");s(LW,"runGatewayPolicy")});var eT={};Q(eT,{gatewayEventsFile:()=>ZC,parseGatewayArgs:()=>QC,runGateway:()=>WW});import{spawn as jW}from"node:child_process";import{appendFile as FW,mkdir as HW}from"node:fs/promises";import{homedir as YC}from"node:os";import{basename as UW,join as XC}from"node:path";import{createInterface as BW}from"node:readline";function ZC(){return XC(YC(),".maind","gateway","events.jsonl")}async function GW(e){try{let t=ZC();await HW(XC(YC(),".maind","gateway"),{recursive:!0}),await FW(t,JSON.stringify(e)+`
1100
- `,{mode:384})}catch{}}function QC(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 WW(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:R}=await Promise.resolve().then(()=>(qC(),VC));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(()=>(JC(),zC));return e[0]==="mode"?R(e.slice(1)):e[0]==="attest"?S(e.slice(1)):P(e.slice(1))}let t=QC(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1097
+ `),0):(process.stdout.write(`maind: policy from cache (${jW(o)}, ${r.mcpUrl}):
1098
+ `),process.stdout.write(LW(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.
1099
+ `),0)}var YC=w(()=>{"use strict";th();oh();ih();s(MW,"runGatewayMode");s($W,"runGatewayAttest");s(LW,"renderRules");s(jW,"cacheAge");s(FW,"runGatewayPolicy")});var tT={};ee(tT,{gatewayEventsFile:()=>QC,parseGatewayArgs:()=>eT,runGateway:()=>qW});import{spawn as HW}from"node:child_process";import{appendFile as UW,mkdir as BW}from"node:fs/promises";import{homedir as XC}from"node:os";import{basename as KW,join as ZC}from"node:path";import{createInterface as GW}from"node:readline";function QC(){return ZC(XC(),".maind","gateway","events.jsonl")}async function VW(e){try{let t=QC();await BW(ZC(XC(),".maind","gateway"),{recursive:!0}),await UW(t,JSON.stringify(e)+`
1100
+ `,{mode:384})}catch{}}function eT(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 qW(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:R}=await Promise.resolve().then(()=>(zC(),qC));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(()=>(YC(),JC));return e[0]==="mode"?R(e.slice(1)):e[0]==="attest"?S(e.slice(1)):P(e.slice(1))}let t=eT(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1101
1101
  maind-mcp-bridge gateway install [--yes] [--dry-run]
1102
1102
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1103
1103
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -1107,50 +1107,50 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
1107
1107
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
1108
1108
  install/uninstall rewrite Claude Code MCP configs (consent per server).
1109
1109
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
1110
- `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??UW(o),c=bs(),l=NC(),d=l==="off"?null:As(),u=c==="off"?[]:Nl(ws())?.rules??[];c!=="off"&&Ol().then(S=>{S!==null&&(u=S,Il(ws(),S))}).catch(()=>{});let p=[],f=Al()&&z()!==null&&c!=="off",m=null;try{m=re()}catch{m=null}let g=Promise.resolve(),y=s(S=>{g=g.then(()=>GW(S)),f&&p.push(S)},"record"),_=s(async()=>{if(!f)return;let S=SC(p.splice(0),c,a,m);S!==null&&(await Qm(S)||await EC(S))},"attestAndReset");f&&RC().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let k=jW(o,i,{stdio:["pipe","pipe","inherit"]});k.stdout.pipe(process.stdout),k.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(S)}
1111
- `),process.exitCode=1});let v=BW({input:process.stdin,terminal:!1});v.on("line",S=>{let R=Ih(S);if(R.kind==="request"&&R.method==="tools/call"&&R.toolName){if(n.has(R.toolName)&&R.id!==void 0){process.stdout.write(Nr(R.id,R.toolName)+`
1112
- `),y(Hl("deny",a,R.toolName,Date.now()));return}let P=PC(R.toolName,a,u,c);if(P.kind==="deny"&&R.id!==void 0){process.stdout.write(Nr(R.id,R.toolName,MC(R.toolName,P.rule))+`
1110
+ `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??KW(o),c=bs(),l=OC(),d=l==="off"?null:As(),u=c==="off"?[]:Nl(ws())?.rules??[];c!=="off"&&Ol().then(S=>{S!==null&&(u=S,Il(ws(),S))}).catch(()=>{});let p=[],f=Al()&&z()!==null&&c!=="off",m=null;try{m=oe()}catch{m=null}let g=Promise.resolve(),y=s(S=>{g=g.then(()=>VW(S)),f&&p.push(S)},"record"),_=s(async()=>{if(!f)return;let S=EC(p.splice(0),c,a,m);S!==null&&(await eh(S)||await RC(S))},"attestAndReset");f&&CC().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let k=HW(o,i,{stdio:["pipe","pipe","inherit"]});k.stdout.pipe(process.stdout),k.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(S)}
1111
+ `),process.exitCode=1});let v=GW({input:process.stdin,terminal:!1});v.on("line",S=>{let R=Nh(S);if(R.kind==="request"&&R.method==="tools/call"&&R.toolName){if(n.has(R.toolName)&&R.id!==void 0){process.stdout.write(Nr(R.id,R.toolName)+`
1112
+ `),y(Hl("deny",a,R.toolName,Date.now()));return}let P=MC(R.toolName,a,u,c);if(P.kind==="deny"&&R.id!==void 0){process.stdout.write(Nr(R.id,R.toolName,$C(R.toolName,P.rule))+`
1113
1113
  `),y(Ul("policy_deny",a,R.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));return}(P.kind==="warn"||P.kind==="deny")&&y(Ul("policy_warn",a,R.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));let K=Is(S,d);if(K.length>0){let x=K.find(j=>j.verdict==="fabricated");if(x!==void 0&&l==="enforce"&&c==="enforce"&&R.id!==void 0&&x!==void 0&&R.id!==void 0){process.stdout.write(Nr(R.id,R.toolName,Or(x,!0))+`
1114
1114
  `),y(Bl("sha_deny",a,R.toolName,Date.now()));return}let D=x??K[0];process.stderr.write(`[maind gateway] ${Or(D,!1)}
1115
1115
  `),y(Bl("sha_warn",a,R.toolName,Date.now()))}y(Hl("tool_call",a,R.toolName,Date.now()))}k.stdin.write(S+`
1116
- `)}),v.on("close",()=>{k.stdin.end()});let E=await new Promise(S=>{k.on("exit",(R,P)=>{S(R??(P?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(S=>setTimeout(S,KW).unref())]),await _(),E}var KW,tT=w(()=>{"use strict";Kl();CC();eh();th();Gl();rh();oh();oe();me();s(ZC,"gatewayEventsFile");KW=5e3;s(GW,"logEvent");s(QC,"parseGatewayArgs");s(WW,"runGateway")});var uh={};Q(uh,{MAX_ENTRIES:()=>ih,TTL_MS:()=>ch,crossSessionDir:()=>lh,decideCrossSession:()=>oT,parseSessionDb:()=>rT,pruneDb:()=>dh,runGuardCrossCheck:()=>e2,runGuardCrossObserve:()=>QW,staleReason:()=>sh});import{mkdir as VW,readFile as qW,readdir as zW,stat as nT,unlink as JW,writeFile as YW}from"node:fs/promises";import{homedir as XW}from"node:os";import{join as ah}from"node:path";function lh(){return ah(XW(),".maind","cross-session")}function rT(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 dh(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=ch);return n.length>ih&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-ih)),{files:Object.fromEntries(n),warned:e.warned}}function oT(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function sh(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 iT(e){let t=lh();return await VW(t,{recursive:!0}),ah(t,`${e}.json`)}async function sT(e,t){try{let n=await qW(await iT(e),"utf8");return dh(rT(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function aT(e,t){try{await YW(await iT(e),JSON.stringify(t),{mode:384})}catch{}}async function ZW(e){try{let t=lh();for(let n of await zW(t)){if(!n.endsWith(".json"))continue;let r=ah(t,n),o=await nT(r).catch(()=>null);o&&e-o.mtimeMs>ch&&await JW(r).catch(()=>{})}}catch{}}async function cT(e){try{return(await nT(e)).mtimeMs}catch{return}}async function QW(e,t=Date.now()){try{if(ye().mode==="off")return 0;let r=e??await V();if(pt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=rt(r);if(!o||!i)return 0;let a=await cT(i);if(a===void 0)return 0;let c=await sT(o,t);return c.files[i]={m:a,t},delete c.warned[i],await aT(o,dh(c,t)),await ZW(t),0}catch{return 0}}async function e2(e,t=Date.now()){try{let n=ye();if(n.mode==="off")return 0;let r=e??await V();if(pt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=rt(r);if(!o||!i)return 0;let a=await sT(o,t),c=oT(a.files[i]?.m,await cT(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(gr(sh(i,c))+`
1117
- `),await ne({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(yr(sh(i,c))+`
1118
- `),a.warned[i]=c.current,await aT(o,a),await ne({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var ch,ih,ph=w(()=>{"use strict";Ee();Fe();Ji();Ct();Jt();ch=48*3600*1e3,ih=500;s(lh,"crossSessionDir");s(rT,"parseSessionDb");s(dh,"pruneDb");s(oT,"decideCrossSession");s(sh,"staleReason");s(iT,"dbPath");s(sT,"loadDb");s(aT,"saveDb");s(ZW,"sweepStaleSessionFiles");s(cT,"fileMtime");s(QW,"runGuardCrossObserve");s(e2,"runGuardCrossCheck")});var fh={};Q(fh,{INDEX_REFRESH_WORKER:()=>lT,acquireLock:()=>Xc,releaseLock:()=>es,runIndexRefreshWorker:()=>s2,runOnIndexRefresh:()=>i2});import{spawn as t2}from"node:child_process";import{existsSync as n2}from"node:fs";import{join as r2}from"node:path";function o2(e){return r2(e,".maind","code-index.sqlite")}async function i2(){try{let e=await V(),t=je(typeof e.cwd=="string"?e.cwd:process.cwd());if(!n2(o2(t))||!Xc(t))return 0;let n=process.argv[1];if(n===void 0)return es(t),0;t2(process.execPath,[n,lT,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function s2(){let e=process.argv[3]??je();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Nc(),Sf)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{es(e)}return 0}var lT,mh=w(()=>{"use strict";Ee();Sn();Hf();lT="index-refresh-run";s(o2,"indexDbPath");s(i2,"runOnIndexRefresh");s(s2,"runIndexRefreshWorker")});function Ml(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 Dl(e){return e.length<3||/^\d+$/.test(e)||dT.has(e)||dT.has(Ml(e))}function l2(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function d2(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function pT(e){let t=new Set,n=new Set,r=[];for(let o of e.matchAll(u2)){let i=o[0],a=i.toLowerCase();if(r.push(a),/[._-]/.test(i)){let c=d2(a);c.length>=4&&!uT.has(c)&&n.add(c)}for(let c of l2(i)){let l=c.toLowerCase();Dl(l)||t.add(Ml(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]}`;uT.has(i)||n.add(i)}return{words:t,compounds:n}}function p2(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 fT(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function gh(e){if(!e)return[];let t=[];for(let n of e.split(`
1119
- `)){let r=f2.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 m2(e){let t=e.shortId.split("-"),n=new Set;for(let i of t)Dl(i)||n.add(Ml(i));let r=new Set;for(let i=0;i+1<t.length;i++)!Dl(t[i])&&!Dl(t[i+1])&&r.add(`${t[i]}-${t[i+1]}`);let o=pT(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 mT(e,t,n=3,r=[]){if(t.length===0)return[];let o=new Set([...r].map(f=>Ml(f.toLowerCase()))),i=t.map(m2),a=new Map,c=new Map;for(let f of i){let m=new Set([...f.keyWords,...f.keyCompounds]);for(let g of m)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...m,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=i.length,d=s(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=pT(p2(e));for(let f of o)u.words.delete(f);let p=[];for(let f of i){let m=new Set;for(let k of u.words)f.keyWords.has(k)&&m.add(k);for(let k of u.compounds)f.keyCompounds.has(k)&&m.add(k);let g=new Set;for(let k of u.words)!m.has(k)&&f.summaryWords.has(k)&&g.add(k);if(m.size===0&&g.size===0)continue;let y=0;for(let k of m)y+=2*d(k);for(let k of g)y+=d(k);let _=[...m].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),b=m.size>=1&&m.size+g.size>=2&&y>=h2;!_&&!b||p.push({convention:f.convention,score:y,matched:[...m,...g]})}return p.sort((f,m)=>m.score-f.score||f.convention.id.localeCompare(m.convention.id)).slice(0,n)}function _2(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function hT(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("/")||g2.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!_2(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||y2.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 hh(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function yT(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 Pl(t-gT);if(!o.tryAdd(`${a2} 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}): ${hh(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?` '${hh(y.signature,70)}'`:""}`}).join("; "),m=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${m>0?` (+${m} 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+=`
1120
- (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:i,symbolNames:a}}function w2(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>b2}function k2(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 v2(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function _T(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=w2(e.range,i)&&a.length>0;if(o.length===0&&e.importers.length===0&&!c)return null;let l=k2([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new Pl(t-gT),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${c2} ${e.relPath} as the local code index knows it (the index matches this file on disk).${u}`))return null;let p=!1;if(c&&d.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let g="",y=0;for(let b of a){let k=`${b.qualifiedName} L${b.startLine}`,v=g.length===0?k:`${g} \xB7 ${k}`;if(v.length>500)break;g=v,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=>`${v2(E.caller,l)}${E.kind==="calls"?"":` [${E.kind}]`}`),b=y.length-_.length,k=g.signature?` '${hh(g.signature,80)}'`:"",v=`- ${g.qualifiedName} L${g.startLine}${k} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!d.tryAdd(v)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(k=>k.slice(l.length)),y=e.importers.length-g.length,_=e.importers.length,b=`Imported by ${_} file${_===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(b)||(p=!0)}e.hidden>0&&!p&&d.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let f=e.unchecked??0;if(f>0&&!p&&d.tryAdd(`(+${f} more reference${f===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),d.size<=1)return null;let m=d.toString();return p&&(m+=`
1121
- (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var a2,c2,dT,uT,u2,f2,h2,g2,y2,Pl,gT,b2,bT=w(()=>{"use strict";a2="[maind context \xB7 prompt]",c2="[maind context \xB7 read]",dT=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+/)),uT=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(Ml,"stem");s(Dl,"isNoise");s(l2,"splitParts");s(d2,"normalizeCompound");u2=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(pT,"termsOf");s(p2,"promptForMatching");s(fT,"repoNameWords");f2=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(gh,"parseConventionLines");s(m2,"profileOf");h2=4.5;s(mT,"matchConventions");g2=/\.(?: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,y2=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(_2,"looksLikeCode");s(hT,"extractSymbolCandidates");s(hh,"clip");Pl=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(`
1122
- `)}},gT=90;s(yT,"renderPromptContext");b2=2e3;s(w2,"isPartialRead");s(k2,"commonDir");s(v2,"callerLabel");s(_T,"renderReadContext")});import{createHash as x2}from"node:crypto";import{existsSync as wT,mkdirSync as S2,readdirSync as E2,rmSync as R2,statSync as C2,writeFileSync as T2}from"node:fs";import{join as $l}from"node:path";function yh(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function N2(e,t,n=null,r=I2){try{for(let o of E2(e)){let i=$l(e,o);if(i!==n)try{t-C2(i).mtimeMs>r&&R2(i,{recursive:!0,force:!0})}catch{}}}catch{}}var A2,I2,vs,kT=w(()=>{"use strict";qe();A2=$l(Ae,"context"),I2=7*24*60*60*1e3;s(yh,"safe");vs=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=A2){let o=n?`${yh(t)}__${yh(n)}`:yh(t);return new e(r,$l(r,o))}fileFor(t){return $l(this.dir,x2("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return wT(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{wT(this.dir)||(S2(this.dir,{recursive:!0,mode:448}),N2(this.root,n,this.dir));for(let r of t)try{T2(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(N2,"sweepStaleScopes")});var wh={};Q(wh,{INDEX_RELPATH:()=>yn,SOFT_BUDGET_MS:()=>ST,findRepoRoot:()=>_n,isMachinePrompt:()=>TT,loadCachedConventions:()=>RT,promptContextFor:()=>IT,promptTextOf:()=>CT,readContextFor:()=>NT,runOnPromptContext:()=>H2,runOnReadContext:()=>B2});import{existsSync as vT,readFileSync as O2,realpathSync as D2,statSync as P2}from"node:fs";import{dirname as M2,isAbsolute as xT,join as xs,relative as $2,sep as L2}from"node:path";function j2(e,t){let n=$2(e,t);return!n||n.startsWith("..")||xT(n)?null:n.split(L2).join("/")}function bh(e){try{let t=P2(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function ET(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Nc(),Sf));return t(e)}function RT(e,t={}){try{let n=t.identity===void 0?_s():t.identity;if(e!==null&&n!==null){let r=wa(e,n),o=Fc(r?.result.instructions??null),i=gh(o);if(i.length>0)return i}}catch{}try{let n=JSON.parse(O2(t.briefingCacheFile??Eo,"utf8"));if(typeof n.conventions=="string")return gh(n.conventions)}catch{}return[]}function CT(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function TT(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 AT(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 F2(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,_h)),c=new Set;for(let[d,u]of a){let p=bh(xs(t,d));p!==null&&_i(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,m=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));m.length>0&&l.push({candidate:d,locations:m,total:f.length})}return l}catch{return[]}finally{try{o.close()}catch{}}}async function IT(e,t={}){let n=t.now??Date.now,r=n(),o=t.env??process.env,i=pe(e,o,t.readConfig??ee);if(!Re(i,{kind:"context",event:"UserPromptSubmit"}))return null;let a=CT(e);if(a.trim().length===0||TT(e,a))return null;let c=AT(e);if(c===null)return null;let l=vs.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:$c(i,o)??process.cwd(),u=_n(d),p=c.agentId===null?(t.assignedNotice??((v,E)=>fs(v,E,{hostPids:ht()})))(c.sessionId,d):null,f=p===null?null:`[maind] ${p}`,m=mT(a,(t.loadConventions??RT)(u),6,fT(u)).filter(v=>!l.has(`conv:${v.convention.id}@${v.convention.version}`)).slice(0,3),g=hT(a).filter(v=>!l.has(`sym:${u??""}:${v.name}`)),y=u===null?null:xs(u,yn),_=g.length>0&&y!==null&&u!==null&&vT(y)&&n()-r<ST?await F2(g,u,y,t.openReader??ET):[],b=yT({repoRoot:u,conventions:m,symbols:_});if(b===null)return f;let k=new Map(m.map(v=>[v.convention.id,v.convention.version]));return l.mark([...b.conventionIds.map(v=>`conv:${v}@${k.get(v)??0}`),...b.symbolNames.map(v=>`sym:${u??""}:${v}`)],n()),f===null?b.text:`${f}
1123
-
1124
- ${b.text}`}async function H2(){try{let e=await V(),t=await IT(e);if(t!==null){let n=ge(pe(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function U2(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 NT(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=pe(e,t.env??process.env,t.readConfig??ee);if(!Re(r,{kind:"context",event:"PreToolUse"}))return null;let o=rt(e);if(!o||Gr(o)===null||ei(o))return null;let i=AT(e);if(i===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=xT(o)?o:xs(a,o),l;try{l=D2(c)}catch{return null}let d=_n(M2(l));if(d===null)return null;let u=xs(d,yn);if(!vT(u))return null;let p=j2(d,l);if(p===null)return null;let f=await(t.openReader??ET)(u);try{let m=f.meta();if(!m.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=bh(l);if(y===null||!_i(g,y))return null;let _=vs.forScope(i.sessionId,i.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let k=f.symbolsInFile(p),v=m.edgesDirty?[]:f.callersOfFile(p),E=m.edgesDirty?[]:f.importersOf(p),S=[...new Set([...v.map(Z=>Z.caller.filePath),...E])],R=S.slice(0,_h),P=new Set(S.slice(_h)),K=f.files(R),x=new Set;for(let Z of R){let ot=K.get(Z),Es=ot===void 0?null:bh(xs(d,Z));ot!==void 0&&Es!==null&&_i(ot,Es)&&x.add(Z)}let T=s(Z=>v.filter(ot=>Z.has(ot.caller.filePath)).length+E.filter(ot=>Z.has(ot)).length,"countIn"),D=v.filter(Z=>x.has(Z.caller.filePath)).map(Z=>({calleeKey:Z.calleeKey,kind:Z.kind,caller:{nodeKey:Z.caller.nodeKey,kind:Z.caller.kind,qualifiedName:Z.caller.qualifiedName,filePath:Z.caller.filePath,startLine:Z.caller.startLine}})),j=E.filter(Z=>x.has(Z)),At=T(P),Ss=v.length-D.length+(E.length-j.length)-At,Uo=_T({relPath:p,symbols:k,callers:D,importers:j,hidden:Ss,unchecked:At,range:U2(e)});return Uo===null?null:(_.mark([b],n()),Uo)}finally{f.close()}}async function B2(){try{let e=await V(),t=await NT(e);if(t!==null){let n=ge(pe(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var ST,_h,kh=w(()=>{"use strict";dn();Ve();Uc();wr();Ho();Ht();bT();kT();Cm();hs();hc();Ee();Fe();ST=200,_h=200;s(j2,"repoRelative");s(bh,"diskStat");s(ET,"openReader");s(RT,"loadCachedConventions");s(CT,"promptTextOf");s(TT,"isMachinePrompt");s(AT,"scopeOf");s(F2,"locateSymbols");s(IT,"promptContextFor");s(H2,"runOnPromptContext");s(U2,"readRangeOf");s(NT,"readContextFor");s(B2,"runOnReadContext")});import{randomUUID as K2}from"node:crypto";Ko();import{createInterface as uP}from"node:readline";var MT=[["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 $T(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of MT)if(t.includes(n))return r;return null}s($T,"mapClientInfoNameToFamily");function Ch(e){let t;try{t=JSON.parse(e)}catch{return null}if(!jl(t)||t.method!=="initialize")return null;let n=t.params;if(!jl(n))return null;let r=n.clientInfo;if(!jl(r))return null;let o=r.name,i=$T(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(Ch,"tryExtractInitializeClient");function jl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(jl,"isRecord");import{fileURLToPath as LT}from"node:url";var Fl="maind-bridge-",jT=8,Th=8e3;function Xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Xt,"isRecord");function FT(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Xt(t)||t.method!=="initialize"||!Xt(t.params))return!1;let n=t.params.capabilities;return Xt(n)&&Xt(n.roots)}catch{return!1}}s(FT,"clientDeclaresRoots");function HT(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(HT,"isInitializedNotification");function UT(e){if(!Xt(e)||!Xt(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Xt(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=LT(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=jT)break}return n}s(UT,"rootPathsFrom");var Ts=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(Xt(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&&HT(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=Th){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 Ah(e,t,n=Th){return FT(e)?UT(await t.request("roots/list",n)):null}s(Ah,"listClientRoots");Kl();Gl();function Wl(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(`
1116
+ `)}),v.on("close",()=>{k.stdin.end()});let E=await new Promise(S=>{k.on("exit",(R,P)=>{S(R??(P?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(S=>setTimeout(S,WW).unref())]),await _(),E}var WW,nT=w(()=>{"use strict";Kl();TC();th();nh();Gl();oh();ih();ie();me();s(QC,"gatewayEventsFile");WW=5e3;s(VW,"logEvent");s(eT,"parseGatewayArgs");s(qW,"runGateway")});var ph={};ee(ph,{MAX_ENTRIES:()=>sh,TTL_MS:()=>lh,crossSessionDir:()=>dh,decideCrossSession:()=>iT,parseSessionDb:()=>oT,pruneDb:()=>uh,runGuardCrossCheck:()=>n2,runGuardCrossObserve:()=>t2,staleReason:()=>ah});import{mkdir as zW,readFile as JW,readdir as YW,stat as rT,unlink as XW,writeFile as ZW}from"node:fs/promises";import{homedir as QW}from"node:os";import{join as ch}from"node:path";function dh(){return ch(QW(),".maind","cross-session")}function oT(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 uh(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=lh);return n.length>sh&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-sh)),{files:Object.fromEntries(n),warned:e.warned}}function iT(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function ah(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 sT(e){let t=dh();return await zW(t,{recursive:!0}),ch(t,`${e}.json`)}async function aT(e,t){try{let n=await JW(await sT(e),"utf8");return uh(oT(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function cT(e,t){try{await ZW(await sT(e),JSON.stringify(t),{mode:384})}catch{}}async function e2(e){try{let t=dh();for(let n of await YW(t)){if(!n.endsWith(".json"))continue;let r=ch(t,n),o=await rT(r).catch(()=>null);o&&e-o.mtimeMs>lh&&await XW(r).catch(()=>{})}}catch{}}async function lT(e){try{return(await rT(e)).mtimeMs}catch{return}}async function t2(e,t=Date.now()){try{if(ye().mode==="off")return 0;let r=e??await V();if(pt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=rt(r);if(!o||!i)return 0;let a=await lT(i);if(a===void 0)return 0;let c=await aT(o,t);return c.files[i]={m:a,t},delete c.warned[i],await cT(o,uh(c,t)),await e2(t),0}catch{return 0}}async function n2(e,t=Date.now()){try{let n=ye();if(n.mode==="off")return 0;let r=e??await V();if(pt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=rt(r);if(!o||!i)return 0;let a=await aT(o,t),c=iT(a.files[i]?.m,await lT(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(gr(ah(i,c))+`
1117
+ `),await re({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(yr(ah(i,c))+`
1118
+ `),a.warned[i]=c.current,await cT(o,a),await re({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var lh,sh,fh=w(()=>{"use strict";Ee();Fe();Ji();Ct();Jt();lh=48*3600*1e3,sh=500;s(dh,"crossSessionDir");s(oT,"parseSessionDb");s(uh,"pruneDb");s(iT,"decideCrossSession");s(ah,"staleReason");s(sT,"dbPath");s(aT,"loadDb");s(cT,"saveDb");s(e2,"sweepStaleSessionFiles");s(lT,"fileMtime");s(t2,"runGuardCrossObserve");s(n2,"runGuardCrossCheck")});var mh={};ee(mh,{INDEX_REFRESH_WORKER:()=>dT,acquireLock:()=>Xc,releaseLock:()=>es,runIndexRefreshWorker:()=>c2,runOnIndexRefresh:()=>a2});import{spawn as r2}from"node:child_process";import{existsSync as o2}from"node:fs";import{join as i2}from"node:path";function s2(e){return i2(e,".maind","code-index.sqlite")}async function a2(){try{let e=await V(),t=je(typeof e.cwd=="string"?e.cwd:process.cwd());if(!o2(s2(t))||!Xc(t))return 0;let n=process.argv[1];if(n===void 0)return es(t),0;r2(process.execPath,[n,dT,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function c2(){let e=process.argv[3]??je();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Nc(),Ef)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{es(e)}return 0}var dT,hh=w(()=>{"use strict";Ee();Sn();Uf();dT="index-refresh-run";s(s2,"indexDbPath");s(a2,"runOnIndexRefresh");s(c2,"runIndexRefreshWorker")});function Ml(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 Dl(e){return e.length<3||/^\d+$/.test(e)||uT.has(e)||uT.has(Ml(e))}function u2(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function p2(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function fT(e){let t=new Set,n=new Set,r=[];for(let o of e.matchAll(f2)){let i=o[0],a=i.toLowerCase();if(r.push(a),/[._-]/.test(i)){let c=p2(a);c.length>=4&&!pT.has(c)&&n.add(c)}for(let c of u2(i)){let l=c.toLowerCase();Dl(l)||t.add(Ml(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]}`;pT.has(i)||n.add(i)}return{words:t,compounds:n}}function m2(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 mT(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function yh(e){if(!e)return[];let t=[];for(let n of e.split(`
1119
+ `)){let r=h2.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 g2(e){let t=e.shortId.split("-"),n=new Set;for(let i of t)Dl(i)||n.add(Ml(i));let r=new Set;for(let i=0;i+1<t.length;i++)!Dl(t[i])&&!Dl(t[i+1])&&r.add(`${t[i]}-${t[i+1]}`);let o=fT(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 hT(e,t,n=3,r=[]){if(t.length===0)return[];let o=new Set([...r].map(f=>Ml(f.toLowerCase()))),i=t.map(g2),a=new Map,c=new Map;for(let f of i){let m=new Set([...f.keyWords,...f.keyCompounds]);for(let g of m)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...m,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=i.length,d=s(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=fT(m2(e));for(let f of o)u.words.delete(f);let p=[];for(let f of i){let m=new Set;for(let k of u.words)f.keyWords.has(k)&&m.add(k);for(let k of u.compounds)f.keyCompounds.has(k)&&m.add(k);let g=new Set;for(let k of u.words)!m.has(k)&&f.summaryWords.has(k)&&g.add(k);if(m.size===0&&g.size===0)continue;let y=0;for(let k of m)y+=2*d(k);for(let k of g)y+=d(k);let _=[...m].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),b=m.size>=1&&m.size+g.size>=2&&y>=y2;!_&&!b||p.push({convention:f.convention,score:y,matched:[...m,...g]})}return p.sort((f,m)=>m.score-f.score||f.convention.id.localeCompare(m.convention.id)).slice(0,n)}function w2(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function gT(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("/")||_2.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!w2(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||b2.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 gh(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function _T(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 Pl(t-yT);if(!o.tryAdd(`${l2} 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}): ${gh(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?` '${gh(y.signature,70)}'`:""}`}).join("; "),m=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${m>0?` (+${m} 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+=`
1120
+ (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:i,symbolNames:a}}function v2(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>k2}function x2(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 S2(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function bT(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=v2(e.range,i)&&a.length>0;if(o.length===0&&e.importers.length===0&&!c)return null;let l=x2([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new Pl(t-yT),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${d2} ${e.relPath} as the local code index knows it (the index matches this file on disk).${u}`))return null;let p=!1;if(c&&d.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let g="",y=0;for(let b of a){let k=`${b.qualifiedName} L${b.startLine}`,v=g.length===0?k:`${g} \xB7 ${k}`;if(v.length>500)break;g=v,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=>`${S2(E.caller,l)}${E.kind==="calls"?"":` [${E.kind}]`}`),b=y.length-_.length,k=g.signature?` '${gh(g.signature,80)}'`:"",v=`- ${g.qualifiedName} L${g.startLine}${k} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!d.tryAdd(v)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(k=>k.slice(l.length)),y=e.importers.length-g.length,_=e.importers.length,b=`Imported by ${_} file${_===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(b)||(p=!0)}e.hidden>0&&!p&&d.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let f=e.unchecked??0;if(f>0&&!p&&d.tryAdd(`(+${f} more reference${f===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),d.size<=1)return null;let m=d.toString();return p&&(m+=`
1121
+ (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var l2,d2,uT,pT,f2,h2,y2,_2,b2,Pl,yT,k2,wT=w(()=>{"use strict";l2="[maind context \xB7 prompt]",d2="[maind context \xB7 read]",uT=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+/)),pT=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(Ml,"stem");s(Dl,"isNoise");s(u2,"splitParts");s(p2,"normalizeCompound");f2=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(fT,"termsOf");s(m2,"promptForMatching");s(mT,"repoNameWords");h2=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(yh,"parseConventionLines");s(g2,"profileOf");y2=4.5;s(hT,"matchConventions");_2=/\.(?: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,b2=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(w2,"looksLikeCode");s(gT,"extractSymbolCandidates");s(gh,"clip");Pl=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(`
1122
+ `)}},yT=90;s(_T,"renderPromptContext");k2=2e3;s(v2,"isPartialRead");s(x2,"commonDir");s(S2,"callerLabel");s(bT,"renderReadContext")});import{createHash as E2}from"node:crypto";import{existsSync as kT,mkdirSync as R2,readdirSync as C2,rmSync as T2,statSync as A2,writeFileSync as I2}from"node:fs";import{join as $l}from"node:path";function _h(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function D2(e,t,n=null,r=O2){try{for(let o of C2(e)){let i=$l(e,o);if(i!==n)try{t-A2(i).mtimeMs>r&&T2(i,{recursive:!0,force:!0})}catch{}}}catch{}}var N2,O2,vs,vT=w(()=>{"use strict";qe();N2=$l(Ae,"context"),O2=7*24*60*60*1e3;s(_h,"safe");vs=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=N2){let o=n?`${_h(t)}__${_h(n)}`:_h(t);return new e(r,$l(r,o))}fileFor(t){return $l(this.dir,E2("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return kT(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{kT(this.dir)||(R2(this.dir,{recursive:!0,mode:448}),D2(this.root,n,this.dir));for(let r of t)try{I2(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(D2,"sweepStaleScopes")});var kh={};ee(kh,{INDEX_RELPATH:()=>yn,SOFT_BUDGET_MS:()=>ET,findRepoRoot:()=>_n,isMachinePrompt:()=>AT,loadCachedConventions:()=>CT,promptContextFor:()=>NT,promptTextOf:()=>TT,readContextFor:()=>OT,runOnPromptContext:()=>B2,runOnReadContext:()=>G2});import{existsSync as xT,readFileSync as P2,realpathSync as M2,statSync as $2}from"node:fs";import{dirname as L2,isAbsolute as ST,join as xs,relative as j2,sep as F2}from"node:path";function H2(e,t){let n=j2(e,t);return!n||n.startsWith("..")||ST(n)?null:n.split(F2).join("/")}function wh(e){try{let t=$2(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function RT(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Nc(),Ef));return t(e)}function CT(e,t={}){try{let n=t.identity===void 0?_s():t.identity;if(e!==null&&n!==null){let r=wa(e,n),o=Fc(r?.result.instructions??null),i=yh(o);if(i.length>0)return i}}catch{}try{let n=JSON.parse(P2(t.briefingCacheFile??Eo,"utf8"));if(typeof n.conventions=="string")return yh(n.conventions)}catch{}return[]}function TT(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function AT(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 IT(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 U2(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,bh)),c=new Set;for(let[d,u]of a){let p=wh(xs(t,d));p!==null&&_i(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,m=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));m.length>0&&l.push({candidate:d,locations:m,total:f.length})}return l}catch{return[]}finally{try{o.close()}catch{}}}async function NT(e,t={}){let n=t.now??Date.now,r=n(),o=t.env??process.env,i=pe(e,o,t.readConfig??te);if(!Re(i,{kind:"context",event:"UserPromptSubmit"}))return null;let a=TT(e);if(a.trim().length===0||AT(e,a))return null;let c=IT(e);if(c===null)return null;let l=vs.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:$c(i,o)??process.cwd(),u=_n(d),p=c.agentId===null?(t.assignedNotice??((v,E)=>fs(v,E,{hostPids:ht()})))(c.sessionId,d):null,f=p===null?null:`[maind] ${p}`,m=hT(a,(t.loadConventions??CT)(u),6,mT(u)).filter(v=>!l.has(`conv:${v.convention.id}@${v.convention.version}`)).slice(0,3),g=gT(a).filter(v=>!l.has(`sym:${u??""}:${v.name}`)),y=u===null?null:xs(u,yn),_=g.length>0&&y!==null&&u!==null&&xT(y)&&n()-r<ET?await U2(g,u,y,t.openReader??RT):[],b=_T({repoRoot:u,conventions:m,symbols:_});if(b===null)return f;let k=new Map(m.map(v=>[v.convention.id,v.convention.version]));return l.mark([...b.conventionIds.map(v=>`conv:${v}@${k.get(v)??0}`),...b.symbolNames.map(v=>`sym:${u??""}:${v}`)],n()),f===null?b.text:`${f}
1123
+
1124
+ ${b.text}`}async function B2(){try{let e=await V(),t=await NT(e);if(t!==null){let n=ge(pe(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function K2(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 OT(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=pe(e,t.env??process.env,t.readConfig??te);if(!Re(r,{kind:"context",event:"PreToolUse"}))return null;let o=rt(e);if(!o||Gr(o)===null||ei(o))return null;let i=IT(e);if(i===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=ST(o)?o:xs(a,o),l;try{l=M2(c)}catch{return null}let d=_n(L2(l));if(d===null)return null;let u=xs(d,yn);if(!xT(u))return null;let p=H2(d,l);if(p===null)return null;let f=await(t.openReader??RT)(u);try{let m=f.meta();if(!m.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=wh(l);if(y===null||!_i(g,y))return null;let _=vs.forScope(i.sessionId,i.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let k=f.symbolsInFile(p),v=m.edgesDirty?[]:f.callersOfFile(p),E=m.edgesDirty?[]:f.importersOf(p),S=[...new Set([...v.map(Z=>Z.caller.filePath),...E])],R=S.slice(0,bh),P=new Set(S.slice(bh)),K=f.files(R),x=new Set;for(let Z of R){let ot=K.get(Z),Es=ot===void 0?null:wh(xs(d,Z));ot!==void 0&&Es!==null&&_i(ot,Es)&&x.add(Z)}let T=s(Z=>v.filter(ot=>Z.has(ot.caller.filePath)).length+E.filter(ot=>Z.has(ot)).length,"countIn"),D=v.filter(Z=>x.has(Z.caller.filePath)).map(Z=>({calleeKey:Z.calleeKey,kind:Z.kind,caller:{nodeKey:Z.caller.nodeKey,kind:Z.caller.kind,qualifiedName:Z.caller.qualifiedName,filePath:Z.caller.filePath,startLine:Z.caller.startLine}})),j=E.filter(Z=>x.has(Z)),At=T(P),Ss=v.length-D.length+(E.length-j.length)-At,Uo=bT({relPath:p,symbols:k,callers:D,importers:j,hidden:Ss,unchecked:At,range:K2(e)});return Uo===null?null:(_.mark([b],n()),Uo)}finally{f.close()}}async function G2(){try{let e=await V(),t=await OT(e);if(t!==null){let n=ge(pe(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var ET,bh,vh=w(()=>{"use strict";dn();Ve();Uc();wr();Ho();Ht();wT();vT();Tm();hs();hc();Ee();Fe();ET=200,bh=200;s(H2,"repoRelative");s(wh,"diskStat");s(RT,"openReader");s(CT,"loadCachedConventions");s(TT,"promptTextOf");s(AT,"isMachinePrompt");s(IT,"scopeOf");s(U2,"locateSymbols");s(NT,"promptContextFor");s(B2,"runOnPromptContext");s(K2,"readRangeOf");s(OT,"readContextFor");s(G2,"runOnReadContext")});import{randomUUID as W2}from"node:crypto";Ko();import{createInterface as pP}from"node:readline";var $T=[["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 LT(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of $T)if(t.includes(n))return r;return null}s(LT,"mapClientInfoNameToFamily");function Th(e){let t;try{t=JSON.parse(e)}catch{return null}if(!jl(t)||t.method!=="initialize")return null;let n=t.params;if(!jl(n))return null;let r=n.clientInfo;if(!jl(r))return null;let o=r.name,i=LT(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(Th,"tryExtractInitializeClient");function jl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(jl,"isRecord");import{fileURLToPath as jT}from"node:url";var Fl="maind-bridge-",FT=8,Ah=8e3;function Xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Xt,"isRecord");function HT(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Xt(t)||t.method!=="initialize"||!Xt(t.params))return!1;let n=t.params.capabilities;return Xt(n)&&Xt(n.roots)}catch{return!1}}s(HT,"clientDeclaresRoots");function UT(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(UT,"isInitializedNotification");function BT(e){if(!Xt(e)||!Xt(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Xt(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=jT(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=FT)break}return n}s(BT,"rootPathsFrom");var Ts=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(Xt(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&&UT(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=Ah){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 Ih(e,t,n=Ah){return HT(e)?BT(await t.request("roots/list",n)):null}s(Ih,"listClientRoots");Kl();Gl();function Wl(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(`
1125
1125
  `).trim();if(r=[],i.length!==0)try{n.push(JSON.parse(i))}catch{}},"flush");for(let i of t.split(`
1126
- `)){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(Wl,"rpcMessagesOf");function $h(e,t){for(let n of Wl(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($h,"parseCloudToolResponse");Ht();var pP="https://mcp.maind.dev/mcp",bi=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},xa=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=Zr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=fP(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=mP(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 Ts(a=>process.stdout.write(a+`
1127
- `),i!==null&&i.initFrame!==null&&(i.pendingFrame===null||!Qr(i.pendingFrame))),this.shaRepoRoot=As(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??pP}async run(t=Xu()){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 Ah(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=Ch(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Qr(t)&&(this.initFrame=t);let r=yP(t),o=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=Is(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&Ph(p)&&r.id!==null){let m=Or(p,!0);process.stderr.write(`[maind] ${m}
1126
+ `)){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(Wl,"rpcMessagesOf");function Lh(e,t){for(let n of Wl(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(Lh,"parseCloudToolResponse");Ht();var fP="https://mcp.maind.dev/mcp",bi=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},xa=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=Zr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=mP(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=hP(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 Ts(a=>process.stdout.write(a+`
1127
+ `),i!==null&&i.initFrame!==null&&(i.pendingFrame===null||!Qr(i.pendingFrame))),this.shaRepoRoot=As(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??fP}async run(t=Xu()){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 Ih(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=Th(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Qr(t)&&(this.initFrame=t);let r=_P(t),o=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=Is(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&Mh(p)&&r.id!==null){let m=Or(p,!0);process.stderr.write(`[maind] ${m}
1128
1128
  `);let g=r.params?.name;process.stdout.write(Nr(r.id,typeof g=="string"?g:"unknown",m)+`
1129
1129
  `);return}o=Or(f,!1),process.stderr.write(`[maind] ${o}
1130
- `)}if(this.assignedInbox&&!Rh(this.clientFamily)){let p=this.assignedInbox.takeNote();p!==null&&(o=o===null?p:`${o}
1130
+ `)}if(this.assignedInbox&&!Ch(this.clientFamily)){let p=this.assignedInbox.takeNote();p!==null&&(o=o===null?p:`${o}
1131
1131
  [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+`
1132
- `);return}let i=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Qr(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=ka(t);if(this.serveInitializeFromCache(t,p))return;va(p,-32603,`bridge network error: ${Tw(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&&!Qr(t)){let u=await c.text().catch(()=>"");if(Cw(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=ka(t);va(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=ka(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;va(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 Ju(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
1132
+ `);return}let i=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Qr(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=ka(t);if(this.serveInitializeFromCache(t,p))return;va(p,-32603,`bridge network error: ${Aw(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&&!Qr(t)){let u=await c.text().catch(()=>"");if(Tw(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=ka(t);va(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=ka(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;va(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 Ju(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
1133
1133
  `);return}if(Qr(t)){let u=d.startsWith("text/event-stream")?await Ju(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
1134
- `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(o!==null){let u=d.startsWith("text/event-stream")?await Ju(c):await c.text(),p=gP(u,o);p.trim().length>0&&process.stdout.write(p+`
1135
- `);return}if(d.startsWith("text/event-stream"))await hP(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
1136
- `)}}}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 bi(bP(o));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=ka(n);va(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 wP(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&&Cw(l)?{kind:"session_lost",body:l}:a.ok?$h(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:Tw(a),timedOut:_P(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=lt()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Ew(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Qr(t))return!1;let r=wa(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Rw(n,r)+`
1137
- `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ba(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Xu(){return uP({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}s(Xu,"stdinLines");function fP(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(fP,"normalizeClientFamily");function mP(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(mP,"normalizeClientVersion");async function hP(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(`
1134
+ `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(o!==null){let u=d.startsWith("text/event-stream")?await Ju(c):await c.text(),p=yP(u,o);p.trim().length>0&&process.stdout.write(p+`
1135
+ `);return}if(d.startsWith("text/event-stream"))await gP(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
1136
+ `)}}}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 bi(wP(o));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=ka(n);va(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 kP(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&&Tw(l)?{kind:"session_lost",body:l}:a.ok?Lh(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:Aw(a),timedOut:bP(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=lt()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Rw(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Qr(t))return!1;let r=wa(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Cw(n,r)+`
1137
+ `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ba(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Xu(){return pP({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}s(Xu,"stdinLines");function mP(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(mP,"normalizeClientFamily");function hP(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(hP,"normalizeClientVersion");async function gP(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(`
1138
1138
  `).trim();o=[],a.length>0&&process.stdout.write(a+`
1139
1139
  `)},"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(`
1140
- `))!==-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(hP,"pipeSseToStdout");function gP(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(gP,"appendNoteToToolResult");function yP(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(yP,"parseRpc");async function Ju(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(`
1140
+ `))!==-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(gP,"pipeSseToStdout");function yP(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(yP,"appendNoteToToolResult");function _P(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(_P,"parseRpc");async function Ju(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(`
1141
1141
  `).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(`
1142
1142
  `))!==-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(`
1143
- `)}s(Ju,"collectSseText");function ka(e){try{return JSON.parse(e).id??null}catch{return null}}s(ka,"tryExtractId");function Qr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Qr,"isInitializeRequest");function Cw(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(Cw,"isSessionLossBody");function Tw(e){return e instanceof Error?e.message:String(e)}s(Tw,"stringifyErr");function _P(e){return e?.name==="TimeoutError"}s(_P,"isTimeoutError");function va(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
1144
- `)}s(va,"emitJsonRpcError");function bP(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(bP,"extractHint");function wP(e){try{let t=Wl(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(wP,"parsePresenceToolResult");oe();tp();np();Ue();me();Ff();Sn();Sn();import{readFileSync as H1}from"node:fs";import{join as US}from"node:path";function Jc(e){return e?Math.ceil(e.length/4):0}s(Jc,"estimateTokens");var BS=1e6,Yc=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 KS(e){try{let t=H1(e,"utf8");return t.length>BS?t.slice(0,BS):t}catch{return""}}s(KS,"readFileCapped");function U1(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(U1,"distinctFilePaths");function GS(e,t,n,r){try{let o=Jc(n);if(e==="codebase_search"){let i=U1(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=Jc(KS(US(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=Jc(KS(US(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(GS,"measureLocalToolSaved");dn();Sn();import{createHash as cH}from"node:crypto";dn();import{execFileSync as W1}from"node:child_process";import{createHash as V1}from"node:crypto";Sn();Hf();import{realpathSync as YS}from"node:fs";function q1(e,t){try{return YS(e)===YS(t)}catch{return e===t}}s(q1,"samePath");var Uf=30,z1=10,XS=20,J1=new Map;function Bf(e){return e instanceof Error?e.message:String(e)}s(Bf,"msg");function Zc(e){let t=e.split(`
1145
- `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Zc,"firstLine");var ZS=s(e=>e?e.slice(0,12):"?","short");async function Y1(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await JS(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:Bf(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(Y1,"refreshIndex");function X1(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(X1,"isEmptyRange");function Z1(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(Z1,"localOnly");function Q1(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(Q1,"localGradeBlockers");function eH(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=Gu(!1,e.projectKey,e.result);if(!t.persist)return t;let n=Q1(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(eH,"bridgePersistDecision");function QS(e,t){try{return W1("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(QS,"git");function tH(e,t){let n=ri(e),r=n&&QS(e,["merge-base",t,`origin/${n}`])||null,o=QS(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(tH,"gitPersistFacts");function nH(e,t){return V1("sha256").update(`${e??""}
1146
- ${JSON.stringify(t)}`).digest("hex")}s(nH,"payloadKey");function mt(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(mt,"fail");var vr="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function eE(e){let t=Vu(e);if(t!==null&&qu(t))return mt("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 mt("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 mt("cloud_unavailable",`review_verdict failed: ${Zc(t?.detail??e)||"no detail"}`,vr)}s(eE,"fromProtocolText");function rH(e,t,n){switch(e.kind){case"no_session":return mt("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. ${vr}`);case"transport_error":return e.timedOut?mt("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."):mt("cloud_unavailable",`network error: ${e.message}`,vr);case"http_error":return e.status===401?mt("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Zc(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?mt("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."):mt("cloud_unavailable",`HTTP ${e.status}: ${Zc(e.body)}`,vr);case"rpc_error":return eE(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return eE(e.text);let r;try{r=JSON.parse(e.text)}catch{return mt("cloud_unavailable",`review_verdict returned non-JSON text: ${Zc(e.text)}`,vr)}return typeof r!="object"||r===null?mt("cloud_unavailable","review_verdict returned no object",vr):{kind:"verdict",body:r}}}}s(rH,"interpretOutcome");var oH="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).",iH={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"},tE=s(e=>e.map(t=>iH[t]??t).join("; "),"adviceFor");function sH(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: ${tE(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 ${ZS(n)}, but this branch forks off ${o??"the default branch"} at ${ZS(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(sH,"skipText");function aH(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=tE(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=sH(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(aH,"recordHint");async function nE(e,t,n){let r=n.repoRoot??je(),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 ue=xo(c,r);if(ue===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(!q1(ue.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=ue.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??J1,m=[],g=await Y1(i,o,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await i.reviewChanges(Bu(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(X1(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:_,warnings:m};let b;try{b=await i.reviewDetectorScopes({baseRef:l})}catch(ue){let vh=Xe(jt(`reviewDetectorScopes failed: ${Bf(ue)}`));b={commit:vh,local:vh},m.push(`repo-health detectors unavailable (${Bf(ue)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:v}=Ku(y,b.commit);v>0&&m.push(`${v} symbol(s) exceed the server schema (name > ${ya} or qualified name > ${_a} chars) and were left out \u2014 this run is not attestation-grade.`);let E=nH(a,k),S=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",R=eH({persistWanted:u,since:l,projectKey:a,result:y,payload:k,git:S?(n.persistFacts??tH)(o,y.headSha):null,recordedRunId:f.get(E)??null}),P={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:v,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,XS),local_only:Z1(b).slice(0,XS)}},K=await n.callCloudTool("review_verdict",{attest:k,persist:R.persist,...a?{project_key:a}:{}},{timeoutMs:p}),x=rH(K,p,R.persist);if(x.kind==="error")return{ok:!1,error:x.error,message:x.message,hint:x.hint,base:_,local:P,warnings:m};let T=x.body;if(T.ok!==!0){let ue=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:ue?oH:T.hint??vr,base:_,local:P,warnings:m}}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:m};let D=T.attest,j=T.run??null,At=j&&typeof j.id=="string"?{persisted:!0,run_id:j.id,commit_sha:j.commit_sha??null,attestation_format:j.attestation_format??null}:{persisted:!1,reason:R.skipped??T.run_note??"not_persisted",...R.detail?{detail:R.detail}:{}};At.persisted&&f.set(E,j.id);let Ss=typeof D?.attestation_grade=="boolean"?D.attestation_grade:null,Uo=Array.isArray(D?.grade_blockers)?D.grade_blockers:[],Z=T.counts??{},ot=Array.isArray(T.findings)?T.findings:[],Es=`Verdict ${T.verdict??"?"}: ${Z.block??0} block, ${Z.warn??0} warn, ${Z.note??0} note`+(T.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:T.verdict??null,counts:Z,record:At,attest:D?{attestation_grade:Ss,grade_blockers:Uo,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:`${Es} ${aH(At,Ss,Uo,y.headSha)}`,findings:ot.slice(0,Uf).map(ue=>({convention_id:ue.convention_id,convention_version:ue.convention_version,severity:ue.severity,action:ue.action,...ue.downgrade_reason?{downgrade_reason:ue.downgrade_reason}:{},summary:ue.summary,matched_changed_symbols:(ue.matched_changed_symbols??[]).slice(0,z1),matched_symbol_count:ue.matched_symbols?.length??0})),...ot.length>Uf?{findings_not_shown:ot.length-Uf}:{},detector_findings:T.detector_findings??[],policy_source:T.policy_source??null,coverage_note:Wu(y,D?.evaluated_convention_count,v),base:_,local:P,warnings:m}}s(nE,"runAttestReview");var rE=(()=>{let e=Object.keys(li),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Qc(e){return cH("sha256").update(e,"utf8").digest("hex")}s(Qc,"nodeKeyHash");var lH=["module","class","interface","function","method","type_alias","enum","variable"],Kf=[{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:lH,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 "+rE+" \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 "+rE+", 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."}}}}],Gf=new Map([["codebase_review_verdict","attest_review_changes"]]),sE=new Set([...Kf.map(e=>e.name),...Gf.keys()]),Wf=new Set(["attest_review_changes",...[...Gf].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function aE(e,t,n,r){if(!Wf.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 nE(e,n,r),i=Gf.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(aE,"dispatchCloudBackedTool");function _e(e){return typeof e=="string"&&e.length>0?e:void 0}s(_e,"str");function xr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(xr,"num");function oE(e){if(e===void 0)return{repoRoot:je(),scanDirs:void 0};let t=xo(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(oE,"anchorRepo");function iE(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(iE,"dirNotFound");async function cE(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=_e(n.for_path);if(o!==void 0){let u=tS(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 Zn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,m=s(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let 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 v of i){let E=xo(v);if(E===null){p.push(v);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=[],m=[],g=[],y=[];for(let[v,E]of u){let S=[...E],R=S.includes(""),P=await Xn(v,{dirs:R?void 0:S,minFiles:r});f.push({repo_root:v,dirs:R?null:S}),m.push(...P.findings),g.push(...P.facts.namespaces.map(K=>({repo_root:v,dir:K.dir,prefix:K.prefix,file_count:K.fileCount}))),y.push(...P.facts.skipped)}let _=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=je(),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:_e(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=_e(n.dir),o,i;if(r!==void 0){let u=xo(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=je(),i=void 0;let a=tr(o,{dirs:i,baseRef:_e(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=oE(_e(n.dir));if(r===null)return iE("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=er(r.repoRoot,{dirs:r.scanDirs,baseRef:_e(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=oE(_e(n.dir));if(r===null)return iE("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=$u(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:_e(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=_e(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:_e(n.kind),limit:xr(n.limit)})).map(i=>({...i,nodeKeyHash:Qc(i.nodeKey)}))}case"codebase_trace":{let r=_e(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:xr(n.max_depth),limit:xr(n.limit)})}case"codebase_snippet":{let r=_e(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:Qc(r)}}case"codebase_map":return e.getArchitecture({topN:xr(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:_e(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:xr(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:Qc(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:_e(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:xr(n.limit)}),o;if(n.include_history!==!1)try{o=kd(await e.fileHistory({since:_e(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:_e(n.since)})}catch(l){i=Xe(jt(`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:Qc(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:_e(n.since),limit:xr(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(cE,"dispatchLocalTool");var el=class{constructor(t=rS,n=null,r=je,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Kf}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&sE.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=Wf.has(o)?await aE(this.getEngine(),o,i,this.ctx??void 0):await cE(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=Qx(a)?`${eS} (${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=GS(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};to();var dH="/mcp-client-metrics-ingest",uH=4e3,pH="codebase_search_tokens_saved";async function lE(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${ki()}${dH}`,n=new AbortController,r=setTimeout(()=>n.abort(),uH);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:pH,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)}
1147
- `),!1}finally{clearTimeout(r)}}s(lE,"postSavingsMetric");zf();ts();Ko();me();import{existsSync as NH,readFileSync as OH,readdirSync as DH,statSync as PH}from"node:fs";import{dirname as MH,join as ns,resolve as Yf}from"node:path";var $H=8,LH=128;function jH(e){return DH(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>t.name).sort()}s(jH,"defaultListDirs");function FH(e){let t=ns(e,".git");if(!NH(t))return null;if(PH(t).isDirectory())return{isDir:!0,gitdir:null};let n=/^gitdir:\s*(.+)\s*$/m.exec(OH(t,"utf8"));return{isDir:!1,gitdir:n?Yf(e,n[1].trim()):null}}s(FH,"defaultGitKind");function HH(e){let t=`${ns(".git","worktrees")}`,n=e.lastIndexOf(t);return n>0?MH(ns(e.slice(0,n),".git")):null}s(HH,"mainCheckoutOf");function kE(e,t,n={}){try{let r=n.listDirs??jH,o=n.gitKind??FH,i=n.keyOf??xt,a=r(e).slice(0,LH),c=new Set,l=new Map;for(let u of a)try{let p=o(ns(e,u));if(p===null)continue;l.set(u,p),p.isDir&&c.add(Yf(e,u))}catch{}let d=new Map;for(let[u,p]of l){if(!p.isDir&&p.gitdir!==null){let g=HH(p.gitdir);if(g!==null&&c.has(Yf(g)))continue}let f=null;try{f=i(ns(e,u))}catch{f=null}if(f===null||f===t)continue;let m=d.get(f);(!m||p.isDir&&!m.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,$H)}catch{return[]}}s(kE,"discoverNestedRepos");Ht();rl();ur();import{join as aU}from"node:path";var cU="<synthetic>";function AE(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:aU(rf,of(e.cwd),`${e.transcript_stem}.jsonl`)}s(AE,"transcriptPathFromSideChannel");var ol=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??nf)(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!==cU&&(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 lU}from"node:child_process";var dU=8,uU=32;function pU(e){return e.split(`
1148
- `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,uU)}s(pU,"parsePorcelain");function fU(e,t=dU){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(fU,"condenseToDirs");async function IE(e=mU){let t=await e();if(t===null)return null;let n=fU(pU(t));return n.length>0?n:null}s(IE,"deriveWorkingPaths");async function mU(){return await new Promise(e=>{lU("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(mU,"defaultGitStatus");var Zf=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],hU=["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",...Zf],gU=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Qf(e){return e.find(t=>!t.startsWith("-"))}s(Qf,"firstPositionalOf");function NE(e){let t=Qf(e);return t===void 0||!gU.test(t)||hU.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(NE,"unknownSubcommandError");var G2=1;function W2(e){return Zf.includes(e)}s(W2,"isHookSubcommand");var V2=6e4;async function q2(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==z()&&or(e),e;let t=z();if(t!==null)return t;let n=await no(H);return n===null&&(ir("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.
1149
- `),process.exit(1)),ir("paired",null,{version:H}),n.apiKey}s(q2,"ensureApiKey");async function z2(e){let t=await no(H);return t===null&&(ir("auth_failed",`${e}; re-authorization did not complete`,{version:H}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1150
- `),process.exit(1)),ir("paired",null,{version:H}),t.apiKey}s(z2,"reauth");async function J2(){let e=Qf(process.argv.slice(2)),t=NE(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1151
- `),process.exit(2)),e==="install"){let x=process.argv.indexOf("install"),T=process.argv.slice(x+1),D=await jS(T);process.exit(D)}if(e==="refresh-rules"){let{runRefreshRules:x}=await Promise.resolve().then(()=>(zc(),$f));process.exit(await x(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:x}=await Promise.resolve().then(()=>(um(),c0));process.exit(await x(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:x}=await Promise.resolve().then(()=>($R(),MR));process.exit(await x())}if(e==="session-end-run"){let{runSessionEndWorker:x}=await Promise.resolve().then(()=>(zm(),IR));process.exit(await x())}if(e==="on-session-briefing"){let{runOnSessionBriefing:x}=await Promise.resolve().then(()=>(jR(),LR));process.exit(await x())}if(e==="on-session-reminder"){let{runOnSessionReminder:x}=await Promise.resolve().then(()=>(UR(),HR));process.exit(await x())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:x}=await Promise.resolve().then(()=>(YR(),JR));process.exit(await x())}if(e==="guard"){let x=process.argv.indexOf("guard"),{runGuard:T}=await Promise.resolve().then(()=>(nC(),tC));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-inject"){let{runGuardInject:x}=await Promise.resolve().then(()=>(wr(),SS));process.exit(await x())}if(e==="guard-gate"){let{runGuardGate:x}=await Promise.resolve().then(()=>(dC(),lC));process.exit(await x())}if(e==="guard-stop"){let{runGuardStop:x}=await Promise.resolve().then(()=>(fC(),pC));process.exit(await x())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:x}=await Promise.resolve().then(()=>(Zm(),iC));process.exit(await x())}if(e==="guard-capture"){let{runGuardCapture:x}=await Promise.resolve().then(()=>(yC(),gC));process.exit(await x())}if(e==="gateway"){let x=process.argv.indexOf("gateway"),{runGateway:T}=await Promise.resolve().then(()=>(tT(),eT));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:x}=await Promise.resolve().then(()=>(ph(),uh));process.exit(await x())}if(e==="guard-cross-check"){let{runGuardCrossCheck:x}=await Promise.resolve().then(()=>(ph(),uh));process.exit(await x())}if(e==="on-index-refresh"){let{runOnIndexRefresh:x}=await Promise.resolve().then(()=>(mh(),fh));process.exit(await x())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:x}=await Promise.resolve().then(()=>(mh(),fh));process.exit(await x())}if(e==="on-prompt-context"){let{runOnPromptContext:x}=await Promise.resolve().then(()=>(kh(),wh));process.exit(await x())}if(e==="on-read-context"){let{runOnReadContext:x}=await Promise.resolve().then(()=>(kh(),wh));process.exit(await x())}if(e!==void 0&&W2(e)){let x=await Promise.resolve().then(()=>(hs(),Q0)),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+`
1152
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(Y2(),process.exit(0)),process.argv.includes("--reauth")&&(wi(),await no(H,process.stdout)===null&&process.exit(1),ir("paired",null,{version:H}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1153
- `),process.exit(0));let n=ce(),r=await q2(),o=re(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Yc:null,c=null,l=new Map,d=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new el(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=oS(x),l.set(x,T)),T},"engineFor"),projectKeyFor:xt}),u=`bridge-${K2()}`,p=s(async()=>{if(!a)return;let x=a.takePending();x.tokens<=0||await lE({apiKey:r,deviceId:n,sessionId:u,tokensSaved:x.tokens,bridgeVersion:H})},"flushSavings"),f=a?setInterval(()=>{p()},V2):null;f?.unref();let m=new nl({projectKey:o}),g=new ol({resolvePath:s(()=>AE(m.sideChannel()),"resolvePath"),fallbackModel:s(()=>m.sideChannel()?.model??null,"fallbackModel")}),y=new Rs,_=null,b=s(()=>(_===null&&(_=o!==null?kE(lt(),o):[]),_),"nestedRepos"),k=s(x=>b().find(T=>T.projectKey===x)?.dir??null,"nestedDirOf"),v=new tl({projectKey:o,identity:m,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(()=>IE(),"deriveWorkingPaths"),snapshot:o!==null?X2(wE({projectKey:o}),y,k):void 0,nestedProjectKeys:s(()=>b().map(x=>x.projectKey),"nestedProjectKeys")}),E=v.isEnabled?setInterval(()=>{v.pollActivity()},pE):null;if(E?.unref(),v.isEnabled){let x=s(T=>{v.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(()=>(Gc(),OS)).then(({refreshAgentsMdForSession:j})=>j(x,{apiKey:r,projectKey:o,listRoots:T})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(zc(),$f))).then(({refreshRulesForSession:j})=>j(x,{apiKey:s(()=>r,"apiKey"),listRoots:T})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),P=0,K=Xu();try{for(;;){let x=c?.carryOver()??null,T=new xa({apiKey:r,deviceId:n,bridgeVersion:H,projectKey:o,localRouter:d,presence:v,onConnectionOutcome:s((D,j)=>ir(D,j,{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 bi&&P<G2){P+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${D.message}; re-authorizing\u2026
1154
- `),r=await z2(D.reason);continue}throw D}}}finally{f&&clearInterval(f),E&&clearInterval(E),await v.end(),await p()}}s(J2,"main");function Y2(){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(`
1155
- `))}s(Y2,"printHelp");J2().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1156
- `),process.exit(1)});function X2(e,t,n){return{...e,write(r,o){let i=r;try{i=Eh(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(X2,"withAssignedCapture");
1143
+ `)}s(Ju,"collectSseText");function ka(e){try{return JSON.parse(e).id??null}catch{return null}}s(ka,"tryExtractId");function Qr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Qr,"isInitializeRequest");function Tw(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(Tw,"isSessionLossBody");function Aw(e){return e instanceof Error?e.message:String(e)}s(Aw,"stringifyErr");function bP(e){return e?.name==="TimeoutError"}s(bP,"isTimeoutError");function va(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
1144
+ `)}s(va,"emitJsonRpcError");function wP(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(wP,"extractHint");function kP(e){try{let t=Wl(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(kP,"parsePresenceToolResult");ie();tp();np();Ue();me();Hf();Sn();Sn();import{readFileSync as B1}from"node:fs";import{join as BS}from"node:path";function Jc(e){return e?Math.ceil(e.length/4):0}s(Jc,"estimateTokens");var KS=1e6,Yc=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 GS(e){try{let t=B1(e,"utf8");return t.length>KS?t.slice(0,KS):t}catch{return""}}s(GS,"readFileCapped");function K1(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(K1,"distinctFilePaths");function WS(e,t,n,r){try{let o=Jc(n);if(e==="codebase_search"){let i=K1(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=Jc(GS(BS(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=Jc(GS(BS(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(WS,"measureLocalToolSaved");dn();Sn();import{createHash as dH}from"node:crypto";dn();import{execFileSync as q1}from"node:child_process";import{createHash as z1}from"node:crypto";Sn();Uf();import{realpathSync as XS}from"node:fs";function J1(e,t){try{return XS(e)===XS(t)}catch{return e===t}}s(J1,"samePath");var Bf=30,Y1=10,ZS=20,X1=new Map;function Kf(e){return e instanceof Error?e.message:String(e)}s(Kf,"msg");function Zc(e){let t=e.split(`
1145
+ `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Zc,"firstLine");var QS=s(e=>e?e.slice(0,12):"?","short");async function Z1(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await YS(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:Kf(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(Z1,"refreshIndex");function Q1(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(Q1,"isEmptyRange");function eH(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(eH,"localOnly");function tH(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(tH,"localGradeBlockers");function nH(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=Gu(!1,e.projectKey,e.result);if(!t.persist)return t;let n=tH(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(nH,"bridgePersistDecision");function eE(e,t){try{return q1("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(eE,"git");function rH(e,t){let n=ri(e),r=n&&eE(e,["merge-base",t,`origin/${n}`])||null,o=eE(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(rH,"gitPersistFacts");function oH(e,t){return z1("sha256").update(`${e??""}
1146
+ ${JSON.stringify(t)}`).digest("hex")}s(oH,"payloadKey");function mt(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(mt,"fail");var vr="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function tE(e){let t=Vu(e);if(t!==null&&qu(t))return mt("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 mt("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 mt("cloud_unavailable",`review_verdict failed: ${Zc(t?.detail??e)||"no detail"}`,vr)}s(tE,"fromProtocolText");function iH(e,t,n){switch(e.kind){case"no_session":return mt("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. ${vr}`);case"transport_error":return e.timedOut?mt("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."):mt("cloud_unavailable",`network error: ${e.message}`,vr);case"http_error":return e.status===401?mt("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Zc(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?mt("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."):mt("cloud_unavailable",`HTTP ${e.status}: ${Zc(e.body)}`,vr);case"rpc_error":return tE(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return tE(e.text);let r;try{r=JSON.parse(e.text)}catch{return mt("cloud_unavailable",`review_verdict returned non-JSON text: ${Zc(e.text)}`,vr)}return typeof r!="object"||r===null?mt("cloud_unavailable","review_verdict returned no object",vr):{kind:"verdict",body:r}}}}s(iH,"interpretOutcome");var sH="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).",aH={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"},nE=s(e=>e.map(t=>aH[t]??t).join("; "),"adviceFor");function cH(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: ${nE(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 ${QS(n)}, but this branch forks off ${o??"the default branch"} at ${QS(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(cH,"skipText");function lH(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=nE(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=cH(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(lH,"recordHint");async function rE(e,t,n){let r=n.repoRoot??je(),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 ue=xo(c,r);if(ue===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(!J1(ue.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=ue.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??X1,m=[],g=await Z1(i,o,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await i.reviewChanges(Bu(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(Q1(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:_,warnings:m};let b;try{b=await i.reviewDetectorScopes({baseRef:l})}catch(ue){let xh=Xe(jt(`reviewDetectorScopes failed: ${Kf(ue)}`));b={commit:xh,local:xh},m.push(`repo-health detectors unavailable (${Kf(ue)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:v}=Ku(y,b.commit);v>0&&m.push(`${v} symbol(s) exceed the server schema (name > ${ya} or qualified name > ${_a} chars) and were left out \u2014 this run is not attestation-grade.`);let E=oH(a,k),S=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",R=nH({persistWanted:u,since:l,projectKey:a,result:y,payload:k,git:S?(n.persistFacts??rH)(o,y.headSha):null,recordedRunId:f.get(E)??null}),P={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:v,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,ZS),local_only:eH(b).slice(0,ZS)}},K=await n.callCloudTool("review_verdict",{attest:k,persist:R.persist,...a?{project_key:a}:{}},{timeoutMs:p}),x=iH(K,p,R.persist);if(x.kind==="error")return{ok:!1,error:x.error,message:x.message,hint:x.hint,base:_,local:P,warnings:m};let T=x.body;if(T.ok!==!0){let ue=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:ue?sH:T.hint??vr,base:_,local:P,warnings:m}}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:m};let D=T.attest,j=T.run??null,At=j&&typeof j.id=="string"?{persisted:!0,run_id:j.id,commit_sha:j.commit_sha??null,attestation_format:j.attestation_format??null}:{persisted:!1,reason:R.skipped??T.run_note??"not_persisted",...R.detail?{detail:R.detail}:{}};At.persisted&&f.set(E,j.id);let Ss=typeof D?.attestation_grade=="boolean"?D.attestation_grade:null,Uo=Array.isArray(D?.grade_blockers)?D.grade_blockers:[],Z=T.counts??{},ot=Array.isArray(T.findings)?T.findings:[],Es=`Verdict ${T.verdict??"?"}: ${Z.block??0} block, ${Z.warn??0} warn, ${Z.note??0} note`+(T.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:T.verdict??null,counts:Z,record:At,attest:D?{attestation_grade:Ss,grade_blockers:Uo,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:`${Es} ${lH(At,Ss,Uo,y.headSha)}`,findings:ot.slice(0,Bf).map(ue=>({convention_id:ue.convention_id,convention_version:ue.convention_version,severity:ue.severity,action:ue.action,...ue.downgrade_reason?{downgrade_reason:ue.downgrade_reason}:{},summary:ue.summary,matched_changed_symbols:(ue.matched_changed_symbols??[]).slice(0,Y1),matched_symbol_count:ue.matched_symbols?.length??0})),...ot.length>Bf?{findings_not_shown:ot.length-Bf}:{},detector_findings:T.detector_findings??[],policy_source:T.policy_source??null,coverage_note:Wu(y,D?.evaluated_convention_count,v),base:_,local:P,warnings:m}}s(rE,"runAttestReview");var oE=(()=>{let e=Object.keys(li),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Qc(e){return dH("sha256").update(e,"utf8").digest("hex")}s(Qc,"nodeKeyHash");var uH=["module","class","interface","function","method","type_alias","enum","variable"],Gf=[{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:uH,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 "+oE+" \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 "+oE+", 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."}}}}],Wf=new Map([["codebase_review_verdict","attest_review_changes"]]),aE=new Set([...Gf.map(e=>e.name),...Wf.keys()]),Vf=new Set(["attest_review_changes",...[...Wf].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function cE(e,t,n,r){if(!Vf.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 rE(e,n,r),i=Wf.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(cE,"dispatchCloudBackedTool");function _e(e){return typeof e=="string"&&e.length>0?e:void 0}s(_e,"str");function xr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(xr,"num");function iE(e){if(e===void 0)return{repoRoot:je(),scanDirs:void 0};let t=xo(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(iE,"anchorRepo");function sE(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(sE,"dirNotFound");async function lE(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=_e(n.for_path);if(o!==void 0){let u=nS(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 Zn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,m=s(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let 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 v of i){let E=xo(v);if(E===null){p.push(v);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=[],m=[],g=[],y=[];for(let[v,E]of u){let S=[...E],R=S.includes(""),P=await Xn(v,{dirs:R?void 0:S,minFiles:r});f.push({repo_root:v,dirs:R?null:S}),m.push(...P.findings),g.push(...P.facts.namespaces.map(K=>({repo_root:v,dir:K.dir,prefix:K.prefix,file_count:K.fileCount}))),y.push(...P.facts.skipped)}let _=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=je(),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:_e(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=_e(n.dir),o,i;if(r!==void 0){let u=xo(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=je(),i=void 0;let a=tr(o,{dirs:i,baseRef:_e(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=iE(_e(n.dir));if(r===null)return sE("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=er(r.repoRoot,{dirs:r.scanDirs,baseRef:_e(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=iE(_e(n.dir));if(r===null)return sE("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=$u(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:_e(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=_e(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:_e(n.kind),limit:xr(n.limit)})).map(i=>({...i,nodeKeyHash:Qc(i.nodeKey)}))}case"codebase_trace":{let r=_e(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:xr(n.max_depth),limit:xr(n.limit)})}case"codebase_snippet":{let r=_e(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:Qc(r)}}case"codebase_map":return e.getArchitecture({topN:xr(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:_e(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:xr(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:Qc(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:_e(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:xr(n.limit)}),o;if(n.include_history!==!1)try{o=kd(await e.fileHistory({since:_e(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:_e(n.since)})}catch(l){i=Xe(jt(`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:Qc(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:_e(n.since),limit:xr(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(lE,"dispatchLocalTool");var el=class{constructor(t=oS,n=null,r=je,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Gf}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&aE.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=Vf.has(o)?await cE(this.getEngine(),o,i,this.ctx??void 0):await lE(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=eS(a)?`${tS} (${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=WS(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};to();var pH="/mcp-client-metrics-ingest",fH=4e3,mH="codebase_search_tokens_saved";async function dE(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${ki()}${pH}`,n=new AbortController,r=setTimeout(()=>n.abort(),fH);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:mH,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)}
1147
+ `),!1}finally{clearTimeout(r)}}s(dE,"postSavingsMetric");Jf();ts();Ko();me();import{existsSync as DH,readFileSync as PH,readdirSync as MH,statSync as $H}from"node:fs";import{dirname as LH,join as ns,resolve as Xf}from"node:path";var jH=8,FH=128;function HH(e){return MH(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>t.name).sort()}s(HH,"defaultListDirs");function UH(e){let t=ns(e,".git");if(!DH(t))return null;if($H(t).isDirectory())return{isDir:!0,gitdir:null};let n=/^gitdir:\s*(.+)\s*$/m.exec(PH(t,"utf8"));return{isDir:!1,gitdir:n?Xf(e,n[1].trim()):null}}s(UH,"defaultGitKind");function BH(e){let t=`${ns(".git","worktrees")}`,n=e.lastIndexOf(t);return n>0?LH(ns(e.slice(0,n),".git")):null}s(BH,"mainCheckoutOf");function vE(e,t,n={}){try{let r=n.listDirs??HH,o=n.gitKind??UH,i=n.keyOf??xt,a=r(e).slice(0,FH),c=new Set,l=new Map;for(let u of a)try{let p=o(ns(e,u));if(p===null)continue;l.set(u,p),p.isDir&&c.add(Xf(e,u))}catch{}let d=new Map;for(let[u,p]of l){if(!p.isDir&&p.gitdir!==null){let g=BH(p.gitdir);if(g!==null&&c.has(Xf(g)))continue}let f=null;try{f=i(ns(e,u))}catch{f=null}if(f===null||f===t)continue;let m=d.get(f);(!m||p.isDir&&!m.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,jH)}catch{return[]}}s(vE,"discoverNestedRepos");Ht();rl();ur();import{join as lU}from"node:path";var dU="<synthetic>";function IE(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:lU(of,sf(e.cwd),`${e.transcript_stem}.jsonl`)}s(IE,"transcriptPathFromSideChannel");var ol=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??rf)(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!==dU&&(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 uU}from"node:child_process";var pU=8,fU=32;function mU(e){return e.split(`
1148
+ `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,fU)}s(mU,"parsePorcelain");function hU(e,t=pU){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(hU,"condenseToDirs");async function NE(e=gU){let t=await e();if(t===null)return null;let n=hU(mU(t));return n.length>0?n:null}s(NE,"deriveWorkingPaths");async function gU(){return await new Promise(e=>{uU("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(gU,"defaultGitStatus");var Qf=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],yU=["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",...Qf],_U=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function em(e){return e.find(t=>!t.startsWith("-"))}s(em,"firstPositionalOf");function OE(e){let t=em(e);return t===void 0||!_U.test(t)||yU.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(OE,"unknownSubcommandError");var V2=1;function q2(e){return Qf.includes(e)}s(q2,"isHookSubcommand");var z2=6e4;async function J2(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==z()&&or(e),e;let t=z();if(t!==null)return t;let n=await no(H);return n===null&&(ir("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.
1149
+ `),process.exit(1)),ir("paired",null,{version:H}),n.apiKey}s(J2,"ensureApiKey");async function Y2(e){let t=await no(H);return t===null&&(ir("auth_failed",`${e}; re-authorization did not complete`,{version:H}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1150
+ `),process.exit(1)),ir("paired",null,{version:H}),t.apiKey}s(Y2,"reauth");async function X2(){let e=em(process.argv.slice(2)),t=OE(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1151
+ `),process.exit(2)),e==="install"){let x=process.argv.indexOf("install"),T=process.argv.slice(x+1),D=await FS(T);process.exit(D)}if(e==="refresh-rules"){let{runRefreshRules:x}=await Promise.resolve().then(()=>(zc(),Lf));process.exit(await x(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:x}=await Promise.resolve().then(()=>(pm(),l0));process.exit(await x(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:x}=await Promise.resolve().then(()=>(LR(),$R));process.exit(await x())}if(e==="session-end-run"){let{runSessionEndWorker:x}=await Promise.resolve().then(()=>(Jm(),NR));process.exit(await x())}if(e==="on-session-briefing"){let{runOnSessionBriefing:x}=await Promise.resolve().then(()=>(FR(),jR));process.exit(await x())}if(e==="on-session-reminder"){let{runOnSessionReminder:x}=await Promise.resolve().then(()=>(BR(),UR));process.exit(await x())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:x}=await Promise.resolve().then(()=>(XR(),YR));process.exit(await x())}if(e==="guard"){let x=process.argv.indexOf("guard"),{runGuard:T}=await Promise.resolve().then(()=>(rC(),nC));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-inject"){let{runGuardInject:x}=await Promise.resolve().then(()=>(wr(),ES));process.exit(await x())}if(e==="guard-gate"){let{runGuardGate:x}=await Promise.resolve().then(()=>(uC(),dC));process.exit(await x())}if(e==="guard-stop"){let{runGuardStop:x}=await Promise.resolve().then(()=>(mC(),fC));process.exit(await x())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:x}=await Promise.resolve().then(()=>(Qm(),sC));process.exit(await x())}if(e==="guard-capture"){let{runGuardCapture:x}=await Promise.resolve().then(()=>(_C(),yC));process.exit(await x())}if(e==="gateway"){let x=process.argv.indexOf("gateway"),{runGateway:T}=await Promise.resolve().then(()=>(nT(),tT));process.exit(await T(process.argv.slice(x+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:x}=await Promise.resolve().then(()=>(fh(),ph));process.exit(await x())}if(e==="guard-cross-check"){let{runGuardCrossCheck:x}=await Promise.resolve().then(()=>(fh(),ph));process.exit(await x())}if(e==="on-index-refresh"){let{runOnIndexRefresh:x}=await Promise.resolve().then(()=>(hh(),mh));process.exit(await x())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:x}=await Promise.resolve().then(()=>(hh(),mh));process.exit(await x())}if(e==="on-prompt-context"){let{runOnPromptContext:x}=await Promise.resolve().then(()=>(vh(),kh));process.exit(await x())}if(e==="on-read-context"){let{runOnReadContext:x}=await Promise.resolve().then(()=>(vh(),kh));process.exit(await x())}if(e!==void 0&&q2(e)){let x=await Promise.resolve().then(()=>(hs(),eR)),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+`
1152
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(Z2(),process.exit(0)),process.argv.includes("--reauth")&&(wi(),await no(H,process.stdout)===null&&process.exit(1),ir("paired",null,{version:H}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1153
+ `),process.exit(0));let n=le(),r=await J2(),o=oe(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Yc:null,c=null,l=new Map,d=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new el(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=iS(x),l.set(x,T)),T},"engineFor"),projectKeyFor:xt}),u=`bridge-${W2()}`,p=s(async()=>{if(!a)return;let x=a.takePending();x.tokens<=0||await dE({apiKey:r,deviceId:n,sessionId:u,tokensSaved:x.tokens,bridgeVersion:H})},"flushSavings"),f=a?setInterval(()=>{p()},z2):null;f?.unref();let m=new nl({projectKey:o}),g=new ol({resolvePath:s(()=>IE(m.sideChannel()),"resolvePath"),fallbackModel:s(()=>m.sideChannel()?.model??null,"fallbackModel")}),y=new Rs,_=null,b=s(()=>(_===null&&(_=o!==null?vE(lt(),o):[]),_),"nestedRepos"),k=s(x=>b().find(T=>T.projectKey===x)?.dir??null,"nestedDirOf"),v=new tl({projectKey:o,identity:m,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(()=>NE(),"deriveWorkingPaths"),snapshot:o!==null?Q2(kE({projectKey:o}),y,k):void 0,nestedProjectKeys:s(()=>b().map(x=>x.projectKey),"nestedProjectKeys")}),E=v.isEnabled?setInterval(()=>{v.pollActivity()},fE):null;if(E?.unref(),v.isEnabled){let x=s(T=>{v.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(()=>(Gc(),DS)).then(({refreshAgentsMdForSession:j})=>j(x,{apiKey:r,projectKey:o,listRoots:T})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(zc(),Lf))).then(({refreshRulesForSession:j})=>j(x,{apiKey:s(()=>r,"apiKey"),listRoots:T})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),P=0,K=Xu();try{for(;;){let x=c?.carryOver()??null,T=new xa({apiKey:r,deviceId:n,bridgeVersion:H,projectKey:o,localRouter:d,presence:v,onConnectionOutcome:s((D,j)=>ir(D,j,{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 bi&&P<V2){P+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${D.message}; re-authorizing\u2026
1154
+ `),r=await Y2(D.reason);continue}throw D}}}finally{f&&clearInterval(f),E&&clearInterval(E),await v.end(),await p()}}s(X2,"main");function Z2(){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(`
1155
+ `))}s(Z2,"printHelp");X2().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1156
+ `),process.exit(1)});function Q2(e,t,n){return{...e,write(r,o){let i=r;try{i=Rh(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(Q2,"withAssignedCapture");