@maind-dev/mcp-bridge 0.97.0 → 0.98.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/README.md +20 -1
- package/build/index.js +263 -241
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var af=Object.defineProperty;var s=(e,t)=>af(e,"name",{value:t,configurable:!0});var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var n in t)af(e,n,{get:t[n],enumerable:!0})};import{existsSync as RE,mkdirSync as CE,readdirSync as AE,readFileSync as IE,renameSync as NE,statSync as OE,unlinkSync as DE,writeFileSync as PE}from"node:fs";import{homedir as ME}from"node:os";import{join as Ao}from"node:path";function Io(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,i=si(r.id),o=si(r.key),a=si(r.title),c=si(r.status);if(!i||!o||!a||!c)continue;let l=r.here===!1?!1:void 0,d=si(r.where);if(t.push({id:i,key:o,title:a,status:c,...l===!1?{here:l}:{},...d?{where:d}:{}}),t.length>=$E)break}return t}function No(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 cf(e=ME()){return Ao(e,".maind","assigned-told")}function lf(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function df(e){try{let t=JSON.parse(IE(e,"utf8"));return{ids:Array.isArray(t.ids)?t.ids.filter(n=>typeof n=="string"):[],checked_at:typeof t.checked_at=="number"?t.checked_at:0}}catch{return{ids:[],checked_at:0}}}function jE(e,t,n){CE(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;PE(r,JSON.stringify(n),{mode:384}),NE(r,t)}function uf(e,t,n=cf()){let r=Ao(n,`${lf(e)}.json`);return RE(r)?t-df(r).checked_at<FE:!1}function dc(e,t,n,r=cf()){try{let i=Ao(r,`${lf(e)}.json`),o=df(i),a=t.filter(c=>!o.ids.includes(c.id));return jE(r,i,{ids:[...o.ids,...a.map(c=>c.id)].slice(-200),checked_at:n}),HE(r,n,i),a}catch{return[]}}function HE(e,t,n){try{for(let r of AE(e)){let i=Ao(e,r);i!==n&&t-OE(i).mtimeMs>LE&&DE(i)}}catch{}}function pf(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 i=r;if(i.here!==!1||typeof i.project_key!="string")return r;let o=t(i.project_key);return o?{...i,where:o}:r})}:e}function ff(e){return e==="claude-code"}var $E,LE,FE,si,Co,ai=v(()=>{"use strict";$E=5,LE=7*24*60*60*1e3,FE=6e4,si=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Io,"parseAssignedList");s(No,"assignedNoticeText");s(cf,"assignedToldDir");s(lf,"safeName");s(df,"readTold");s(jE,"writeTold");s(uf,"checkedRecently");s(dc,"takeUntold");s(HE,"pruneTold");Co=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=Io(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 No(t)}};s(pf,"labelNestedItems");s(ff,"clientHasHooks")});function yf(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let o={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function ir(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function fc(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function mc(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function hc(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var gc=v(()=>{"use strict";s(yf,"parseFrame");s(ir,"denyResult");s(fc,"toolEvent");s(mc,"policyEvent");s(hc,"shaEvent")});import{execFileSync as vf}from"node:child_process";function wf(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=XE}function ZE(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let o of qE){let a=r[o];typeof a=="string"&&_f.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of JE){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&_f.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function QE(e,t){let n=t(e);if(n===e)return{field:"",sha:e,verdict:"proven"};if(n!==null)return{field:"",sha:e,verdict:"unknown"};let r=e.slice(0,bf);for(let i=bf;i>=YE;i--){let o=r.slice(0,i),a=t(o);if(a!==null&&a.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function or(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function kf(){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 Do(e=process.cwd()){try{let n=vf("git",["rev-parse","--show-toplevel"],{cwd:e,env:kf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function e0(e){return t=>{try{let r=vf("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:kf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function Po(e,t){if(t===null)return[];let n=ZE(e);if(n.length===0)return[];let r=e0(t),i=[];for(let{field:o,sha:a}of n){let c=QE(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var qE,JE,_f,YE,bf,XE,yc=v(()=>{"use strict";qE=["commit_sha","base_sha","head_sha"],JE=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],_f=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,YE=7,bf=12,XE=10;s(wf,"isDenyGrade");s(ZE,"extractShaArgs");s(QE,"classifySha");s(or,"shaFindingText");s(kf,"cleanGitEnv");s(Do,"resolveRepoRootForSha");s(e0,"gitShaResolver");s(Po,"inspectLineForShas")});var Sf=v(()=>{"use strict"});var U,bc,C,Xe,ci=v(()=>{(function(e){e.assertEqual=i=>{};function t(i){}s(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of o)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(U||(U={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(bc||(bc={}));C=U.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=s(e=>{switch(typeof e){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(e)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(e)?C.array:e===null?C.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C.promise:typeof Map<"u"&&e instanceof Map?C.map:typeof Set<"u"&&e instanceof Set?C.set:typeof Date<"u"&&e instanceof Date?C.date:C.object;default:return C.unknown}},"getParsedType")});var T,t0,ve,Mo=v(()=>{ci();T=U.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"]),t0=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ve=class e extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},i=s(o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,U.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ve.create=e=>new ve(e)});var n0,ft,vc=v(()=>{Mo();ci();n0=s((e,t)=>{let n;switch(e.code){case T.invalid_type:e.received===C.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,U.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${U.joinValues(e.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${U.joinValues(e.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${U.joinValues(e.options)}, received '${e.received}'`;break;case T.invalid_arguments:n="Invalid function arguments";break;case T.invalid_return_type:n="Invalid function return type";break;case T.invalid_date:n="Invalid date";break;case T.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:U.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case T.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case T.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case T.custom:n="Invalid input";break;case T.invalid_intersection_types:n="Intersection results could not be merged";break;case T.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case T.not_finite:n="Number must be finite";break;default:n=t.defaultError,U.assertNever(e)}return{message:n}},"errorMap"),ft=n0});function r0(e){Ef=e}function sr(){return Ef}var Ef,$o=v(()=>{vc();Ef=ft;s(r0,"setErrorMap");s(sr,"getErrorMap")});function R(e,t){let n=sr(),r=li({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ft?void 0:ft].filter(i=>!!i)});e.common.issues.push(r)}var li,i0,ie,M,rn,pe,Lo,Fo,It,ar,wc=v(()=>{$o();vc();li=s(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:o,message:c}},"makeIssue"),i0=[];s(R,"addIssueToContext");ie=class e{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return M;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let o=await i.key,a=await i.value;r.push({key:o,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return M;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}},M=Object.freeze({status:"aborted"}),rn=s(e=>({status:"dirty",value:e}),"DIRTY"),pe=s(e=>({status:"valid",value:e}),"OK"),Lo=s(e=>e.status==="aborted","isAborted"),Fo=s(e=>e.status==="dirty","isDirty"),It=s(e=>e.status==="valid","isValid"),ar=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Tf=v(()=>{});var O,Rf=v(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}))});function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:s((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function Nf(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 w0(e){return new RegExp(`^${Nf(e)}$`)}function Of(e){let t=`${If}T${Nf(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 k0(e,t){return!!((t==="v4"||!t)&&m0.test(e)||(t==="v6"||!t)&&g0.test(e))}function x0(e,t){if(!d0.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function S0(e,t){return!!((t==="v4"||!t)&&h0.test(e)||(t==="v6"||!t)&&y0.test(e))}function E0(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}function cr(e){if(e instanceof we){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ae.create(cr(r))}return new we({...e._def,shape:s(()=>t,"shape")})}else return e instanceof gt?new gt({...e._def,type:cr(e.element)}):e instanceof Ae?Ae.create(cr(e.unwrap())):e instanceof Qe?Qe.create(cr(e.unwrap())):e instanceof Ze?Ze.create(e.items.map(t=>cr(t))):e}function xc(e,t){let n=Xe(e),r=Xe(t);if(e===t)return{valid:!0,data:e};if(n===C.object&&r===C.object){let i=U.objectKeys(t),o=U.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of o){let l=xc(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===C.array&&r===C.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],c=t[o],l=xc(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===C.date&&r===C.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function Df(e,t){return new hn({values:e,typeName:$.ZodEnum,...L(t)})}function Af(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Pf(e,t={},n){return e?Ot.create().superRefine((r,i)=>{let o=e(r);if(o instanceof Promise)return o.then(a=>{if(!a){let c=Af(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!o){let a=Af(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Ot.create()}var Ie,Cf,H,o0,s0,a0,c0,l0,d0,u0,p0,f0,kc,m0,h0,g0,y0,_0,b0,If,v0,Nt,on,sn,an,cn,lr,ln,dn,Ot,ht,je,dr,gt,we,un,mt,jo,pn,Ze,Ho,ur,pr,Uo,fn,mn,hn,gn,Dt,Ne,Ae,Qe,yn,_n,fr,T0,di,ui,bn,R0,$,C0,Mf,$f,A0,I0,Lf,N0,O0,D0,P0,M0,$0,L0,F0,j0,H0,U0,B0,G0,K0,W0,V0,z0,q0,J0,Y0,X0,Z0,Q0,eT,tT,nT,rT,iT,oT,sT,aT,cT,lT,dT,Ff=v(()=>{Mo();$o();Rf();wc();ci();Ie=class{static{s(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Cf=s((e,t)=>{if(It(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 ve(e.common.issues);return this._error=n,this._error}}},"handleResult");s(L,"processCreateParams");H=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return Xe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Xe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ie,ctx:{common:t.parent.common,data:t.data,parsedType:Xe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(ar(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xe(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Cf(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return It(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=>It(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:Xe(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(ar(i)?i:Promise.resolve(i));return Cf(r,o)}refine(t,n){let r=s(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,o)=>{let a=t(i),c=s(()=>o.addIssue({code:T.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new Ne({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s(n=>this["~validate"](n),"validate")}}optional(){return Ae.create(this,this._def)}nullable(){return Qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return Dt.create(this,this._def)}or(t){return un.create([this,t],this._def)}and(t){return pn.create(this,t,this._def)}transform(t){return new Ne({...L(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new yn({...L(this._def),innerType:this,defaultValue:n,typeName:$.ZodDefault})}brand(){return new di({typeName:$.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new _n({...L(this._def),innerType:this,catchValue:n,typeName:$.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ui.create(this,t)}readonly(){return bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},o0=/^c[^\s-]{8,}$/i,s0=/^[0-9a-z]+$/,a0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,c0=/^[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,l0=/^[a-z0-9_-]{21}$/i,d0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,u0=/^[-+]?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)?)??$/,p0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,f0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",m0=/^(?:(?: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])$/,h0=/^(?:(?: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])$/,g0=/^(([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]))$/,y0=/^(([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])$/,_0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,b0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,If="((\\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])))",v0=new RegExp(`^${If}$`);s(Nf,"timeRegexSource");s(w0,"timeRegex");s(Of,"datetimeRegex");s(k0,"isValidIP");s(x0,"isValidJWT");s(S0,"isValidCidr");Nt=class e extends H{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C.string){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_type,expected:C.string,received:o.parsedType}),M}let r=new ie,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,c=t.data.length<o.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?R(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&R(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")p0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"email",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")kc||(kc=new RegExp(f0,"u")),kc.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"emoji",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")c0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"uuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")l0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"nanoid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")o0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")s0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid2",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")a0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ulid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),R(i,{validation:"url",code:T.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"regex",code:T.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Of(o).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?v0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?w0(o).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?u0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"duration",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?k0(t.data,o.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ip",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?x0(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"jwt",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?S0(t.data,o.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cidr",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?_0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?b0.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64url",code:T.invalid_string,message:o.message}),r.dirty()):U.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:T.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}};Nt.create=e=>new Nt({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...L(e)});s(E0,"floatSafeRemainder");on=class e extends H{static{s(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==C.number){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_type,expected:C.number,received:o.parsedType}),M}let r,i=new ie;for(let o of this._def.checks)o.kind==="int"?U.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),R(r,{code:T.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?E0(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),R(r,{code:T.not_finite,message:o.message}),i.dirty()):U.assertNever(o);return{status:i.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,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(i)}]})}_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"&&U.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};on.create=e=>new on({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...L(e)});sn=class e extends H{static{s(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==C.bigint)return this._getInvalidInput(t);let r,i=new ie;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):U.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return R(n,{code:T.invalid_type,expected:C.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,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message: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}};sn.create=e=>new sn({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...L(e)});an=class extends H{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C.boolean){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:C.boolean,received:r.parsedType}),M}return pe(t.data)}};an.create=e=>new an({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...L(e)});cn=class e extends H{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C.date){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_type,expected:C.date,received:o.parsedType}),M}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_date}),M}let r=new ie,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):U.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};cn.create=e=>new cn({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...L(e)});lr=class extends H{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==C.symbol){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:C.symbol,received:r.parsedType}),M}return pe(t.data)}};lr.create=e=>new lr({typeName:$.ZodSymbol,...L(e)});ln=class extends H{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:C.undefined,received:r.parsedType}),M}return pe(t.data)}};ln.create=e=>new ln({typeName:$.ZodUndefined,...L(e)});dn=class extends H{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==C.null){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:C.null,received:r.parsedType}),M}return pe(t.data)}};dn.create=e=>new dn({typeName:$.ZodNull,...L(e)});Ot=class extends H{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}};Ot.create=e=>new Ot({typeName:$.ZodAny,...L(e)});ht=class extends H{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}};ht.create=e=>new ht({typeName:$.ZodUnknown,...L(e)});je=class extends H{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return R(n,{code:T.invalid_type,expected:C.never,received:n.parsedType}),M}};je.create=e=>new je({typeName:$.ZodNever,...L(e)});dr=class extends H{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:C.void,received:r.parsedType}),M}return pe(t.data)}};dr.create=e=>new dr({typeName:$.ZodVoid,...L(e)});gt=class e extends H{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==C.array)return R(n,{code:T.invalid_type,expected:C.array,received:n.parsedType}),M;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(R(n,{code:a?T.too_big:T.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(R(n,{code:T.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(R(n,{code:T.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new Ie(n,a,n.path,c)))).then(a=>ie.mergeArray(r,a));let o=[...n.data].map((a,c)=>i.type._parseSync(new Ie(n,a,n.path,c)));return ie.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message: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)}};gt.create=(e,t)=>new gt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...L(t)});s(cr,"deepPartialify");we=class e extends H{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=U.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==C.object){let d=this._getOrReturnCtx(t);return R(d,{code:T.invalid_type,expected:C.object,received:d.parsedType}),M}let{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof je&&this._def.unknownKeys==="strip"))for(let d in i.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Ie(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof je){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(R(i,{code:T.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Ie(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,f=await u.value;d.push({key:p,value:f,alwaysSet:u.alwaysSet})}return d}).then(d=>ie.mergeObjectSync(r,d)):ie.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return O.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:s((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:O.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:s(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:s(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:$.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 U.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 U.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}deepPartial(){return cr(this)}partial(t){let n={};for(let r of U.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of U.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ae;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return Df(U.objectKeys(this.shape))}};we.create=(e,t)=>new we({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:je.create(),typeName:$.ZodObject,...L(t)});we.strictCreate=(e,t)=>new we({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:je.create(),typeName:$.ZodObject,...L(t)});we.lazycreate=(e,t)=>new we({shape:e,unknownKeys:"strip",catchall:je.create(),typeName:$.ZodObject,...L(t)});un=class extends H{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=o.map(c=>new ve(c.ctx.common.issues));return R(n,{code:T.invalid_union,unionErrors:a}),M}if(s(i,"handleResults"),n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let c=a.map(l=>new ve(l));return R(n,{code:T.invalid_union,unionErrors:c}),M}}get options(){return this._def.options}};un.create=(e,t)=>new un({options:e,typeName:$.ZodUnion,...L(t)});mt=s(e=>e instanceof fn?mt(e.schema):e instanceof Ne?mt(e.innerType()):e instanceof mn?[e.value]:e instanceof hn?e.options:e instanceof gn?U.objectValues(e.enum):e instanceof yn?mt(e._def.innerType):e instanceof ln?[void 0]:e instanceof dn?[null]:e instanceof Ae?[void 0,...mt(e.unwrap())]:e instanceof Qe?[null,...mt(e.unwrap())]:e instanceof di||e instanceof bn?mt(e.unwrap()):e instanceof _n?mt(e._def.innerType):[],"getDiscriminator"),jo=class e extends H{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.object)return R(n,{code:T.invalid_type,expected:C.object,received:n.parsedType}),M;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(R(n,{code:T.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 i=new Map;for(let o of n){let a=mt(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,o)}}return new e({typeName:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};s(xc,"mergeValues");pn=class extends H{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=s((o,a)=>{if(Lo(o)||Lo(a))return M;let c=xc(o.value,a.value);return c.valid?((Fo(o)||Fo(a))&&n.dirty(),{status:n.value,value:c.data}):(R(r,{code:T.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(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};pn.create=(e,t,n)=>new pn({left:e,right:t,typeName:$.ZodIntersection,...L(n)});Ze=class e extends H{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.array)return R(r,{code:T.invalid_type,expected:C.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return R(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(R(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Ie(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>ie.mergeArray(n,a)):ie.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ze.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:e,typeName:$.ZodTuple,rest:null,...L(t)})};Ho=class e extends H{static{s(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.object)return R(r,{code:T.invalid_type,expected:C.object,received:r.parsedType}),M;let i=[],o=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:o._parse(new Ie(r,c,r.path,c)),value:a._parse(new Ie(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ie.mergeObjectAsync(n,i):ie.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof H?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...L(r)}):new e({keyType:Nt.create(),valueType:t,typeName:$.ZodRecord,...L(n)})}},ur=class extends H{static{s(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.map)return R(r,{code:T.invalid_type,expected:C.map,received:r.parsedType}),M;let i=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new Ie(r,c,r.path,[d,"key"])),value:o._parse(new Ie(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return 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}}}};ur.create=(e,t,n)=>new ur({valueType:t,keyType:e,typeName:$.ZodMap,...L(n)});pr=class e extends H{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.set)return R(r,{code:T.invalid_type,expected:C.set,received:r.parsedType}),M;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(R(r,{code:T.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(R(r,{code:T.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return 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)=>o._parse(new Ie(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message: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)}};pr.create=(e,t)=>new pr({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...L(t)});Uo=class e extends H{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.function)return R(n,{code:T.invalid_type,expected:C.function,received:n.parsedType}),M;function r(c,l){return li({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sr(),ft].filter(d=>!!d),issueData:{code:T.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function i(c,l){return li({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sr(),ft].filter(d=>!!d),issueData:{code:T.invalid_return_type,returnTypeError:l}})}s(i,"makeReturnsIssue");let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Dt){let c=this;return pe(async function(...l){let d=new ve([]),u=await c._def.args.parseAsync(l,o).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(m=>{throw d.addIssue(i(p,m)),d})})}else{let c=this;return pe(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new ve([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new ve([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ze.create(t).rest(ht.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||Ze.create([]).rest(ht.create()),returns:n||ht.create(),typeName:$.ZodFunction,...L(r)})}},fn=class extends H{static{s(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};fn.create=(e,t)=>new fn({getter:e,typeName:$.ZodLazy,...L(t)});mn=class extends H{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return R(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:t.data}}get value(){return this._def.value}};mn.create=(e,t)=>new mn({value:e,typeName:$.ZodLiteral,...L(t)});s(Df,"createZodEnum");hn=class e extends H{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return R(n,{expected:U.joinValues(r),received:n.parsedType,code:T.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 R(n,{received:n.data,code:T.invalid_enum_value,options:r}),M}return pe(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};hn.create=Df;gn=class extends H{static{s(this,"ZodNativeEnum")}_parse(t){let n=U.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==C.string&&r.parsedType!==C.number){let i=U.objectValues(n);return R(r,{expected:U.joinValues(i),received:r.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(U.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=U.objectValues(n);return R(r,{received:r.data,code:T.invalid_enum_value,options:i}),M}return pe(t.data)}get enum(){return this._def.values}};gn.create=(e,t)=>new gn({values:e,typeName:$.ZodNativeEnum,...L(t)});Dt=class extends H{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.promise&&n.common.async===!1)return R(n,{code:T.invalid_type,expected:C.promise,received:n.parsedType}),M;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return pe(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Dt.create=(e,t)=>new Dt({type:e,typeName:$.ZodPromise,...L(t)});Ne=class extends H{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s(a=>{R(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?rn(l.value):n.value==="dirty"?rn(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"?rn(c.value):n.value==="dirty"?rn(c.value):c}}if(i.type==="refinement"){let a=s(c=>{let l=i.refinement(c,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?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(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!It(a))return M;let c=i.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>It(a)?Promise.resolve(i.transform(a.value,o)).then(c=>({status:n.value,value:c})):M);U.assertNever(i)}};Ne.create=(e,t,n)=>new Ne({schema:e,typeName:$.ZodEffects,effect:t,...L(n)});Ne.createWithPreprocess=(e,t,n)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:$.ZodEffects,...L(n)});Ae=class extends H{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===C.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ae.create=(e,t)=>new Ae({innerType:e,typeName:$.ZodOptional,...L(t)});Qe=class extends H{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===C.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Qe.create=(e,t)=>new Qe({innerType:e,typeName:$.ZodNullable,...L(t)});yn=class extends H{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};yn.create=(e,t)=>new yn({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});_n=class extends H{static{s(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ar(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};_n.create=(e,t)=>new _n({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});fr=class extends H{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==C.nan){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:C.nan,received:r.parsedType}),M}return{status:"valid",value:t.data}}};fr.create=e=>new fr({typeName:$.ZodNaN,...L(e)});T0=Symbol("zod_brand"),di=class extends H{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}},ui=class e extends H{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),rn(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:$.ZodPipeline})}},bn=class extends H{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(i=>(It(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return ar(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};bn.create=(e,t)=>new bn({innerType:e,typeName:$.ZodReadonly,...L(t)});s(Af,"cleanParams");s(Pf,"custom");R0={object:we.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"})($||($={}));C0=s((e,t={message:`Input not instance of ${e.name}`})=>Pf(n=>n instanceof e,t),"instanceOfType"),Mf=Nt.create,$f=on.create,A0=fr.create,I0=sn.create,Lf=an.create,N0=cn.create,O0=lr.create,D0=ln.create,P0=dn.create,M0=Ot.create,$0=ht.create,L0=je.create,F0=dr.create,j0=gt.create,H0=we.create,U0=we.strictCreate,B0=un.create,G0=jo.create,K0=pn.create,W0=Ze.create,V0=Ho.create,z0=ur.create,q0=pr.create,J0=Uo.create,Y0=fn.create,X0=mn.create,Z0=hn.create,Q0=gn.create,eT=Dt.create,tT=Ne.create,nT=Ae.create,rT=Qe.create,iT=Ne.createWithPreprocess,oT=ui.create,sT=s(()=>Mf().optional(),"ostring"),aT=s(()=>$f().optional(),"onumber"),cT=s(()=>Lf().optional(),"oboolean"),lT={string:s(e=>Nt.create({...e,coerce:!0}),"string"),number:s(e=>on.create({...e,coerce:!0}),"number"),boolean:s(e=>an.create({...e,coerce:!0}),"boolean"),bigint:s(e=>sn.create({...e,coerce:!0}),"bigint"),date:s(e=>cn.create({...e,coerce:!0}),"date")},dT=M});var h={};Q(h,{BRAND:()=>T0,DIRTY:()=>rn,EMPTY_PATH:()=>i0,INVALID:()=>M,NEVER:()=>dT,OK:()=>pe,ParseStatus:()=>ie,Schema:()=>H,ZodAny:()=>Ot,ZodArray:()=>gt,ZodBigInt:()=>sn,ZodBoolean:()=>an,ZodBranded:()=>di,ZodCatch:()=>_n,ZodDate:()=>cn,ZodDefault:()=>yn,ZodDiscriminatedUnion:()=>jo,ZodEffects:()=>Ne,ZodEnum:()=>hn,ZodError:()=>ve,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>Uo,ZodIntersection:()=>pn,ZodIssueCode:()=>T,ZodLazy:()=>fn,ZodLiteral:()=>mn,ZodMap:()=>ur,ZodNaN:()=>fr,ZodNativeEnum:()=>gn,ZodNever:()=>je,ZodNull:()=>dn,ZodNullable:()=>Qe,ZodNumber:()=>on,ZodObject:()=>we,ZodOptional:()=>Ae,ZodParsedType:()=>C,ZodPipeline:()=>ui,ZodPromise:()=>Dt,ZodReadonly:()=>bn,ZodRecord:()=>Ho,ZodSchema:()=>H,ZodSet:()=>pr,ZodString:()=>Nt,ZodSymbol:()=>lr,ZodTransformer:()=>Ne,ZodTuple:()=>Ze,ZodType:()=>H,ZodUndefined:()=>ln,ZodUnion:()=>un,ZodUnknown:()=>ht,ZodVoid:()=>dr,addIssueToContext:()=>R,any:()=>M0,array:()=>j0,bigint:()=>I0,boolean:()=>Lf,coerce:()=>lT,custom:()=>Pf,date:()=>N0,datetimeRegex:()=>Of,defaultErrorMap:()=>ft,discriminatedUnion:()=>G0,effect:()=>tT,enum:()=>Z0,function:()=>J0,getErrorMap:()=>sr,getParsedType:()=>Xe,instanceof:()=>C0,intersection:()=>K0,isAborted:()=>Lo,isAsync:()=>ar,isDirty:()=>Fo,isValid:()=>It,late:()=>R0,lazy:()=>Y0,literal:()=>X0,makeIssue:()=>li,map:()=>z0,nan:()=>A0,nativeEnum:()=>Q0,never:()=>L0,null:()=>P0,nullable:()=>rT,number:()=>$f,object:()=>H0,objectUtil:()=>bc,oboolean:()=>cT,onumber:()=>aT,optional:()=>nT,ostring:()=>sT,pipeline:()=>oT,preprocess:()=>iT,promise:()=>eT,quotelessJson:()=>t0,record:()=>V0,set:()=>q0,setErrorMap:()=>r0,strictObject:()=>U0,string:()=>Mf,symbol:()=>O0,transformer:()=>tT,tuple:()=>W0,undefined:()=>D0,union:()=>B0,unknown:()=>$0,util:()=>U,void:()=>F0});var Sc=v(()=>{$o();wc();Tf();ci();Ff();Mo()});var fe=v(()=>{Sc();Sc()});var Ec,Tc=v(()=>{"use strict";fe();Ec=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 uT,jf=v(()=>{"use strict";fe();Tc();uT=Ec.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 Hf,Uf,Bf,Gf,Rc,Kf,Wf,Vf,pT,zf=v(()=>{"use strict";fe();Hf=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Uf=h.enum(Hf),Bf=["new_to_ai_agents","new_to_this_client","experienced"],Gf=h.enum(Bf),Rc=[{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"}],Kf=Rc.map(e=>e.header),Wf=h.object({experience_level:h.array(Gf).default([]),stack_filters:h.array(h.string()).default([])}).default({experience_level:[],stack_filters:[]}),Vf=h.object({id:h.string().min(1),client:Uf,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:Wf,version:h.number().int().min(1).default(1),changelog:h.string().max(500).optional()}),pT=Vf.extend({body:h.string().min(1)})});var Jf,Bo,Yf,Go,fT,mT,Xf,Zf,Qf,em,Ko,hT,gT,qf,yT,tm,_T,nm=v(()=>{"use strict";fe();Jf=["operating_procedure","code_review","communication_style"],Bo=h.enum(Jf),Yf=["info","recommended","required"],Go=h.enum(Yf),fT=["optional","default_on","mandatory"],mT=h.enum(fT),Xf=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Zf=h.enum(Xf),Qf=["verify","contribute","mixed"],em=h.enum(Qf),Ko=h.object({clients:h.array(Zf).default([]),stacks:h.array(h.string()).default([]),intents:h.array(em).default([])}).default({clients:[],stacks:[],intents:[]}),hT=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,gT=64,qf=200,yT=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")),tm=h.object({id:h.string().min(5).max(gT).regex(hT,"id must match conv_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),scope:Bo,version:h.number().int().min(1),changed_at:yT,changelog:h.string().max(500).optional(),applies_to:Ko,severity:Go.default("recommended"),disableability:mT.default("default_on"),summary:h.string().min(1).max(qf,`summary must be \u2264 ${qf} 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()}),_T=tm.extend({body:h.string().min(1)})});var Pt=v(()=>{"use strict";Tc();jf();zf();nm()});var Cc,Wo,Ac,rm,im,om,bT,sm=v(()=>{"use strict";fe();Cc=h.object({type:h.literal("text"),md:h.string().min(1).max(2e4)}),Wo=h.number().min(0).max(1).optional(),Ac=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:Wo,right:Wo,bottom:Wo,left:Wo}).optional()}),rm=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")}),im=h.object({type:h.literal("accordion"),title:h.string().min(1).max(200),subtag:rm.optional(),blocks:h.array(h.discriminatedUnion("type",[Cc,Ac])).max(50)}),om=h.discriminatedUnion("type",[Cc,Ac,im]),bT=h.array(om).max(100)});var am,vT,cm,lm,wT,kT,xT,dm=v(()=>{"use strict";fe();am=["free","solo_pro","team","enterprise"],vT=h.enum(am),cm=["solo_pro","team","enterprise"],lm=h.enum(cm),wT=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),kT=h.object({user_id:h.string().uuid(),tier:lm,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:wT.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"}),xT=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var um=v(()=>{"use strict"});var ST,ET,TT,pm=v(()=>{"use strict";fe();ST=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),ET=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:ST.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"}),TT=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var fm,RT,mm,hm,gm,ym,CT,_m=v(()=>{"use strict";fe();fm=h.enum(["info","important","critical"]),RT=h.enum(["pass","warn","fail"]),mm=h.object({type:h.enum(["template","lesson"]),id:h.string().min(1)}),hm=h.object({languages:h.array(h.string()).optional(),tools:h.array(h.string()).optional()}).optional(),gm=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")})]),ym=h.object({id:h.string().min(1),title:h.string().min(1),severity:fm,weight:h.number().int().positive().max(100),applies_when:hm,check:gm,fail_message:h.string().min(1),warn_message:h.string().optional(),remediation:mm.optional()}),CT=h.object({version:h.literal(1),checks:h.array(ym).min(1)})});function IT(e){if(!AT.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Vo(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 NT(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var AT,zo,bm,vm,et,Ic,wm,OT,km=v(()=>{"use strict";fe();AT=/^\d{4}-\d{2}-\d{2}$/;s(IT,"isRealDate");zo=h.string().refine(IT,{message:"expected a real calendar date as YYYY-MM-DD"}),bm=["exact","prefix"],vm=h.enum(bm),et=h.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Ic=[2e5,272e3],wm=h.object({model_pattern:h.string().min(1).max(100),match_kind:vm,valid_from:zo,valid_to:zo.nullable().optional(),input:et,output:et,cache_read:et,cache_write_5m:et,cache_write_1h:et,long_context:h.enum(["same_price","tiered"]).optional(),input_above_200k:et.optional(),output_above_200k:et.optional(),cache_read_above_200k:et.optional(),cache_write_5m_above_200k:et.optional(),cache_write_1h_above_200k:et.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=>Vo(e)===0||Vo(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"||Vo(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=>Vo(e)===0||e.context_threshold_tokens==null||Ic.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Ic.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Vo,"aboveRateCount");s(NT,"rowKey");OT=h.object({changelog:h.string().min(1).max(500),as_of:zo,source_url:h.string().url().max(500),rows:h.array(wm).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,o)=>{let a=NT(i),c=n.get(a);c!==void 0?t.addIssue({code:h.ZodIssueCode.custom,path:["rows",o],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,o)});let r=new Map;e.rows.forEach((i,o)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:o,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((o,a)=>o.r.valid_from.localeCompare(a.r.valid_from));for(let o=0;o<i.length-1;o++){let a=i[o],c=i[o+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:h.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var mr=v(()=>{"use strict"});var pi=v(()=>{"use strict"});var Tm=v(()=>{"use strict";pi();mr()});var Rm=v(()=>{"use strict";mr()});var Cm=v(()=>{"use strict";Pt();pi();mr()});var Am=v(()=>{"use strict";pi();mr()});var Im=v(()=>{"use strict";mr();Tm();Rm();Cm();Am();pi()});var XT,ZT,Nm,QT,Om,Nc,Dm,Pm,Mm,$m,eR,Oc=v(()=>{"use strict";fe();Pt();XT=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,ZT=64,Nm=200,QT=1e3,Om=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")),Nc=h.enum(["low","medium","high"]),Dm=h.object({owner:h.string().min(1).max(160).optional(),risk_level:Nc.optional(),reviewed_at:Om.optional()}).default({}),Pm=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}),Mm=h.object({lesson_query:Pm,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:[]}),$m=h.object({id:h.string().min(6).max(ZT).regex(XT,"id must match skill_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),version:h.number().int().min(1),changed_at:Om,tier:h.enum(["community","curated"]).default("curated"),summary:h.string().min(1).max(Nm,`summary must be \u2264 ${Nm} chars (rendered as one line in skill_index)`),description:h.string().max(QT).optional(),applies_to:Ko,membership:Mm,governance:Dm}),eR=$m.extend({body:h.string().default(""),org_id:h.string().uuid().optional(),org_name:h.string().optional()})});var Lm,Fm,jm,Hm,Um,Bm,tR,Gm,nR,rR,Km=v(()=>{"use strict";fe();Oc();Lm=h.enum(["maind","agent-skill"]),Fm=h.enum(["ready","needs_attention","blocked"]),jm=h.enum(["info","important","critical"]),Hm=h.enum(["pass","warn","fail"]),Um=h.enum(["structure","governance","scope","membership","package","references"]),Bm=h.object({id:h.string().min(1),title:h.string().min(1),status:Hm,severity:jm,category:Um,field:h.string().nullable().optional(),message:h.string().min(1),hint:h.string().optional()}),tR=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({}),Gm=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(),nR=h.object({directory_name:h.string().min(1).max(120).optional(),frontmatter:Gm,body:h.string().default(""),file_listing:h.array(h.string()).optional()}),rR=h.object({format:Lm,subject:h.string().min(1),status:Fm,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(Bm),next_steps:h.array(h.string()),trust_note:h.string().min(1)})});var Dc=v(()=>{"use strict"});var Wm,oR,Vm,zm,qm,hr,sR,Jm,Ym,Xm,Zm,Qm,eh,th,nh,aR,rh,ih,oh,Mt,Pc,sh,ah,cR,ch=v(()=>{"use strict";fe();Pt();Dc();Wm=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],oR=h.enum(Wm),Vm=["verdict","advisory"],zm=h.enum(Vm),qm=["block","warn","note"],hr=h.enum(qm),sR=h.object({convention_id:h.string().min(1).max(64),convention_version:h.number().int().min(1),severity:Go,scope:Bo,grade:zm,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()}),Jm=["open","warn","info"],Ym=h.enum(Jm),Xm=["introduced","pre_existing"],Zm=h.enum(Xm),Qm=["full","partial","none"],eh=h.enum(Qm),th=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:Ym,baseline:Zm,evidence_hash:h.string().regex(/^[a-f0-9]{64}$/),count:h.number().int().min(1).max(1e5)}),nh=h.object({version:h.literal(1).default(1),actions:h.object({required:hr.default("block"),recommended:hr.default("warn"),info:hr.default("note")}).default({}),overrides:h.array(h.object({convention_id:h.string().min(1).max(64),action:hr})).max(64).default([]),risk_flag_action:h.enum(["warn","note","ignore"]).default("warn"),detector_overrides:h.array(h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),action:hr,reason:h.string().min(1).max(200)})).max(32).optional()}),aR=nh.parse({}),rh=["ran","not_applicable","unavailable","ungraded"],ih=h.enum(rh),oh=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),state:ih}),Mt=1e3,Pc=h.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),sh=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()}),ah=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:eh}),cR=h.object({changed_symbols:h.array(sh).max(Mt),risk_flags:h.array(h.string().max(64)).max(16),detector_findings:h.array(th).max(64),detector_runs:h.array(oh).min(1).max(32),diff_stats:ah,commit_sha:Pc.optional(),base_sha:Pc.optional(),merge_base_sha:Pc.optional(),dirty:h.boolean().optional(),code_index_version:h.string().min(1).max(32).optional()})});var lh,dh,uh,ph,fh,Mc,lR,dR,mh,hh,gh,yh,_h,uR,pR,bh,vh,wh,fR,kh=v(()=>{"use strict";fe();lh=14,dh=14,uh=14,ph=1,fh=365,Mc=h.number().int().min(ph).max(fh),lR=["propose","direct"],dR="propose",mh=["propose","direct"],hh="propose",gh=["propose","direct"],yh="propose",_h=["off","propose","direct"],uR=["member","admin","owner"],pR="member",bh="off",vh="en",wh=h.object({version:h.literal(1).default(1),at_risk_days:Mc.default(lh),stagnation_days:Mc.default(dh),agent_date_mode:h.enum(lR).default(dR),health_manual_ttl_days:Mc.default(uh),agent_event_mode:h.enum(mh).default(hh),agent_update_mode:h.enum(gh).default(yh),agent_pull_mode:h.enum(_h).default(bh),org_wide_authoring_min_role:h.enum(uR).default(pR),planning_language:h.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(vh)}),fR=wh.parse({})});var xh,mR,Sh=v(()=>{"use strict";fe();xh=h.object({version:h.literal(1).default(1),org_visibility:h.boolean().default(!1),session_span_visibility:h.boolean().default(!0)}),mR=xh.parse({})});var Eh,Th,hR,gR,Rh=v(()=>{"use strict";fe();Eh=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([])}),Th=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:Eh.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()}),hR=Th.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()}),gR=h.object({id:h.string().uuid(),title:h.string(),summary:h.string(),tags:h.array(h.string()).default([])})});var Ch=v(()=>{"use strict"});function qo(e){let t=[],n=null;return e.split(`
|
|
3
|
-
`).forEach((r,i)=>{let o=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(o===""||a>n)return;n=null}if(o===""||o.startsWith("#"))return;let c=
|
|
4
|
-
`).slice(0,1e3)}var
|
|
5
|
-
`).filter(l=>
|
|
2
|
+
var Of=Object.defineProperty;var s=(e,t)=>Of(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var X=(e,t)=>{for(var n in t)Of(e,n,{get:t[n],enumerable:!0})};import{existsSync as x0,mkdirSync as E0,readdirSync as T0,readFileSync as R0,renameSync as A0,statSync as C0,unlinkSync as I0,writeFileSync as N0}from"node:fs";import{homedir as O0}from"node:os";import{join as Po}from"node:path";function Mo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,i=ui(r.id),o=ui(r.key),a=ui(r.title),c=ui(r.status);if(!i||!o||!a||!c)continue;let l=r.here===!1?!1:void 0,d=ui(r.where);if(t.push({id:i,key:o,title:a,status:c,...l===!1?{here:l}:{},...d?{where:d}:{}}),t.length>=D0)break}return t}function $o(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 Df(e=O0()){return Po(e,".maind","assigned-told")}function Pf(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function Mf(e){try{let t=JSON.parse(R0(e,"utf8"));return{ids:Array.isArray(t.ids)?t.ids.filter(n=>typeof n=="string"):[],checked_at:typeof t.checked_at=="number"?t.checked_at:0}}catch{return{ids:[],checked_at:0}}}function $0(e,t,n){E0(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;N0(r,JSON.stringify(n),{mode:384}),A0(r,t)}function $f(e,t,n=Df()){let r=Po(n,`${Pf(e)}.json`);return x0(r)?t-Mf(r).checked_at<M0:!1}function Sc(e,t,n,r=Df()){try{let i=Po(r,`${Pf(e)}.json`),o=Mf(i),a=t.filter(c=>!o.ids.includes(c.id));return $0(r,i,{ids:[...o.ids,...a.map(c=>c.id)].slice(-200),checked_at:n}),L0(r,n,i),a}catch{return[]}}function L0(e,t,n){try{for(let r of T0(e)){let i=Po(e,r);i!==n&&t-C0(i).mtimeMs>P0&&I0(i)}}catch{}}function Lf(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 i=r;if(i.here!==!1||typeof i.project_key!="string")return r;let o=t(i.project_key);return o?{...i,where:o}:r})}:e}function Ff(e){return e==="claude-code"}var D0,P0,M0,ui,Do,pi=w(()=>{"use strict";D0=5,P0=7*24*60*60*1e3,M0=6e4,ui=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Mo,"parseAssignedList");s($o,"assignedNoticeText");s(Df,"assignedToldDir");s(Pf,"safeName");s(Mf,"readTold");s($0,"writeTold");s($f,"checkedRecently");s(Sc,"takeUntold");s(L0,"pruneTold");Do=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=Mo(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 $o(t)}};s(Lf,"labelNestedItems");s(Ff,"clientHasHooks")});function Bf(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let o={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function ir(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function Tc(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Rc(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Ac(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Cc=w(()=>{"use strict";s(Bf,"parseFrame");s(ir,"denyResult");s(Tc,"toolEvent");s(Rc,"policyEvent");s(Ac,"shaEvent")});import{execFileSync as Wf}from"node:child_process";function Vf(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=q0}function J0(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let o of W0){let a=r[o];typeof a=="string"&&Kf.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of V0){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Kf.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function Y0(e,t){let n=t(e);if(n===e)return{field:"",sha:e,verdict:"proven"};if(n!==null)return{field:"",sha:e,verdict:"unknown"};let r=e.slice(0,Gf);for(let i=Gf;i>=z0;i--){let o=r.slice(0,i),a=t(o);if(a!==null&&a.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function or(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function zf(){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 Fo(e=process.cwd()){try{let n=Wf("git",["rev-parse","--show-toplevel"],{cwd:e,env:zf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function X0(e){return t=>{try{let r=Wf("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:zf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function jo(e,t){if(t===null)return[];let n=J0(e);if(n.length===0)return[];let r=X0(t),i=[];for(let{field:o,sha:a}of n){let c=Y0(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var W0,V0,Kf,z0,Gf,q0,Ic=w(()=>{"use strict";W0=["commit_sha","base_sha","head_sha"],V0=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Kf=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,z0=7,Gf=12,q0=10;s(Vf,"isDenyGrade");s(J0,"extractShaArgs");s(Y0,"classifySha");s(or,"shaFindingText");s(zf,"cleanGitEnv");s(Fo,"resolveRepoRootForSha");s(X0,"gitShaResolver");s(jo,"inspectLineForShas")});var Jf=w(()=>{"use strict"});var B,Oc,A,Xe,fi=w(()=>{(function(e){e.assertEqual=i=>{};function t(i){}s(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of o)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(B||(B={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Oc||(Oc={}));A=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=s(e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}},"getParsedType")});var T,Z0,ke,Ho=w(()=>{fi();T=B.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"]),Z0=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ke=class e extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},i=s(o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ke.create=e=>new ke(e)});var Q0,pt,Dc=w(()=>{Ho();fi();Q0=s((e,t)=>{let n;switch(e.code){case T.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,B.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(e.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(e.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(e.options)}, received '${e.received}'`;break;case T.invalid_arguments:n="Invalid function arguments";break;case T.invalid_return_type:n="Invalid function return type";break;case T.invalid_date:n="Invalid date";break;case T.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:B.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case T.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case T.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case T.custom:n="Invalid input";break;case T.invalid_intersection_types:n="Intersection results could not be merged";break;case T.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case T.not_finite:n="Number must be finite";break;default:n=t.defaultError,B.assertNever(e)}return{message:n}},"errorMap"),pt=Q0});function eT(e){Yf=e}function sr(){return Yf}var Yf,Uo=w(()=>{Dc();Yf=pt;s(eT,"setErrorMap");s(sr,"getErrorMap")});function R(e,t){let n=sr(),r=mi({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===pt?void 0:pt].filter(i=>!!i)});e.common.issues.push(r)}var mi,tT,se,M,an,pe,Bo,Ko,It,ar,Pc=w(()=>{Uo();Dc();mi=s(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:o,message:c}},"makeIssue"),tT=[];s(R,"addIssueToContext");se=class e{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return M;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let o=await i.key,a=await i.value;r.push({key:o,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return M;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}},M=Object.freeze({status:"aborted"}),an=s(e=>({status:"dirty",value:e}),"DIRTY"),pe=s(e=>({status:"valid",value:e}),"OK"),Bo=s(e=>e.status==="aborted","isAborted"),Ko=s(e=>e.status==="dirty","isDirty"),It=s(e=>e.status==="valid","isValid"),ar=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Xf=w(()=>{});var O,Zf=w(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}))});function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:s((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function nm(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 _T(e){return new RegExp(`^${nm(e)}$`)}function rm(e){let t=`${tm}T${nm(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 bT(e,t){return!!((t==="v4"||!t)&&uT.test(e)||(t==="v6"||!t)&&fT.test(e))}function wT(e,t){if(!aT.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function vT(e,t){return!!((t==="v4"||!t)&&pT.test(e)||(t==="v6"||!t)&&mT.test(e))}function kT(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}function cr(e){if(e instanceof Se){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Oe.create(cr(r))}return new Se({...e._def,shape:s(()=>t,"shape")})}else return e instanceof ht?new ht({...e._def,type:cr(e.element)}):e instanceof Oe?Oe.create(cr(e.unwrap())):e instanceof Qe?Qe.create(cr(e.unwrap())):e instanceof Ze?Ze.create(e.items.map(t=>cr(t))):e}function $c(e,t){let n=Xe(e),r=Xe(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let i=B.objectKeys(t),o=B.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of o){let l=$c(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],c=t[o],l=$c(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function im(e,t){return new _n({values:e,typeName:$.ZodEnum,...L(t)})}function em(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function om(e,t={},n){return e?Ot.create().superRefine((r,i)=>{let o=e(r);if(o instanceof Promise)return o.then(a=>{if(!a){let c=em(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!o){let a=em(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Ot.create()}var De,Qf,H,nT,rT,iT,oT,sT,aT,cT,lT,dT,Mc,uT,pT,fT,mT,hT,gT,tm,yT,Nt,cn,ln,dn,un,lr,pn,fn,Ot,mt,Ue,dr,ht,Se,mn,ft,Go,hn,Ze,Wo,ur,pr,Vo,gn,yn,_n,bn,Dt,Pe,Oe,Qe,wn,vn,fr,ST,hi,gi,kn,xT,$,ET,sm,am,TT,RT,cm,AT,CT,IT,NT,OT,DT,PT,MT,$T,LT,FT,jT,HT,UT,BT,KT,GT,WT,VT,zT,qT,JT,YT,XT,ZT,QT,eR,tR,nR,rR,iR,oR,sR,aR,lm=w(()=>{Ho();Uo();Zf();Pc();fi();De=class{static{s(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Qf=s((e,t)=>{if(It(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 ke(e.common.issues);return this._error=n,this._error}}},"handleResult");s(L,"processCreateParams");H=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return Xe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Xe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new se,ctx:{common:t.parent.common,data:t.data,parsedType:Xe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(ar(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xe(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Qf(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return It(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=>It(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:Xe(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(ar(i)?i:Promise.resolve(i));return Qf(r,o)}refine(t,n){let r=s(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,o)=>{let a=t(i),c=s(()=>o.addIssue({code:T.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new Pe({schema:this,typeName:$.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 Oe.create(this,this._def)}nullable(){return Qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ht.create(this)}promise(){return Dt.create(this,this._def)}or(t){return mn.create([this,t],this._def)}and(t){return hn.create(this,t,this._def)}transform(t){return new Pe({...L(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new wn({...L(this._def),innerType:this,defaultValue:n,typeName:$.ZodDefault})}brand(){return new hi({typeName:$.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new vn({...L(this._def),innerType:this,catchValue:n,typeName:$.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return gi.create(this,t)}readonly(){return kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nT=/^c[^\s-]{8,}$/i,rT=/^[0-9a-z]+$/,iT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,oT=/^[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,sT=/^[a-z0-9_-]{21}$/i,aT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cT=/^[-+]?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)?)??$/,lT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",uT=/^(?:(?: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])$/,pT=/^(?:(?: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])$/,fT=/^(([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]))$/,mT=/^(([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])$/,hT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tm="((\\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])))",yT=new RegExp(`^${tm}$`);s(nm,"timeRegexSource");s(_T,"timeRegex");s(rm,"datetimeRegex");s(bT,"isValidIP");s(wT,"isValidJWT");s(vT,"isValidCidr");Nt=class e extends H{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_type,expected:A.string,received:o.parsedType}),M}let r=new se,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,c=t.data.length<o.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?R(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&R(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")lT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"email",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Mc||(Mc=new RegExp(dT,"u")),Mc.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"emoji",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")oT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"uuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")sT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"nanoid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")nT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")rT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cuid2",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")iT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ulid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),R(i,{validation:"url",code:T.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"regex",code:T.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?rm(o).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?yT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?_T(o).test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{code:T.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?cT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"duration",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?bT(t.data,o.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"ip",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?wT(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"jwt",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?vT(t.data,o.version)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"cidr",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?hT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?gT.test(t.data)||(i=this._getOrReturnCtx(t,i),R(i,{validation:"base64url",code:T.invalid_string,message:o.message}),r.dirty()):B.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:T.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}};Nt.create=e=>new Nt({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...L(e)});s(kT,"floatSafeRemainder");cn=class e extends H{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)!==A.number){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_type,expected:A.number,received:o.parsedType}),M}let r,i=new se;for(let o of this._def.checks)o.kind==="int"?B.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),R(r,{code:T.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?kT(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),R(r,{code:T.not_finite,message:o.message}),i.dirty()):B.assertNever(o);return{status:i.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,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(i)}]})}_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"&&B.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)}};cn.create=e=>new cn({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...L(e)});ln=class e extends H{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)!==A.bigint)return this._getInvalidInput(t);let r,i=new se;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),R(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):B.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return R(n,{code:T.invalid_type,expected:A.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,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message: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}};ln.create=e=>new ln({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...L(e)});dn=class extends H{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:A.boolean,received:r.parsedType}),M}return pe(t.data)}};dn.create=e=>new dn({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...L(e)});un=class e extends H{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_type,expected:A.date,received:o.parsedType}),M}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return R(o,{code:T.invalid_date}),M}let r=new se,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),R(i,{code:T.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):B.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message: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}};un.create=e=>new un({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...L(e)});lr=class extends H{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:A.symbol,received:r.parsedType}),M}return pe(t.data)}};lr.create=e=>new lr({typeName:$.ZodSymbol,...L(e)});pn=class extends H{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:A.undefined,received:r.parsedType}),M}return pe(t.data)}};pn.create=e=>new pn({typeName:$.ZodUndefined,...L(e)});fn=class extends H{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:A.null,received:r.parsedType}),M}return pe(t.data)}};fn.create=e=>new fn({typeName:$.ZodNull,...L(e)});Ot=class extends H{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}};Ot.create=e=>new Ot({typeName:$.ZodAny,...L(e)});mt=class extends H{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}};mt.create=e=>new mt({typeName:$.ZodUnknown,...L(e)});Ue=class extends H{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return R(n,{code:T.invalid_type,expected:A.never,received:n.parsedType}),M}};Ue.create=e=>new Ue({typeName:$.ZodNever,...L(e)});dr=class extends H{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:A.void,received:r.parsedType}),M}return pe(t.data)}};dr.create=e=>new dr({typeName:$.ZodVoid,...L(e)});ht=class e extends H{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==A.array)return R(n,{code:T.invalid_type,expected:A.array,received:n.parsedType}),M;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(R(n,{code:a?T.too_big:T.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(R(n,{code:T.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(R(n,{code:T.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new De(n,a,n.path,c)))).then(a=>se.mergeArray(r,a));let o=[...n.data].map((a,c)=>i.type._parseSync(new De(n,a,n.path,c)));return se.mergeArray(r,o)}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)}};ht.create=(e,t)=>new ht({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...L(t)});s(cr,"deepPartialify");Se=class e extends H{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=B.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let d=this._getOrReturnCtx(t);return R(d,{code:T.invalid_type,expected:A.object,received:d.parsedType}),M}let{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ue&&this._def.unknownKeys==="strip"))for(let d in i.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new De(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof Ue){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(R(i,{code:T.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new De(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,f=await u.value;d.push({key:p,value:f,alwaysSet:u.alwaysSet})}return d}).then(d=>se.mergeObjectSync(r,d)):se.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 i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:O.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:s(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:s(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:$.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 B.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 B.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}deepPartial(){return cr(this)}partial(t){let n={};for(let r of B.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of B.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Oe;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return im(B.objectKeys(this.shape))}};Se.create=(e,t)=>new Se({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:Ue.create(),typeName:$.ZodObject,...L(t)});Se.strictCreate=(e,t)=>new Se({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:Ue.create(),typeName:$.ZodObject,...L(t)});Se.lazycreate=(e,t)=>new Se({shape:e,unknownKeys:"strip",catchall:Ue.create(),typeName:$.ZodObject,...L(t)});mn=class extends H{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=o.map(c=>new ke(c.ctx.common.issues));return R(n,{code:T.invalid_union,unionErrors:a}),M}if(s(i,"handleResults"),n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let c=a.map(l=>new ke(l));return R(n,{code:T.invalid_union,unionErrors:c}),M}}get options(){return this._def.options}};mn.create=(e,t)=>new mn({options:e,typeName:$.ZodUnion,...L(t)});ft=s(e=>e instanceof gn?ft(e.schema):e instanceof Pe?ft(e.innerType()):e instanceof yn?[e.value]:e instanceof _n?e.options:e instanceof bn?B.objectValues(e.enum):e instanceof wn?ft(e._def.innerType):e instanceof pn?[void 0]:e instanceof fn?[null]:e instanceof Oe?[void 0,...ft(e.unwrap())]:e instanceof Qe?[null,...ft(e.unwrap())]:e instanceof hi||e instanceof kn?ft(e.unwrap()):e instanceof vn?ft(e._def.innerType):[],"getDiscriminator"),Go=class e extends H{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return R(n,{code:T.invalid_type,expected:A.object,received:n.parsedType}),M;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(R(n,{code:T.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 i=new Map;for(let o of n){let a=ft(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,o)}}return new e({typeName:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};s($c,"mergeValues");hn=class extends H{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=s((o,a)=>{if(Bo(o)||Bo(a))return M;let c=$c(o.value,a.value);return c.valid?((Ko(o)||Ko(a))&&n.dirty(),{status:n.value,value:c.data}):(R(r,{code:T.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(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};hn.create=(e,t,n)=>new hn({left:e,right:t,typeName:$.ZodIntersection,...L(n)});Ze=class e extends H{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return R(r,{code:T.invalid_type,expected:A.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return R(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(R(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new De(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>se.mergeArray(n,a)):se.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ze.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:e,typeName:$.ZodTuple,rest:null,...L(t)})};Wo=class e extends H{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!==A.object)return R(r,{code:T.invalid_type,expected:A.object,received:r.parsedType}),M;let i=[],o=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:o._parse(new De(r,c,r.path,c)),value:a._parse(new De(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?se.mergeObjectAsync(n,i):se.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof H?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...L(r)}):new e({keyType:Nt.create(),valueType:t,typeName:$.ZodRecord,...L(n)})}},ur=class extends H{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!==A.map)return R(r,{code:T.invalid_type,expected:A.map,received:r.parsedType}),M;let i=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new De(r,c,r.path,[d,"key"])),value:o._parse(new De(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}}}};ur.create=(e,t,n)=>new ur({valueType:t,keyType:e,typeName:$.ZodMap,...L(n)});pr=class e extends H{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return R(r,{code:T.invalid_type,expected:A.set,received:r.parsedType}),M;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(R(r,{code:T.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(R(r,{code:T.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return 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)=>o._parse(new De(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)}};pr.create=(e,t)=>new pr({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...L(t)});Vo=class e extends H{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return R(n,{code:T.invalid_type,expected:A.function,received:n.parsedType}),M;function r(c,l){return mi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sr(),pt].filter(d=>!!d),issueData:{code:T.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function i(c,l){return mi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sr(),pt].filter(d=>!!d),issueData:{code:T.invalid_return_type,returnTypeError:l}})}s(i,"makeReturnsIssue");let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Dt){let c=this;return pe(async function(...l){let d=new ke([]),u=await c._def.args.parseAsync(l,o).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(m=>{throw d.addIssue(i(p,m)),d})})}else{let c=this;return pe(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new ke([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new ke([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ze.create(t).rest(mt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ze.create([]).rest(mt.create()),returns:n||mt.create(),typeName:$.ZodFunction,...L(r)})}},gn=class extends H{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})}};gn.create=(e,t)=>new gn({getter:e,typeName:$.ZodLazy,...L(t)});yn=class extends H{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return R(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:t.data}}get value(){return this._def.value}};yn.create=(e,t)=>new yn({value:e,typeName:$.ZodLiteral,...L(t)});s(im,"createZodEnum");_n=class e extends H{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return R(n,{expected:B.joinValues(r),received:n.parsedType,code:T.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 R(n,{received:n.data,code:T.invalid_enum_value,options:r}),M}return pe(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};_n.create=im;bn=class extends H{static{s(this,"ZodNativeEnum")}_parse(t){let n=B.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let i=B.objectValues(n);return R(r,{expected:B.joinValues(i),received:r.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=B.objectValues(n);return R(r,{received:r.data,code:T.invalid_enum_value,options:i}),M}return pe(t.data)}get enum(){return this._def.values}};bn.create=(e,t)=>new bn({values:e,typeName:$.ZodNativeEnum,...L(t)});Dt=class extends H{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return R(n,{code:T.invalid_type,expected:A.promise,received:n.parsedType}),M;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return pe(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Dt.create=(e,t)=>new Dt({type:e,typeName:$.ZodPromise,...L(t)});Pe=class extends H{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s(a=>{R(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?an(l.value):n.value==="dirty"?an(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"?an(c.value):n.value==="dirty"?an(c.value):c}}if(i.type==="refinement"){let a=s(c=>{let l=i.refinement(c,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?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(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!It(a))return M;let c=i.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>It(a)?Promise.resolve(i.transform(a.value,o)).then(c=>({status:n.value,value:c})):M);B.assertNever(i)}};Pe.create=(e,t,n)=>new Pe({schema:e,typeName:$.ZodEffects,effect:t,...L(n)});Pe.createWithPreprocess=(e,t,n)=>new Pe({schema:t,effect:{type:"preprocess",transform:e},typeName:$.ZodEffects,...L(n)});Oe=class extends H{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===A.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Oe.create=(e,t)=>new Oe({innerType:e,typeName:$.ZodOptional,...L(t)});Qe=class extends H{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===A.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Qe.create=(e,t)=>new Qe({innerType:e,typeName:$.ZodNullable,...L(t)});wn=class extends H{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};wn.create=(e,t)=>new wn({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});vn=class extends H{static{s(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ar(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};vn.create=(e,t)=>new vn({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});fr=class extends H{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return R(r,{code:T.invalid_type,expected:A.nan,received:r.parsedType}),M}return{status:"valid",value:t.data}}};fr.create=e=>new fr({typeName:$.ZodNaN,...L(e)});ST=Symbol("zod_brand"),hi=class extends H{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}},gi=class e extends H{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),an(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:$.ZodPipeline})}},kn=class extends H{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(i=>(It(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return ar(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};kn.create=(e,t)=>new kn({innerType:e,typeName:$.ZodReadonly,...L(t)});s(em,"cleanParams");s(om,"custom");xT={object:Se.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"})($||($={}));ET=s((e,t={message:`Input not instance of ${e.name}`})=>om(n=>n instanceof e,t),"instanceOfType"),sm=Nt.create,am=cn.create,TT=fr.create,RT=ln.create,cm=dn.create,AT=un.create,CT=lr.create,IT=pn.create,NT=fn.create,OT=Ot.create,DT=mt.create,PT=Ue.create,MT=dr.create,$T=ht.create,LT=Se.create,FT=Se.strictCreate,jT=mn.create,HT=Go.create,UT=hn.create,BT=Ze.create,KT=Wo.create,GT=ur.create,WT=pr.create,VT=Vo.create,zT=gn.create,qT=yn.create,JT=_n.create,YT=bn.create,XT=Dt.create,ZT=Pe.create,QT=Oe.create,eR=Qe.create,tR=Pe.createWithPreprocess,nR=gi.create,rR=s(()=>sm().optional(),"ostring"),iR=s(()=>am().optional(),"onumber"),oR=s(()=>cm().optional(),"oboolean"),sR={string:s(e=>Nt.create({...e,coerce:!0}),"string"),number:s(e=>cn.create({...e,coerce:!0}),"number"),boolean:s(e=>dn.create({...e,coerce:!0}),"boolean"),bigint:s(e=>ln.create({...e,coerce:!0}),"bigint"),date:s(e=>un.create({...e,coerce:!0}),"date")},aR=M});var h={};X(h,{BRAND:()=>ST,DIRTY:()=>an,EMPTY_PATH:()=>tT,INVALID:()=>M,NEVER:()=>aR,OK:()=>pe,ParseStatus:()=>se,Schema:()=>H,ZodAny:()=>Ot,ZodArray:()=>ht,ZodBigInt:()=>ln,ZodBoolean:()=>dn,ZodBranded:()=>hi,ZodCatch:()=>vn,ZodDate:()=>un,ZodDefault:()=>wn,ZodDiscriminatedUnion:()=>Go,ZodEffects:()=>Pe,ZodEnum:()=>_n,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>Vo,ZodIntersection:()=>hn,ZodIssueCode:()=>T,ZodLazy:()=>gn,ZodLiteral:()=>yn,ZodMap:()=>ur,ZodNaN:()=>fr,ZodNativeEnum:()=>bn,ZodNever:()=>Ue,ZodNull:()=>fn,ZodNullable:()=>Qe,ZodNumber:()=>cn,ZodObject:()=>Se,ZodOptional:()=>Oe,ZodParsedType:()=>A,ZodPipeline:()=>gi,ZodPromise:()=>Dt,ZodReadonly:()=>kn,ZodRecord:()=>Wo,ZodSchema:()=>H,ZodSet:()=>pr,ZodString:()=>Nt,ZodSymbol:()=>lr,ZodTransformer:()=>Pe,ZodTuple:()=>Ze,ZodType:()=>H,ZodUndefined:()=>pn,ZodUnion:()=>mn,ZodUnknown:()=>mt,ZodVoid:()=>dr,addIssueToContext:()=>R,any:()=>OT,array:()=>$T,bigint:()=>RT,boolean:()=>cm,coerce:()=>sR,custom:()=>om,date:()=>AT,datetimeRegex:()=>rm,defaultErrorMap:()=>pt,discriminatedUnion:()=>HT,effect:()=>ZT,enum:()=>JT,function:()=>VT,getErrorMap:()=>sr,getParsedType:()=>Xe,instanceof:()=>ET,intersection:()=>UT,isAborted:()=>Bo,isAsync:()=>ar,isDirty:()=>Ko,isValid:()=>It,late:()=>xT,lazy:()=>zT,literal:()=>qT,makeIssue:()=>mi,map:()=>GT,nan:()=>TT,nativeEnum:()=>YT,never:()=>PT,null:()=>NT,nullable:()=>eR,number:()=>am,object:()=>LT,objectUtil:()=>Oc,oboolean:()=>oR,onumber:()=>iR,optional:()=>QT,ostring:()=>rR,pipeline:()=>nR,preprocess:()=>tR,promise:()=>XT,quotelessJson:()=>Z0,record:()=>KT,set:()=>WT,setErrorMap:()=>eT,strictObject:()=>FT,string:()=>sm,symbol:()=>CT,transformer:()=>ZT,tuple:()=>BT,undefined:()=>IT,union:()=>jT,unknown:()=>DT,util:()=>B,void:()=>MT});var Lc=w(()=>{Uo();Pc();Xf();fi();lm();Ho()});var fe=w(()=>{Lc();Lc()});var Fc,jc=w(()=>{"use strict";fe();Fc=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 cR,dm=w(()=>{"use strict";fe();jc();cR=Fc.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 um,pm,fm,mm,Hc,hm,gm,ym,lR,_m=w(()=>{"use strict";fe();um=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],pm=h.enum(um),fm=["new_to_ai_agents","new_to_this_client","experienced"],mm=h.enum(fm),Hc=[{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"}],hm=Hc.map(e=>e.header),gm=h.object({experience_level:h.array(mm).default([]),stack_filters:h.array(h.string()).default([])}).default({experience_level:[],stack_filters:[]}),ym=h.object({id:h.string().min(1),client:pm,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:gm,version:h.number().int().min(1).default(1),changelog:h.string().max(500).optional()}),lR=ym.extend({body:h.string().min(1)})});var wm,zo,vm,qo,dR,uR,km,Sm,xm,Em,Jo,pR,fR,bm,mR,Tm,hR,Rm=w(()=>{"use strict";fe();wm=["operating_procedure","code_review","communication_style"],zo=h.enum(wm),vm=["info","recommended","required"],qo=h.enum(vm),dR=["optional","default_on","mandatory"],uR=h.enum(dR),km=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Sm=h.enum(km),xm=["verify","contribute","mixed"],Em=h.enum(xm),Jo=h.object({clients:h.array(Sm).default([]),stacks:h.array(h.string()).default([]),intents:h.array(Em).default([])}).default({clients:[],stacks:[],intents:[]}),pR=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,fR=64,bm=200,mR=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")),Tm=h.object({id:h.string().min(5).max(fR).regex(pR,"id must match conv_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),scope:zo,version:h.number().int().min(1),changed_at:mR,changelog:h.string().max(500).optional(),applies_to:Jo,severity:qo.default("recommended"),disableability:uR.default("default_on"),summary:h.string().min(1).max(bm,`summary must be \u2264 ${bm} 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()}),hR=Tm.extend({body:h.string().min(1)})});var Pt=w(()=>{"use strict";jc();dm();_m();Rm()});var Uc,Yo,Bc,Am,Cm,Im,gR,Nm=w(()=>{"use strict";fe();Uc=h.object({type:h.literal("text"),md:h.string().min(1).max(2e4)}),Yo=h.number().min(0).max(1).optional(),Bc=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:Yo,right:Yo,bottom:Yo,left:Yo}).optional()}),Am=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")}),Cm=h.object({type:h.literal("accordion"),title:h.string().min(1).max(200),subtag:Am.optional(),blocks:h.array(h.discriminatedUnion("type",[Uc,Bc])).max(50)}),Im=h.discriminatedUnion("type",[Uc,Bc,Cm]),gR=h.array(Im).max(100)});var Om,yR,Dm,Pm,_R,bR,wR,Mm=w(()=>{"use strict";fe();Om=["free","solo_pro","team","enterprise"],yR=h.enum(Om),Dm=["solo_pro","team","enterprise"],Pm=h.enum(Dm),_R=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),bR=h.object({user_id:h.string().uuid(),tier:Pm,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:_R.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"}),wR=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var $m=w(()=>{"use strict"});var vR,kR,SR,Lm=w(()=>{"use strict";fe();vR=h.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),kR=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:vR.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"}),SR=h.object({override_id:h.string().uuid(),reason:h.string().min(3).max(200).optional()})});var Fm,xR,jm,Hm,Um,Bm,ER,Km=w(()=>{"use strict";fe();Fm=h.enum(["info","important","critical"]),xR=h.enum(["pass","warn","fail"]),jm=h.object({type:h.enum(["template","lesson"]),id:h.string().min(1)}),Hm=h.object({languages:h.array(h.string()).optional(),tools:h.array(h.string()).optional()}).optional(),Um=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")})]),Bm=h.object({id:h.string().min(1),title:h.string().min(1),severity:Fm,weight:h.number().int().positive().max(100),applies_when:Hm,check:Um,fail_message:h.string().min(1),warn_message:h.string().optional(),remediation:jm.optional()}),ER=h.object({version:h.literal(1),checks:h.array(Bm).min(1)})});function RR(e){if(!TR.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Xo(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 AR(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var TR,Zo,Gm,Wm,et,Kc,Vm,CR,zm=w(()=>{"use strict";fe();TR=/^\d{4}-\d{2}-\d{2}$/;s(RR,"isRealDate");Zo=h.string().refine(RR,{message:"expected a real calendar date as YYYY-MM-DD"}),Gm=["exact","prefix"],Wm=h.enum(Gm),et=h.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Kc=[2e5,272e3],Vm=h.object({model_pattern:h.string().min(1).max(100),match_kind:Wm,valid_from:Zo,valid_to:Zo.nullable().optional(),input:et,output:et,cache_read:et,cache_write_5m:et,cache_write_1h:et,long_context:h.enum(["same_price","tiered"]).optional(),input_above_200k:et.optional(),output_above_200k:et.optional(),cache_read_above_200k:et.optional(),cache_write_5m_above_200k:et.optional(),cache_write_1h_above_200k:et.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=>Xo(e)===0||Xo(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"||Xo(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=>Xo(e)===0||e.context_threshold_tokens==null||Kc.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Kc.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});s(Xo,"aboveRateCount");s(AR,"rowKey");CR=h.object({changelog:h.string().min(1).max(500),as_of:Zo,source_url:h.string().url().max(500),rows:h.array(Vm).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,o)=>{let a=AR(i),c=n.get(a);c!==void 0?t.addIssue({code:h.ZodIssueCode.custom,path:["rows",o],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,o)});let r=new Map;e.rows.forEach((i,o)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:o,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((o,a)=>o.r.valid_from.localeCompare(a.r.valid_from));for(let o=0;o<i.length-1;o++){let a=i[o],c=i[o+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:h.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var mr=w(()=>{"use strict"});var yi=w(()=>{"use strict"});var Xm=w(()=>{"use strict";yi();mr()});var Zm=w(()=>{"use strict";mr()});var Qm=w(()=>{"use strict";Pt();yi();mr()});var eh=w(()=>{"use strict";yi();mr()});var th=w(()=>{"use strict";mr();Xm();Zm();Qm();eh();yi()});var qR,JR,nh,YR,rh,Gc,ih,oh,sh,ah,XR,Wc=w(()=>{"use strict";fe();Pt();qR=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,JR=64,nh=200,YR=1e3,rh=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")),Gc=h.enum(["low","medium","high"]),ih=h.object({owner:h.string().min(1).max(160).optional(),risk_level:Gc.optional(),reviewed_at:rh.optional()}).default({}),oh=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}),sh=h.object({lesson_query:oh,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:[]}),ah=h.object({id:h.string().min(6).max(JR).regex(qR,"id must match skill_<lowercase_alphanum_underscore>"),title:h.string().min(1).max(200),version:h.number().int().min(1),changed_at:rh,tier:h.enum(["community","curated"]).default("curated"),summary:h.string().min(1).max(nh,`summary must be \u2264 ${nh} chars (rendered as one line in skill_index)`),description:h.string().max(YR).optional(),applies_to:Jo,membership:sh,governance:ih}),XR=ah.extend({body:h.string().default(""),org_id:h.string().uuid().optional(),org_name:h.string().optional()})});var ch,lh,dh,uh,ph,fh,ZR,mh,QR,eA,hh=w(()=>{"use strict";fe();Wc();ch=h.enum(["maind","agent-skill"]),lh=h.enum(["ready","needs_attention","blocked"]),dh=h.enum(["info","important","critical"]),uh=h.enum(["pass","warn","fail"]),ph=h.enum(["structure","governance","scope","membership","package","references"]),fh=h.object({id:h.string().min(1),title:h.string().min(1),status:uh,severity:dh,category:ph,field:h.string().nullable().optional(),message:h.string().min(1),hint:h.string().optional()}),ZR=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({}),mh=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(),QR=h.object({directory_name:h.string().min(1).max(120).optional(),frontmatter:mh,body:h.string().default(""),file_listing:h.array(h.string()).optional()}),eA=h.object({format:ch,subject:h.string().min(1),status:lh,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(fh),next_steps:h.array(h.string()),trust_note:h.string().min(1)})});var Vc=w(()=>{"use strict"});var gh,nA,yh,_h,bh,hr,rA,wh,vh,kh,Sh,xh,Eh,Th,Rh,iA,Ah,Ch,Ih,Mt,zc,Nh,Oh,oA,Dh=w(()=>{"use strict";fe();Pt();Vc();gh=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],nA=h.enum(gh),yh=["verdict","advisory"],_h=h.enum(yh),bh=["block","warn","note"],hr=h.enum(bh),rA=h.object({convention_id:h.string().min(1).max(64),convention_version:h.number().int().min(1),severity:qo,scope:zo,grade:_h,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()}),wh=["open","warn","info"],vh=h.enum(wh),kh=["introduced","pre_existing"],Sh=h.enum(kh),xh=["full","partial","none"],Eh=h.enum(xh),Th=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:vh,baseline:Sh,evidence_hash:h.string().regex(/^[a-f0-9]{64}$/),count:h.number().int().min(1).max(1e5)}),Rh=h.object({version:h.literal(1).default(1),actions:h.object({required:hr.default("block"),recommended:hr.default("warn"),info:hr.default("note")}).default({}),overrides:h.array(h.object({convention_id:h.string().min(1).max(64),action:hr})).max(64).default([]),risk_flag_action:h.enum(["warn","note","ignore"]).default("warn"),detector_overrides:h.array(h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),action:hr,reason:h.string().min(1).max(200)})).max(32).optional()}),iA=Rh.parse({}),Ah=["ran","not_applicable","unavailable","ungraded"],Ch=h.enum(Ah),Ih=h.object({detector_id:h.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:h.string().regex(/^\d+\.\d+\.\d+$/),state:Ch}),Mt=1e3,zc=h.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Nh=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()}),Oh=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:Eh}),oA=h.object({changed_symbols:h.array(Nh).max(Mt),risk_flags:h.array(h.string().max(64)).max(16),detector_findings:h.array(Th).max(64),detector_runs:h.array(Ih).min(1).max(32),diff_stats:Oh,commit_sha:zc.optional(),base_sha:zc.optional(),merge_base_sha:zc.optional(),dirty:h.boolean().optional(),code_index_version:h.string().min(1).max(32).optional()})});var Ph,Mh,$h,Lh,Fh,qc,sA,aA,jh,Hh,Uh,Bh,Kh,cA,lA,Gh,Wh,Vh,dA,zh=w(()=>{"use strict";fe();Ph=14,Mh=14,$h=14,Lh=1,Fh=365,qc=h.number().int().min(Lh).max(Fh),sA=["propose","direct"],aA="propose",jh=["propose","direct"],Hh="propose",Uh=["propose","direct"],Bh="propose",Kh=["off","propose","direct"],cA=["member","admin","owner"],lA="member",Gh="off",Wh="en",Vh=h.object({version:h.literal(1).default(1),at_risk_days:qc.default(Ph),stagnation_days:qc.default(Mh),agent_date_mode:h.enum(sA).default(aA),health_manual_ttl_days:qc.default($h),agent_event_mode:h.enum(jh).default(Hh),agent_update_mode:h.enum(Uh).default(Bh),agent_pull_mode:h.enum(Kh).default(Gh),org_wide_authoring_min_role:h.enum(cA).default(lA),planning_language:h.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Wh)}),dA=Vh.parse({})});var qh,uA,Jh=w(()=>{"use strict";fe();qh=h.object({version:h.literal(1).default(1),org_visibility:h.boolean().default(!1),session_span_visibility:h.boolean().default(!0)}),uA=qh.parse({})});var Yh,Xh,pA,fA,Zh=w(()=>{"use strict";fe();Yh=h.object({tools:h.array(h.string()).default([]),languages:h.array(h.string()).default([]),platforms:h.array(h.string()).default([]),tags:h.array(h.string()).default([])}),Xh=h.object({id:h.string().uuid(),user_id:h.string().uuid(),project:h.string().max(200).nullable().optional(),title:h.string().min(1).max(200),body:h.string().min(1).max(2e4),context:Yh.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()}),pA=Xh.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:h.number()}),fA=h.object({id:h.string().uuid(),title:h.string(),summary:h.string(),tags:h.array(h.string()).default([])})});var Qh=w(()=>{"use strict"});function Qo(e){let t=[],n=null;return e.split(`
|
|
3
|
+
`).forEach((r,i)=>{let o=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(o===""||a>n)return;n=null}if(o===""||o.startsWith("#"))return;let c=hA.exec(r);if(!c)return;let l=c[3]??"";if(mA.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:i+1,value:d})}),t}var mA,hA,eg=w(()=>{"use strict";mA=new Set(["|",">","|-",">-","|+",">+"]),hA=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(Qo,"plainScalarViolations")});function bi(e,t){let n=s(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(p=>{let f=Number(p);return Number.isFinite(f)?f:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,i]=n(e),[o,a]=n(t);for(let c=0;c<Math.max(r.length,o.length);c+=1){let l=(r[c]??0)-(o[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&a.length===0)return 0;if(i.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(i.length,a.length);c+=1){let l=i[c],d=a[c];if(l===void 0)return-1;if(d===void 0)return 1;let u=/^\d+$/.test(l),p=/^\d+$/.test(d);if(u&&p){let f=Number(l)-Number(d);if(f!==0)return f<0?-1:1}else{if(u!==p)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var tg=w(()=>{"use strict";s(bi,"compareSemver")});var wi=w(()=>{"use strict";Pt();Nm();Pt();Pt();Mm();$m();Lm();Km();zm();th();Pt();Wc();hh();Dh();zh();Jh();Zh();Qh();Vc();eg();tg()});function ng(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
4
|
+
`).slice(0,1e3)}var rg=w(()=>{"use strict";s(ng,"nodeEmbedText")});var Jc,Yc=w(()=>{"use strict";Jc=["function","method","class","interface","enum","type_alias"]});function ig(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var og=w(()=>{"use strict";s(ig,"cosineSimilarity")});import{execFileSync as gA}from"node:child_process";import{createHash as yA}from"node:crypto";import{readFileSync as _A}from"node:fs";import{posix as Be}from"node:path";function sg(e){let t=yA("sha256"),n=[];try{n=gA("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
5
|
+
`).filter(l=>bA.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,i=s(l=>{if(r.has(l))return r.get(l);try{let d=_A(Be.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),o=[],a=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=ag(l,i,0),u=Be.dirname(l)==="."?"":Be.dirname(l);l.endsWith("tsconfig.json")&&a.set(u,d),d.paths&&o.push({dir:d.pathsDir??u,baseUrl:d.baseUrl,paths:d.paths})}let c=[];for(let l of n.filter(d=>d.endsWith("package.json"))){let d=cg(i(l));if(!d||typeof d.name!="string")continue;let u=Be.dirname(l)==="."?"":Be.dirname(l),p=a.get(u);c.push({name:d.name,dir:u,exports:d.exports,main:typeof d.main=="string"?d.main:void 0,module:typeof d.module=="string"?d.module:void 0,types:typeof d.types=="string"?d.types:void 0,outDir:p?.outDir,rootDir:p?.rootDir})}for(let l of[...r.keys()].sort())t.update(l).update("\0").update(r.get(l)).update("\0");return{config:{packages:c,tsconfigs:o},fingerprint:t.digest("hex")}}function ag(e,t,n){let r=cg(t(e));if(!r)return{};let i=Be.dirname(e)==="."?"":Be.dirname(e),o={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=Be.normalize(Be.join(i,a.endsWith(".json")?a:a+".json"));o=ag(d,t,n+1)}let c=r.compilerOptions??{},l={...o};return typeof c.outDir=="string"&&(l.outDir=Be.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=Be.normalize(c.rootDir)),c.paths&&typeof c.paths=="object"&&(l.paths=c.paths,l.pathsDir=i,l.baseUrl=typeof c.baseUrl=="string"?c.baseUrl:void 0),l}function cg(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"')n=!0,t+=i;else if(i==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
6
6
|
`;)r++;t+=`
|
|
7
|
-
`}else if(i==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=i}try{let r=JSON.parse(xR(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function xR(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let o=r+1;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e[o]==="}"||e[o]==="]")continue}t+=i}return t}var kR,Fh=v(()=>{"use strict";kR=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(Mh,"loadModuleConfig");s($h,"compilerFacts");s(Lh,"parseJsonc");s(xR,"dropTrailingCommas")});import{posix as Ue}from"node:path";function gi(e,t){let n=Ue.normalize(e).replace(/^\.\//,""),r=[],i=Jo.some(c=>n.endsWith(c));i&&r.push(n);let o=/\.d\.(m|c)?ts$/.exec(n);o&&r.push(n.slice(0,-o[0].length)+".ts",n.slice(0,-o[0].length)+".tsx");let a=/\.(js|jsx|mjs|cjs)$/.exec(n);if(a){let c=n.slice(0,-a[0].length);for(let l of Jo)r.push(c+l)}if(!i&&!o){for(let c of Jo)r.push(n+c);for(let c of Jo)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function Hh(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let o=Hh(i,t);if(o)return o}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return yi(n[t]);for(let i of r){let o=i.indexOf("*");if(o<0)continue;let a=i.slice(0,o),c=i.slice(o+1);if(t.startsWith(a)&&t.endsWith(c)){let l=yi(n[i]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?yi(e):null}function yi(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=yi(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of SR)if(n in t){let r=yi(t[n]);if(r)return r}}return null}function ER(e,t){let n=Ue.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=Ue.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),o=Ue.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(Ue.join(o,n.slice(i.length+1)))}return r}var Jo,SR,Fc,jh,gr,jc=v(()=>{"use strict";Jo=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],SR=["import","default","node","require","types"],Fc={kind:"unresolved"},jh={kind:"external"};s(gi,"resolvePathCandidates");gr=class{static{s(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,i)=>i.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,i)=>i.dir.length-r.dir.length)}resolve(t,n){let r=`${Ue.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let o=gi(Ue.join(Ue.dirname(t),n),this.files);return o?{kind:"file",path:o}:Fc}if(n.startsWith("node:"))return jh;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(o=>n===o.name||n.startsWith(o.name+"/"));if(i){let o=n===i.name?".":"./"+n.slice(i.name.length+1),a=this.viaPackage(i,o);return a?{kind:"file",path:a}:Fc}return jh}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(o=>o.dir===""||t.startsWith(o.dir+"/"));if(!r?.paths)return null;let i=Ue.join(r.dir,r.baseUrl??".");for(let[o,a]of Object.entries(r.paths)){let c=o.indexOf("*"),l=null;if(c<0)o===n&&(l="");else{let d=o.slice(0,c),u=o.slice(c+1);n.startsWith(d)&&n.endsWith(u)&&n.length>=d.length+u.length&&(l=n.slice(d.length,n.length-u.length))}if(l!==null){for(let d of a){let u=gi(Ue.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return Fc}}return null}viaPackage(t,n){let r=[],i=Hh(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let o of[t.module,t.main,t.types])o&&r.push(o);r.push("index")}else r.push(n);for(let o of r)for(let a of ER(t,o)){let c=gi(Ue.join(t.dir,a),this.files);if(c)return c}return null}};s(Hh,"exportTarget");s(yi,"conditionTarget");s(ER,"toSource")});function tt(e){return`${e}#<module>`}function nt(e,t,n){return`${e}#${t}:${n}`}var vn=v(()=>{"use strict";s(tt,"moduleKey");s(nt,"symbolKey")});import{posix as Uh}from"node:path";function Gh(e){let t=new Map,n=new Set,r=new Map,i=new Map,o=new Set,a=s((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),o.add(c.nodeKey),TR.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===nt(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),a(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:o}}function Kh(e,t,n=new gr({packages:[],tsconfigs:[]},t.files)){let r=IR(),i=new Hc(e,t,n);for(let o of e)o.language==="python"?NR(o.filePath,o.refs,o.imports,t,r.push):i.resolveFile(o,r.push);return r.edges}function AR(e,t,n){return t.startsWith(".")?gi(Uh.join(Uh.dirname(e),t),n):null}function IR(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let o=`${n} ${r} ${i}`;e.has(o)||(e.add(o),t.push({srcKey:n,dstKey:r,kind:i}))}}}function NR(e,t,n,r,i){for(let o of t){let a=r.nameToKeys.get(o.targetName);!a||a.length!==1||i(o.fromKey,a[0],o.kind)}for(let o of n){let a=AR(e,o.specifier,r.files);a&&i(o.fromModuleKey,tt(a),"imports")}}function OR(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return nt(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var TR,Bh,RR,CR,Hc,Wh=v(()=>{"use strict";vn();jc();TR=new Set(["function","method","class","interface","enum","type_alias"]),Bh=["function","class","variable","enum","interface","type_alias"],RR=8,CR=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(Gh,"buildResolutionIndex");s(Kh,"resolveCrossFileEdges");s(AR,"resolveImportTarget");s(IR,"edgeCollector");s(NR,"legacyFacts");s(OR,"classKeyOfMethod");Hc=class{static{s(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let o=new Map;for(let a of i.imports)a.localName&&a.importedName&&o.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(i.filePath,o);for(let a of i.refs){if(a.kind==="calls")continue;let c=this.heritage.get(a.fromKey);c?c.push({file:i.filePath,ref:a}):this.heritage.set(a.fromKey,[{file:i.filePath,ref:a}])}}}resolveFile(t,n){for(let r of t.refs){let i=this.resolveRef(t.filePath,r);i&&n(r.fromKey,i,r.kind)}for(let r of t.imports){let i=this.modules.resolve(t.filePath,r.specifier);i.kind==="file"&&n(tt(t.filePath),tt(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let a=this.resolveLocal(t,n.targetName,0);return a?.kind==="symbol"?a.key:null}if(r==="this")return n.kind==="calls"?this.ownMethod(n.fromKey,n.targetName):null;if(n.receiverType&&n.kind==="calls")return this.typedMethod(t,n.receiverType,n.targetName);if(r!=="?"&&r!=="this.*"&&!r.startsWith("this.")){let a=r.endsWith(".*"),c=a?r.slice(0,-2):r;if(CR.has(c)&&!this.bindings.get(t)?.has(c))return null;let l=this.bindings.get(t)?.get(c);if(l&&this.modules.resolve(t,l.specifier).kind!=="file")return null;if(!a){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),o=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=OR(a);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return o.length===1?o[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),o;if(i<0)o=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);o=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(o?.kind!=="symbol")return null;let a=o.key.endsWith(":class")?[o.key]:[...this.implementers(o.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=nt(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let o of this.supertypes(t)){if(!o.endsWith(":class"))continue;let a=o.indexOf("#"),c=nt(o.slice(0,a),`${o.slice(a+1,o.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let o=this.resolveRef(r,i);if(o){n.add(o);for(let a of this.supertypes(o))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let o=t.slice(0,r),a=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?a.slice(0,a.lastIndexOf(".")):c==="class"?a:null;if(!l)return null;let d=nt(o,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>RR)return null;this.memo.set(i,null);let o=this.computeExport(t,n,r);return this.memo.set(i,o),o}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let o=this.topLevel(t,n);if(o)return o;let a=this.bindings.get(t)?.get(n);if(a)return this.resolveBinding(t,a,r);let c=new Map;for(let l of i){if(l.exportedName!=="*"||!l.specifier)continue;let d=this.modules.resolve(t,l.specifier);if(d.kind!=="file")continue;let u=this.resolveExport(d.path,n,r+1);u&&c.set(u.kind==="symbol"?u.key:`ns:${u.file}`,u)}return c.size===1?[...c.values()][0]:null}topLevel(t,n){let r=this.index.topLevel.get(t)?.get(n);if(!r||r.length===0)return null;if(r.length===1)return{kind:"symbol",key:r[0]};let i=s(o=>{let a=Bh.indexOf(o.slice(o.lastIndexOf(":")+1));return a<0?Bh.length:a},"rank");return{kind:"symbol",key:[...r].sort((o,a)=>i(o)-i(a))[0]}}}});function yr(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function _i(e){return e.toLowerCase().endsWith(".d.ts")}var Yo=v(()=>{"use strict";s(yr,"languageForPath");s(_i,"isSkippablePath")});import{appendFileSync as DR,existsSync as Vh,mkdirSync as PR,readFileSync as MR}from"node:fs";import{join as $R}from"node:path";function bi(e,t={}){try{if(!Vh(e)){if(!t.create)return"skipped";PR(e,{recursive:!0})}let n=$R(e,".gitignore"),r=Vh(n)?MR(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),o=Xo.filter(l=>!i.has(l));if(o.length===0)return"unchanged";let a=r===null?[...LR,...o]:o,c=r&&!r.endsWith(`
|
|
7
|
+
`}else if(i==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=i}try{let r=JSON.parse(wA(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function wA(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let o=r+1;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e[o]==="}"||e[o]==="]")continue}t+=i}return t}var bA,lg=w(()=>{"use strict";bA=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;s(sg,"loadModuleConfig");s(ag,"compilerFacts");s(cg,"parseJsonc");s(wA,"dropTrailingCommas")});import{posix as Ke}from"node:path";function vi(e,t){let n=Ke.normalize(e).replace(/^\.\//,""),r=[],i=es.some(c=>n.endsWith(c));i&&r.push(n);let o=/\.d\.(m|c)?ts$/.exec(n);o&&r.push(n.slice(0,-o[0].length)+".ts",n.slice(0,-o[0].length)+".tsx");let a=/\.(js|jsx|mjs|cjs)$/.exec(n);if(a){let c=n.slice(0,-a[0].length);for(let l of es)r.push(c+l)}if(!i&&!o){for(let c of es)r.push(n+c);for(let c of es)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function ug(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let o=ug(i,t);if(o)return o}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return ki(n[t]);for(let i of r){let o=i.indexOf("*");if(o<0)continue;let a=i.slice(0,o),c=i.slice(o+1);if(t.startsWith(a)&&t.endsWith(c)){let l=ki(n[i]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?ki(e):null}function ki(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=ki(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of vA)if(n in t){let r=ki(t[n]);if(r)return r}}return null}function kA(e,t){let n=Ke.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=Ke.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),o=Ke.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(Ke.join(o,n.slice(i.length+1)))}return r}var es,vA,Xc,dg,gr,Zc=w(()=>{"use strict";es=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],vA=["import","default","node","require","types"],Xc={kind:"unresolved"},dg={kind:"external"};s(vi,"resolvePathCandidates");gr=class{static{s(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,i)=>i.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,i)=>i.dir.length-r.dir.length)}resolve(t,n){let r=`${Ke.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let o=vi(Ke.join(Ke.dirname(t),n),this.files);return o?{kind:"file",path:o}:Xc}if(n.startsWith("node:"))return dg;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(o=>n===o.name||n.startsWith(o.name+"/"));if(i){let o=n===i.name?".":"./"+n.slice(i.name.length+1),a=this.viaPackage(i,o);return a?{kind:"file",path:a}:Xc}return dg}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(o=>o.dir===""||t.startsWith(o.dir+"/"));if(!r?.paths)return null;let i=Ke.join(r.dir,r.baseUrl??".");for(let[o,a]of Object.entries(r.paths)){let c=o.indexOf("*"),l=null;if(c<0)o===n&&(l="");else{let d=o.slice(0,c),u=o.slice(c+1);n.startsWith(d)&&n.endsWith(u)&&n.length>=d.length+u.length&&(l=n.slice(d.length,n.length-u.length))}if(l!==null){for(let d of a){let u=vi(Ke.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return Xc}}return null}viaPackage(t,n){let r=[],i=ug(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let o of[t.module,t.main,t.types])o&&r.push(o);r.push("index")}else r.push(n);for(let o of r)for(let a of kA(t,o)){let c=vi(Ke.join(t.dir,a),this.files);if(c)return c}return null}};s(ug,"exportTarget");s(ki,"conditionTarget");s(kA,"toSource")});function tt(e){return`${e}#<module>`}function nt(e,t,n){return`${e}#${t}:${n}`}var Sn=w(()=>{"use strict";s(tt,"moduleKey");s(nt,"symbolKey")});import{posix as pg}from"node:path";function mg(e){let t=new Map,n=new Set,r=new Map,i=new Map,o=new Set,a=s((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),o.add(c.nodeKey),SA.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===nt(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),a(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:o}}function hg(e,t,n=new gr({packages:[],tsconfigs:[]},t.files)){let r=RA(),i=new Qc(e,t,n);for(let o of e)o.language==="python"?AA(o.filePath,o.refs,o.imports,t,r.push):i.resolveFile(o,r.push);return r.edges}function TA(e,t,n){return t.startsWith(".")?vi(pg.join(pg.dirname(e),t),n):null}function RA(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let o=`${n} ${r} ${i}`;e.has(o)||(e.add(o),t.push({srcKey:n,dstKey:r,kind:i}))}}}function AA(e,t,n,r,i){for(let o of t){let a=r.nameToKeys.get(o.targetName);!a||a.length!==1||i(o.fromKey,a[0],o.kind)}for(let o of n){let a=TA(e,o.specifier,r.files);a&&i(o.fromModuleKey,tt(a),"imports")}}function CA(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return nt(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var SA,fg,xA,EA,Qc,gg=w(()=>{"use strict";Sn();Zc();SA=new Set(["function","method","class","interface","enum","type_alias"]),fg=["function","class","variable","enum","interface","type_alias"],xA=8,EA=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(mg,"buildResolutionIndex");s(hg,"resolveCrossFileEdges");s(TA,"resolveImportTarget");s(RA,"edgeCollector");s(AA,"legacyFacts");s(CA,"classKeyOfMethod");Qc=class{static{s(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let o=new Map;for(let a of i.imports)a.localName&&a.importedName&&o.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(i.filePath,o);for(let a of i.refs){if(a.kind==="calls")continue;let c=this.heritage.get(a.fromKey);c?c.push({file:i.filePath,ref:a}):this.heritage.set(a.fromKey,[{file:i.filePath,ref:a}])}}}resolveFile(t,n){for(let r of t.refs){let i=this.resolveRef(t.filePath,r);i&&n(r.fromKey,i,r.kind)}for(let r of t.imports){let i=this.modules.resolve(t.filePath,r.specifier);i.kind==="file"&&n(tt(t.filePath),tt(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let a=this.resolveLocal(t,n.targetName,0);return a?.kind==="symbol"?a.key:null}if(r==="this")return n.kind==="calls"?this.ownMethod(n.fromKey,n.targetName):null;if(n.receiverType&&n.kind==="calls")return this.typedMethod(t,n.receiverType,n.targetName);if(r!=="?"&&r!=="this.*"&&!r.startsWith("this.")){let a=r.endsWith(".*"),c=a?r.slice(0,-2):r;if(EA.has(c)&&!this.bindings.get(t)?.has(c))return null;let l=this.bindings.get(t)?.get(c);if(l&&this.modules.resolve(t,l.specifier).kind!=="file")return null;if(!a){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),o=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=CA(a);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return o.length===1?o[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),o;if(i<0)o=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);o=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(o?.kind!=="symbol")return null;let a=o.key.endsWith(":class")?[o.key]:[...this.implementers(o.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=nt(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let o of this.supertypes(t)){if(!o.endsWith(":class"))continue;let a=o.indexOf("#"),c=nt(o.slice(0,a),`${o.slice(a+1,o.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let o=this.resolveRef(r,i);if(o){n.add(o);for(let a of this.supertypes(o))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let o=t.slice(0,r),a=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?a.slice(0,a.lastIndexOf(".")):c==="class"?a:null;if(!l)return null;let d=nt(o,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>xA)return null;this.memo.set(i,null);let o=this.computeExport(t,n,r);return this.memo.set(i,o),o}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let o=this.topLevel(t,n);if(o)return o;let a=this.bindings.get(t)?.get(n);if(a)return this.resolveBinding(t,a,r);let c=new Map;for(let l of i){if(l.exportedName!=="*"||!l.specifier)continue;let d=this.modules.resolve(t,l.specifier);if(d.kind!=="file")continue;let u=this.resolveExport(d.path,n,r+1);u&&c.set(u.kind==="symbol"?u.key:`ns:${u.file}`,u)}return c.size===1?[...c.values()][0]:null}topLevel(t,n){let r=this.index.topLevel.get(t)?.get(n);if(!r||r.length===0)return null;if(r.length===1)return{kind:"symbol",key:r[0]};let i=s(o=>{let a=fg.indexOf(o.slice(o.lastIndexOf(":")+1));return a<0?fg.length:a},"rank");return{kind:"symbol",key:[...r].sort((o,a)=>i(o)-i(a))[0]}}}});function yr(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function Si(e){return e.toLowerCase().endsWith(".d.ts")}var ts=w(()=>{"use strict";s(yr,"languageForPath");s(Si,"isSkippablePath")});import{appendFileSync as IA,existsSync as yg,mkdirSync as NA,readFileSync as OA}from"node:fs";import{join as DA}from"node:path";function xi(e,t={}){try{if(!yg(e)){if(!t.create)return"skipped";NA(e,{recursive:!0})}let n=DA(e,".gitignore"),r=yg(n)?OA(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),o=ns.filter(l=>!i.has(l));if(o.length===0)return"unchanged";let a=r===null?[...PA,...o]:o,c=r&&!r.endsWith(`
|
|
8
8
|
`)?`
|
|
9
|
-
`:"";return
|
|
9
|
+
`:"";return IA(n,c+a.join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`),r===null?"created":"appended"}catch{return"skipped"}}var
|
|
12
|
-
`));let n=[];return
|
|
13
|
-
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=
|
|
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=
|
|
15
|
-
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=
|
|
16
|
-
`),"norm"),l=c(o),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...
|
|
17
|
-
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var
|
|
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
|
|
19
|
-
`)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=
|
|
20
|
-
`),_=ig(y[0]??"");if(!_)continue;let b=y.slice(1).filter(w=>w.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,rs),truncated:m.length>rs}}return{history:l,regression:d,ownershipWindowCommits:o,pathsTruncated:a.length>qc}}var ZR,QR,og,qc,rs,ng,sg,Yc=v(()=>{"use strict";_e();ZR="",QR="\0",og=200,qc=50,rs=100,ng="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",sg=10;s(Jc,"aggregateHistoryContext");s(eC,"clamp");s(rg,"splitRecords");s(ig,"parseHistoryRecord");s(tC,"aggregateOwnership");s(ag,"readFileHistory")});import{execFileSync as nC}from"node:child_process";import{readdirSync as rC,statSync as cg}from"node:fs";import{isAbsolute as iC,join as Xc,relative as oC,resolve as sC}from"node:path";function cC(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function lC(e,t){try{let n=nC("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 dC(e){let t;try{t=rC(e)}catch{return null}for(let n of t.filter(cC))try{let r=cg(Xc(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function uC(e){try{return cg(e).isDirectory()}catch{return!1}}function pC(e,t){let n=oC(e,t);return!n||n.startsWith("..")?t:n}function Zc(e){let t=aC.filter(c=>uC(Xc(e,c))),n=lC(e,"core.hooksPath"),r=n?iC(n)?n:sC(e,n):Xc(e,".git","hooks"),i=pC(e,r),o=dC(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function Qc(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 aC,el=v(()=>{"use strict";aC=[".githooks",".husky"];s(cC,"isRealHook");s(lC,"gitConfig");s(dC,"hasExecutableHook");s(uC,"isDir");s(pC,"displayPath");s(Zc,"resolveHookState");s(Qc,"describeHookState")});import{posix as lg}from"node:path";function _r(e){let t=fC.exec(e);return t?t[1]:null}function yt(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function wn(e,t){let n=I(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=lg.basename(o),c=_r(a);if(c===null)continue;let l=lg.dirname(o),d=i.get(l)??[];d.push({path:o,name:a,version:c}),i.set(l,d)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>yt(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function wi(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 fC,ki=v(()=>{"use strict";_e();fC=/^(\d+)_.+\.sql$/;s(_r,"parseMigrationVersion");s(yt,"compareVersions");s(wn,"discoverSupabaseProjects");s(wi,"resolveDefaultBranch")});import{execFileSync as mC}from"node:child_process";import{existsSync as me,readFileSync as Lt,readdirSync as is,statSync as nl}from"node:fs";import{posix as B}from"node:path";function _C(e,t){let n=(()=>{let i=I(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=B.dirname(e);for(let i=0;i<8&&r&&r!==B.dirname(r);i++){if(me(B.join(r,".git"))){let o=(()=>{let c=I(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&il(n,o))){let c=bC(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=B.dirname(r)}return null}function bC(e,t){let n=[];for(let r of gC){let i;try{i=is(B.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=B.join(e,a),l=B.join(t,a);try{let d=nl(c),u=nl(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>yC)continue;Lt(c).equals(Lt(l))||n.push(a)}catch{continue}}}return n.sort()}function gg(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let o=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(o){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!o&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${ol}.`})}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 ${B.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=vC(e.hooks);return a&&t.push(a),wC(t)}function vC(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:Qc(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 wC(e){return[...e].sort((t,n)=>dg[t.status]-dg[n.status]||t.id.localeCompare(n.id))}function yg(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function _t(e){let t=e?.trim();return t||null}function kC(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 xC(e){let t=_t(I(e,["rev-parse","--git-dir"]));if(!t)return null;let n=B.isAbsolute(t)?t:B.join(e,t);return me(B.join(n,"rebase-merge"))||me(B.join(n,"rebase-apply"))?"rebase":me(B.join(n,"MERGE_HEAD"))?"merge":me(B.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function SC(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
21
|
-
`))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function
|
|
22
|
-
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function
|
|
23
|
-
`).filter(
|
|
24
|
-
`).map(N=>N.trim()).filter(N=>N.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:m,detachedHead:i,inProgressOp:g,isSharedMainTree:
|
|
25
|
-
`)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=
|
|
26
|
-
`).filter(Boolean):[]}function
|
|
27
|
-
`,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function
|
|
28
|
-
`:i==="r"?"\r":i==="t"?" ":i)}function
|
|
29
|
-
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||o("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...a.keys(),...c.keys()])){if(
|
|
30
|
-
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>
|
|
31
|
-
`);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let o=/(\d+\.\d+\.\d+)/.exec(i);o&&t.push({version:o[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":
|
|
32
|
-
`)){let i=r.trim();if(n){i===
|
|
33
|
-
`)}function
|
|
34
|
-
`).map(t=>t.trim()).filter(t=>t.length>0)}function
|
|
35
|
-
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function
|
|
36
|
-
`).filter(Boolean)){let[p,...f]=u.split(" ");p.startsWith("A")?a.add(f[0]):p.startsWith("R")?(c.push(f[0]),a.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!a.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=
|
|
11
|
+
`),r===null?"created":"appended"}catch{return"skipped"}}var ns,el,PA,rs=w(()=>{"use strict";ns=["code-index.sqlite","code-index.sqlite-wal","code-index.sqlite-shm","index-refresh.lock","conventions-cache.json","conventions-cache.json.*.tmp","context.md","manifest.json","git-context.md","review.md","review.json","review-comment.md","run-review.md","pr-body.md","HANDOFF-*.md"],el=["# 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).'],PA=el;s(xi,"ensureMaindLocalIgnore")});import{execFileSync as MA}from"node:child_process";import{createHash as $A}from"node:crypto";import{readFileSync as LA,readdirSync as FA,statSync as jA}from"node:fs";import{posix as nl,sep as _g}from"node:path";function I(e,t){try{return MA("git",[...HA,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function UA(e){return _g==="/"?e:e.split(_g).join("/")}function is(e){let t=[];for(let n of e){let r=UA(n).trim();if(!r||Si(r))continue;let i=yr(r);i&&t.push({path:r,language:i})}return t}function wg(e){return is(e)}function vg(e){let t=$t(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return is(t.split(`
|
|
12
|
+
`));let n=[];return kg(e,"",n),is(n)}function kg(e,t,n){let r;try{r=FA(nl.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&bg.has(i.name)||bg.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?kg(e,o,n):i.isFile()&&n.push(o)}}function rl(e,t){return il(e,t)??t}function il(e,t){let n=I(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function os(e,t={}){if(Ei(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?rl(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=$t(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of o.split(`
|
|
13
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=tl((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=$t(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=tl(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 tl(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function ol(e,t={}){let n=os(e,t);return n===null?null:is(n.keys())}function Sg(e,t){try{let n=jA(nl.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function ss(e){return $A("sha256").update(e).digest("hex")}function Ei(e){return $t(e,["rev-parse","HEAD"])?.trim()??null}function as(e,t){return $t(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function sl(e){let t=$t(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
|
|
15
|
+
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=BA(e);return n.some(i=>r===null||!KA(e,i,r))}function BA(e){let t=$t(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function KA(e,t,n){let r=t[0],i=t[1];if(tl(t.slice(3))!==n)return!1;let o;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))o="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let p=$t(e,["show",`HEAD:${n}`]);if(p===null)return!1;o=p}else return!1;let a;try{a=LA(nl.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=s(p=>p.replace(/\r\n/g,`
|
|
16
|
+
`),"norm"),l=c(o),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...ns,...el]);return d.slice(l.length).split(`
|
|
17
|
+
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var bg,HA,$t,be=w(()=>{"use strict";ts();rs();bg=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),HA=["-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");$t=I;s(UA,"toPosix");s(is,"classify");s(wg,"classifyPaths");s(vg,"discoverSourceFiles");s(kg,"walk");s(rl,"resolveDiffBase");s(il,"resolveMergeBase");s(os,"enumerateChangedPaths");s(tl,"unquote");s(ol,"changedSourceFiles");s(Sg,"statFile");s(ss,"hashContent");s(Ei,"headCommit");s(as,"resolveCommitSha");s(sl,"isWorktreeDirty");s(BA,"toolIgnoreRepoPath");s(KA,"isToolOnlyIgnoreChange")});function Eg(e,t={}){if(I(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?rl(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=I(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(o,"utf8")>GA?c="none":qA(o,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 qA(e,t,n){let r=null,i=0,o=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
19
|
+
`)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=zA.exec(l);if(d){if(i++,i>WA){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<VA&&r.addedLines.push(l.slice(1))}c()}var GA,WA,VA,xg,zA,Tg=w(()=>{"use strict";be();GA=16*1024*1024,WA=500,VA=4e3,xg=256*1024,zA=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Eg,"changedHunks");s(qA,"parseUnifiedDiff")});function cl(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=Ng&&r++,c>i&&(i=c);for(let d of a.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=a.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>o&&(o=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}function XA(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Ag(e){return e.split(JA).filter(t=>t.trim().length>0)}function Cg(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(YA);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function ZA(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function Og(e,t,n={}){let r=XA(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,Ig),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,al),l=[];for(let u of c){let p=I(e,["log","-n",String(o),Rg,"--",u]),f=p===null?[]:Ag(p).map(Cg).filter(m=>m!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:i?{topAuthors:ZA(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=as(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=I(e,["log",...p,"-n",String(cs+1),Rg,"--name-only","--",...c]),m=[];if(f!==null)for(let g of Ag(f)){let y=g.split(`
|
|
20
|
+
`),_=Cg(y[0]??"");if(!_)continue;let b=y.slice(1).filter(v=>v.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,cs),truncated:m.length>cs}}return{history:l,regression:d,ownershipWindowCommits:o,pathsTruncated:a.length>al}}var JA,YA,Ig,al,cs,Rg,Ng,ll=w(()=>{"use strict";be();JA="",YA="\0",Ig=200,al=50,cs=100,Rg="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",Ng=10;s(cl,"aggregateHistoryContext");s(XA,"clamp");s(Ag,"splitRecords");s(Cg,"parseHistoryRecord");s(ZA,"aggregateOwnership");s(Og,"readFileHistory")});import{execFileSync as QA}from"node:child_process";import{readdirSync as eC,statSync as Dg}from"node:fs";import{isAbsolute as tC,join as dl,relative as nC,resolve as rC}from"node:path";function oC(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function sC(e,t){try{let n=QA("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 aC(e){let t;try{t=eC(e)}catch{return null}for(let n of t.filter(oC))try{let r=Dg(dl(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function cC(e){try{return Dg(e).isDirectory()}catch{return!1}}function lC(e,t){let n=nC(e,t);return!n||n.startsWith("..")?t:n}function ul(e){let t=iC.filter(c=>cC(dl(e,c))),n=sC(e,"core.hooksPath"),r=n?tC(n)?n:rC(e,n):dl(e,".git","hooks"),i=lC(e,r),o=aC(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function pl(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 iC,fl=w(()=>{"use strict";iC=[".githooks",".husky"];s(oC,"isRealHook");s(sC,"gitConfig");s(aC,"hasExecutableHook");s(cC,"isDir");s(lC,"displayPath");s(ul,"resolveHookState");s(pl,"describeHookState")});import{posix as Pg}from"node:path";function _r(e){let t=dC.exec(e);return t?t[1]:null}function gt(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function xn(e,t){let n=I(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=Pg.basename(o),c=_r(a);if(c===null)continue;let l=Pg.dirname(o),d=i.get(l)??[];d.push({path:o,name:a,version:c}),i.set(l,d)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>gt(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function Ti(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 dC,Ri=w(()=>{"use strict";be();dC=/^(\d+)_.+\.sql$/;s(_r,"parseMigrationVersion");s(gt,"compareVersions");s(xn,"discoverSupabaseProjects");s(Ti,"resolveDefaultBranch")});import{execFileSync as uC}from"node:child_process";import{existsSync as me,readFileSync as Lt,readdirSync as ls,statSync as hl}from"node:fs";import{posix as K}from"node:path";function hC(e,t){let n=(()=>{let i=I(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=K.dirname(e);for(let i=0;i<8&&r&&r!==K.dirname(r);i++){if(me(K.join(r,".git"))){let o=(()=>{let c=I(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&yl(n,o))){let c=gC(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=K.dirname(r)}return null}function gC(e,t){let n=[];for(let r of fC){let i;try{i=ls(K.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=K.join(e,a),l=K.join(t,a);try{let d=hl(c),u=hl(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>mC)continue;Lt(c).equals(Lt(l))||n.push(a)}catch{continue}}}return n.sort()}function Ug(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let o=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(o){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!o&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${_l}.`})}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 ${K.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=yC(e.hooks);return a&&t.push(a),_C(t)}function yC(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:pl(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 _C(e){return[...e].sort((t,n)=>Mg[t.status]-Mg[n.status]||t.id.localeCompare(n.id))}function Bg(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function yt(e){let t=e?.trim();return t||null}function bC(e){let t=yt(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 wC(e){let t=yt(I(e,["rev-parse","--git-dir"]));if(!t)return null;let n=K.isAbsolute(t)?t:K.join(e,t);return me(K.join(n,"rebase-merge"))||me(K.join(n,"rebase-apply"))?"rebase":me(K.join(n,"MERGE_HEAD"))?"merge":me(K.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function vC(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
21
|
+
`))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function kC(e){let t=K.join(e,_l);if(!me(t))return[];try{return Lt(t,"utf8").split(`
|
|
22
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function SC(e){try{return xn(e).map(t=>K.join(K.dirname(t.dir),"config.toml"))}catch{return[]}}function xC(e){let t=I(e,["ls-files","-z","--",...pC]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=Hg[K.basename(r)];if(i===void 0)continue;let o=K.dirname(r);if(!EC(e,o))continue;let a=o==="."?"node_modules":K.join(o,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function EC(e,t){return t==="."?!0:gl(e,t)}function gl(e,t){if(me(K.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Lt(K.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Kg(e,t={}){if(yt(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=yt(I(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=bC(e),c=yt(I(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let S=yt(I(e,["rev-parse","HEAD"])),N=yt(I(e,["rev-parse","@{u}"]));l=S!=null&&N!=null?S===N:null,d=I(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(a){let S=yt(I(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(S){let[N,D]=S.split(/\s+/).map(j=>Number.parseInt(j,10));Number.isFinite(N)&&(p=N),Number.isFinite(D)&&(u=D)}}let m=(I(e,["status","--porcelain"])??"").split(`
|
|
23
|
+
`).filter(S=>S.trim().length>0).length,g=wC(e),y=yt(I(e,["rev-parse","--show-toplevel"]))??e,_=vC(I(e,["worktree","list","--porcelain"])??""),b=_[0]?.path??null,v=b!=null&&yl(b,y),x=Math.max(0,_.length-1),C=null;if(b&&!yl(b,y)){let S=s(D=>me(K.join(b,D))&&!me(K.join(y,D)),"here"),N=[...jg,...SC(y),...kC(y),...t.probePaths??[]];C={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(N.filter(S))],missingDeps:xC(y).filter(D=>S(D.dir))}}let k=hC(y,e),E=t.includeRelease===!1?null:OC(e,o),P=[];return a&&(P=(I(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
24
|
+
`).map(N=>N.trim()).filter(N=>N.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:m,detachedHead:i,inProgressOp:g,isSharedMainTree:v,otherWorktrees:x,worktreeParity:C,toolCopyDrift:k,stalePackageBuilds:Gg(y),release:E,unmergedMigrations:P,hooks:ul(e)}}function yl(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function AC(e){let t=new Set;gl(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Lg;){let i=n.pop();if(i===void 0)break;if(i.depth>=RC)continue;let o;try{o=ls(K.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:K.join(i.rel,a.name);if(r+=1,r>=Lg)break;gl(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function CC(e){let t=[];try{let n=K.join(e,"pnpm-workspace.yaml");if(me(n)){let r=!1;for(let i of Lt(n,"utf8").split(`
|
|
25
|
+
`)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=K.join(e,"package.json");if(me(r)){let i=JSON.parse(Lt(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function IC(e){let t=[];for(let n of AC(e)){let r=n==="."?e:K.join(e,n),i=s(o=>n==="."?o:K.join(n,o),"prefix");for(let o of CC(r)){if(t.length>=ml)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=K.join(r,a);if(!me(c))continue;for(let l of ls(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(K.join(a,l.name))),t.length>=ml)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,ml)}function Fg(e){let t=null,n=0,r=[e];for(;r.length>0&&n<$g;){let i=r.pop();if(i===void 0)break;let o;try{o=ls(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=K.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=hl(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=$g)break}}}return t}function NC(e,t){let n=new Set;for(let r of t)try{let i=K.join(e,r,"package.json");if(!me(i))continue;let o=JSON.parse(Lt(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[l,d]of Object.entries(c))typeof d=="string"&&d.startsWith("workspace:")&&n.add(l)}}catch{}return n}function Gg(e){let t=[],n=IC(e),r=NC(e,n);for(let i of n)try{let o=K.join(e,i,"package.json");if(!me(o))continue;let a=JSON.parse(Lt(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let v=b.replace(/^\.\//,"").split("/")[0];return v==="build"||v==="dist"?v:null},"builtSeg"),l=c(a.types??a.typings),d=c(a.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",f=K.join(e,i,"src"),m=K.join(e,i,u);if(!me(f)||!me(m))continue;let g=Fg(f),y=Fg(m);if(g===null||y===null)continue;let _=g-y;_>TC&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function OC(e,t){if(!t)return null;let n=DC(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(o=>o.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function DC(e,t){try{return uC("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function Ai(e,t={}){let n=await Kg(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Ug(n),i=Bg(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var jg,_l,Hg,pC,fC,mC,Mg,TC,ml,$g,RC,Lg,bl=w(()=>{"use strict";fl();be();Ri();jg=["supabase/config.toml","supabase/.temp",".env"],_l=".maind/worktree-requirements",Hg={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},pC=Object.keys(Hg).flatMap(e=>[e,"*/"+e]),fC=["scripts"],mC=512*1024;s(hC,"gatherToolCopyDrift");s(gC,"compareToolDirs");s(Ug,"computeDivergence");s(yC,"computeHookFinding");Mg={open:0,warn:1,info:2,passed:3};s(_C,"sortFindings");s(Bg,"isHealthy");s(yt,"trimOrNull");s(bC,"resolveDefaultBranch");s(wC,"detectInProgressOp");s(vC,"parseWorktrees");s(kC,"readWorktreeRequirements");s(SC,"discoverSupabaseConfigProbes");s(xC,"discoverDependencyDirs");s(EC,"isWorkspaceRoot");s(gl,"hasWorkspaceMarkers");s(Kg,"gatherRepoHealthFacts");s(yl,"samePath");TC=2e3,ml=64,$g=4e3,RC=3,Lg=400;s(AC,"findWorkspaceRoots");s(CC,"workspacePatternsAt");s(IC,"listWorkspacePackageDirs");s(Fg,"newestMtimeUnder");s(NC,"consumedWorkspaceNames");s(Gg,"gatherStalePackageBuilds");s(OC,"gatherReleaseFact");s(DC,"runGh");s(Ai,"checkDivergence")});import{existsSync as wl,readdirSync as Wg}from"node:fs";import{posix as rt}from"node:path";function kl(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(vl)}function zg(e,t={}){let n=t.minFiles??Sl;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Vg)}function wr(e){return`${e.dir}#${e.prefix}`}function Ci(e){let t=PC.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function qg(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=wr(i),a=e.sightingsByNamespace.get(o);if(!a)continue;let c=new Set(a.keys());for(let[l,d]of a){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),f=u.filter(g=>g!==p),m=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${i.prefix}${xl(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${o}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}function Jg(e){return!e.some(t=>t.status==="open")}function xl(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function El(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Yg(e,t){let n=El(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=Ci(rt.basename(n));if(!i)return r;let o=`${rt.dirname(n)}#${i.prefix}`,a=e.namespaces.find(u=>wr(u)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:i.number,taken:d.length>0,sightings:d,suggestion:xl(c.keys(),i.number)}}function ds(e){let t=e?.trim();return t||null}function br(e){return e?e.split(`
|
|
26
|
+
`).filter(Boolean):[]}function MC(e){let t=ds(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 Xg(e,t={}){let n=t.minFiles??Sl,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=I(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=rt.dirname(a),l=Ci(rt.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=o.get(d);u?u.numbers.push(l.number):o.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>zg(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)=>wr(a).localeCompare(wr(c)))}async function Tl(e,t={}){let n=[];if(ds(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 i=Xg(e,t),o=new Map(i.map(m=>[wr(m),m])),a=[...new Set(i.map(m=>m.dir))],c=new Map,l=s((m,g,y)=>{let _=rt.dirname(m),b=Ci(rt.basename(m));if(!b)return;let v=`${_}#${b.prefix}`;if(!o.has(v))return;let x=c.get(v)??new Map,C=x.get(b.number)??[];C.push({kind:g,where:y,path:m}),x.set(b.number,C),c.set(v,x)},"record"),d=s((m,g,y)=>{if(a.length===0)return;let _=I(e,["ls-tree","-r","--name-only",m,"--",...a]);if(_===null){n.push(`could not read ${y}`);return}for(let b of br(_))l(b,g,y)},"scanTree");for(let m of a){let g=rt.join(e,m);if(wl(g))try{for(let y of Wg(g))l(`${m}/${y}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let u=MC(e),p=t.baseRef??(u?`origin/${u}`:null);if(p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let m=ds(I(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of br(I(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==m&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let m=ds(I(e,["rev-parse","--show-toplevel"]));for(let g of br(I(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===m||!wl(y)))for(let _ of a){let b=rt.join(y,_);if(wl(b))try{for(let v of Wg(b))l(`${_}/${v}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${_} in ${y}`)}}}}let f=[];if(p&&a.length>0){let m=I(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);m===null?n.push(vl):f=br(m);let g=I(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(f=[...f,...br(g)]);let y=I(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(f=[...f,...br(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:f,skipped:n}}async function En(e,t={}){let n=await Tl(e,t),r=qg(n);return{ok:Jg(r),findings:r,facts:n}}async function Tn(e,t,n={}){let r=El(t);if(!Ci(rt.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Tl(e,{...n,dirs:n.dirs??[rt.dirname(r)]});return Yg(i,r)}var vl,PC,Sl,Vg,Ii=w(()=>{"use strict";be();vl="could not diff against the base ref \u2014 everything reported as info";s(kl,"isNumberCollisionsGraded");PC=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Sl=3,Vg=.8;s(zg,"isCounterNamespace");s(wr,"namespaceKey");s(Ci,"parseNumbered");s(qg,"computeNumberCollisions");s(Jg,"isCollisionFree");s(xl,"suggestNextNumber");s(El,"normaliseRepoPath");s(Yg,"checkProposedNumber");s(ds,"trimOrNull");s(br,"lines");s(MC,"resolveDefaultBranch");s(Xg,"detectNamespaces");s(Tl,"gatherNumberCollisionFacts");s(En,"checkNumberCollisions");s(Tn,"checkNumberForPath")});import{execFileSync as $C}from"node:child_process";import{createHash as LC}from"node:crypto";function Rl(e){return LC("sha256").update(e).digest("hex")}function FC(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 jC(e){let t=FC(e);return t?Rl(t):null}function UC(e){return typeof e=="string"&&HC.test(e)}function Zg(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(UC(t))return t;let n;try{n=$C("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?jC(n):null}var HC,Al=w(()=>{"use strict";s(Rl,"sha256Hex");s(FC,"normalizeRemoteUrl");s(jC,"projectKeyFromRemote");HC=/^[a-f0-9]{64}$/;s(UC,"isProjectKey");s(Zg,"computeProjectKey")});function Ol(e){return`spec.${e}`}function vr(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 BC(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Qg(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(BC)}function Oi(e){return Rl(JSON.stringify(Qg(e)))}var Ni,Cl,Il,Nl,Dl=w(()=>{"use strict";Al();Ni={det_number_collisions:{version:"1.2.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]},det_changelog_duplicates:{version:"1.0.0",rules:["changelog.duplicate_heading"]},det_workflow_yaml:{version:"1.1.0",rules:["workflow.unparsable_yaml"]},det_release_claims:{version:"1.1.0",rules:["release.phantom","release.unpublished","release.mislabelled"]},det_agent_doc_prose:{version:"1.1.0",rules:["agentdoc.added_prose"]}},Cl="number.collision",Il="theme.dead_class",Nl="acl.missing_revoke";s(Ol,"specDriftRuleId");s(vr,"gradeEngineStatus");s(BC,"codePointCompare");s(Qg,"normalizeEvidenceForHash");s(Oi,"hashDetectorEvidence")});import{existsSync as KC,readFileSync as ey}from"node:fs";import{posix as GC}from"node:path";function fs(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function ms(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
|
|
27
|
+
`,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function Di(e){return e==='"'||e==="'"||e==="`"}function hs(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function us(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let o=e[i];if(Di(o)){i=fs(e,i);continue}if(hs(e,i)){i=ms(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function WC(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(hs(e,t)){t=ms(e,t);continue}break}return e.slice(t)}function kr(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(Di(o)){i=fs(e,i);continue}if(hs(e,i)){i=ms(e,i);continue}o==="["||o==="{"||o==="("?n++:o==="]"||o==="}"||o===")"?n--:o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(o=>WC(o).trim()).filter(o=>o.length>0)}function iy(e){let t=fs(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
28
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function VC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ml(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${VC(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let a=e[i];if(Di(a)){i=fs(e,i);continue}if(hs(e,i)){i=ms(e,i);continue}if(!o){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(a===";")return null;i++;continue}if(a==="[")return us(e,i);if(a===";")return null;i++}return null}function $l(e){let t={};if(!e.startsWith("{"))return t;for(let n of kr(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],o=r[4].trim();Di(o[0]??"")&&(t[i]=iy(o))}return t}function zC(e,t){if(!e.startsWith("{"))return null;for(let n of kr(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function oy(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function sy(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function ay(e,t){let n=Ml(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=sy(),i=[],o=0;for(let a of kr(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=$l(a),l=c[t.key_field];if(!l){o++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:oy(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function cy(e,t){let n=Ml(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=sy(),i=[],o=0,a=s((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of kr(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){o++;continue}let y=$l(f);for(let[_,b]of Object.entries(u.fields??{}))m[_]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let _=zC(f,u.children);g=_&&_.startsWith("[")?us(_,0):null}}else{if(!f.startsWith("[")){o++;continue}let y=kr(f.slice(1,-1));for(let[_,b]of Object.entries(u.fields??{})){let v=y[Number(b)];m[_]=v!==void 0&&Di(v[0]??"")?iy(v):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?us(_,0):null}}if(p){let y=m[t.key_field];if(!y){o++;continue}let _=(t.partition_by??[]).map(b=>m[b]??"");i.push({key:y,fields:oy(m,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,m)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function ty(e,t){return t.extractor==="object-array"?ay(e,t):cy(e,t)}function ly(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function dy(e,t,n){return`spec.drift:${e}#${t}:${n}`}function qC(e){return e.orderPath.join(" / ")||"(flat)"}function uy(e,t,n,r){let i=[],o=s((d,u,p,f,m,g)=>{i.push({id:dy(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:m,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){o("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${qC(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=d.fields[p]??"",m=u.fields[p]??"";f!==m&&o("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${m||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),f=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),m=new Set(f),g=p.filter(y=>m.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";o("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
|
|
29
|
+
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||o("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...a.keys(),...c.keys()])){if(ly(d,e.grounding,r))continue;let u=a.has(d);o("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function JC(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[i.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${d}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function ny(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 py(e,t={}){let n=s(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(u=>{let p=[],f=[];for(let m of r){let g=u.get(m.spec.path),y=u.get(m.impl.path);if(g==null||y==null){let x=g==null?m.spec.path:m.impl.path;p.push(ny(m.id,`Declared file could not be read: ${x}`)),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=ty(g,m.spec),b=ty(y,m.impl);if(_.error||b.error){p.push(ny(m.id,_.error??b.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let v=_.dropped>0||b.dropped>0;f.push({id:m.id,measured:!0,specRecords:_.records.length,implRecords:b.records.length,partial:v}),v&&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(...uy(m,_.records,b.records,e.files)),p.push(...JC(m,{spec:_.records.length,impl:b.records.length},u))}return{findings:p,contracts:f}},"runOnce"),o=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of i(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||a.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(dy(u.id,p.dimension,p.key),p);let l=o.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:a.has(u.id)?{...u,status:"info",detail:`${u.detail}
|
|
30
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>ry[u.status]-ry[p.status]||u.id.localeCompare(p.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:o.contracts}}function Pl(e){let t=e?.trim();return t||null}function gs(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=s(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=s(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let o=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return o(`${u}: not an object`);if(!d)return o(`${u}: \`id\` is missing`);if(!r(l.reason))return o(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let f=n(l[p]);if(!f)return o(`${u}: \`${p}\` is missing`);let m=r(f.extractor);if(!m)return o(`${u}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return o(`${u}: unknown \`${p}.extractor\` "${m}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let f=n(p);if(!f||!r(f.reason))return o(`${u}: exception for "${r(f?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function YC(e){let t=Pl(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 XC(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 fy(e,t={}){let n=s((g,y)=>GC.join(g,y),"join"),r=t.manifestPath??ps,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Pl(I(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!KC(a))return{...o,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=gs(ey(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let d=new Map;for(let g of XC(c))try{d.set(g,ey(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=I(e,["ls-files","-z"]);if(p===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let f=null,m=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:YC(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=Pl(I(e,["merge-base",y,"HEAD"])),!f)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())m.set(_,I(e,["show",`${f}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:f,files:u,skipped:i}}async function Rn(e,t={}){let n=await fy(e,t);return{...py(n,t),facts:n}}function Ll(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var ps,ry,Pi=w(()=>{"use strict";be();ps=".maind/spec-contracts.json";s(fs,"endOfString");s(ms,"skipComment");s(Di,"isQuote");s(hs,"isCommentStart");s(us,"sliceBalanced");s(WC,"stripLeadingTrivia");s(kr,"splitTopLevel");s(iy,"readStringLiteral");s(VC,"escapeRe");s(Ml,"findSymbolArray");s($l,"parseObjectFields");s(zC,"objectFieldRaw");s(oy,"pickFields");s(sy,"makeOrdinals");s(ay,"extractObjectArray");s(cy,"extractNestedList");s(ty,"extractRecords");s(ly,"isGrounded");s(dy,"findingId");s(qC,"partitionOf");s(uy,"compareContract");s(JC,"checkAssertions");s(ny,"unreadable");ry={open:0,warn:1,info:2,passed:3};s(py,"computeSpecDrift");s(Pl,"trimOrNull");s(gs,"parseManifest");s(YC,"resolveDefaultBranch");s(XC,"declaredPaths");s(fy,"gatherSpecDriftFacts");s(Rn,"checkSpecDrift");s(Ll,"isSpecDriftGraded")});import{execFileSync as ZC}from"node:child_process";import{existsSync as QC,readFileSync as eI}from"node:fs";import{join as tI}from"node:path";function Mi(e){let t=[],n=e.split(`
|
|
31
|
+
`);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let o=/(\d+\.\d+\.\d+)/.exec(i);o&&t.push({version:o[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":nI.test(i)?"never-published":"released"})}return t}function hy(e){let t=new Map;for(let n of Mi(e)){let r=t.get(n.version);r?r.push(n):t.set(n.version,[n])}return[...t.entries()].filter(([,n])=>n.length>1).map(([n,r])=>({version:n,count:r.length,lines:r.map(i=>i.line),shapes:r.map(i=>i.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function gy(e,t){let n=hy(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of Mi(t))r.set(a.version,(r.get(a.version)??0)+1);let i=[],o=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?i:o).push({...a,countBefore:c})}return{introduced:i,preExisting:o,baseResolved:!0}}function yy(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let i=gy(r.head,e.baseRef===null?null:r.base);for(let o of i.introduced)t.push({path:r.path,version:o.version,level:"open",count:o.count,countBefore:o.countBefore,lines:o.lines,title:`${r.path}: version ${o.version} has ${o.count} headings (was ${o.countBefore})`});for(let o of i.preExisting)t.push({path:r.path,version:o.version,level:"info",count:o.count,countBefore:o.countBefore,lines:o.lines,title:`${r.path}: version ${o.version} already had ${o.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function my(e,t){try{return ZC("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function rI(e,t={}){let n=my(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null,o=r.map(a=>{let c=tI(e,a);return{path:a,head:QC(c)?eI(c,"utf8"):null,base:i===null?null:my(["show",`${i}:${a}`],e)}});return{isRepo:!0,baseRef:i,files:o}}function Fl(e,t={}){return yy(rI(e,t))}var nI,ys=w(()=>{"use strict";nI=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;s(Mi,"parseVersionHeadings");s(hy,"findDuplicateHeadings");s(gy,"classifyIntroduced");s(yy,"computeChangelogDuplicates");s(my,"git");s(rI,"gatherChangelogFacts");s(Fl,"checkChangelogDuplicates")});import{execFileSync as iI}from"node:child_process";import{existsSync as oI,readFileSync as _y}from"node:fs";import{dirname as by,join as wy}from"node:path";function ky(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),i=new Set(n.documentedBase??n.documented),o=[...n.documented].sort(bi);for(let a of o){if(r.has(a)||bi(a,n.version)>=0)continue;let c=!i.has(a);t.push({package:n.name,version:a,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${a} is newly documented as released but the registry never served it`:`${n.name}@${a} is documented as released but the registry never served it`})}for(let a of[...n.neverPublished??[]].sort(bi))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 vy(e){let t=Mi(e),n=[...new Set(t.filter(o=>o.shape!=="never-published").map(o=>o.version))],r=new Set(n),i=[...new Set(t.filter(o=>o.shape==="never-published"&&!r.has(o.version)).map(o=>o.version))];return{documented:n,neverPublished:i}}function jl(e,t){try{return iI("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function Sy(e,t=null){let n=jl(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let o;try{o=JSON.parse(_y(wy(e,i),"utf8"))}catch{continue}if(o.private===!0||typeof o.name!="string"||typeof o.version!="string")continue;let a=by(i)==="."?"":by(i),c=wy(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=oI(c)?vy(_y(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:jl(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:vy(p).documented;r.push({dir:a,name:o.name,version:o.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function sI(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 xy(e,t={}){if(jl(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=Sy(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??sI,i={};for(let o of n)try{i[o.name]=await r(o.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${o.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:i,registryReachable:!0,registryError:null}}async function Hl(e,t={}){return ky(await xy(e,t))}var Ul=w(()=>{"use strict";wi();ys();s(ky,"computeReleaseClaims");s(vy,"claimsOf");s(jl,"git");s(Sy,"discoverPackages");s(sI,"packument");s(xy,"gatherReleaseClaimsFacts");s(Hl,"checkReleaseClaims")});import{execFileSync as aI}from"node:child_process";import{existsSync as cI,readFileSync as lI}from"node:fs";import{join as dI}from"node:path";function Kl(e){let t=[],n=!1;for(let r of e.split(`
|
|
32
|
+
`)){let i=r.trim();if(n){i===Ay&&(n=!1);continue}if(i===Ry){n=!0;continue}t.push(r)}return t.join(`
|
|
33
|
+
`)}function Ey(e){return e.split(`
|
|
34
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function Cy(e,t){let n=new Map;for(let o of Ey(t??""))n.set(o,(n.get(o)??0)+1);let r=[];for(let o of Ey(e)){let a=n.get(o)??0;a>0?n.set(o,a-1):r.push(o)}let i=0;for(let o of n.values())i+=o;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function Iy(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=Cy(Kl(n.head),n.base===null?null:Kl(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 Bl(e,t){try{return aI("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function Ny(e,t={}){let n=Bl(["ls-files","-z","--",...Ty],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Bl(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,o=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=dI(e,a);return{path:a,head:cI(c)?lI(c,"utf8"):null,base:r===null?null:Bl(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:o}}function Gl(e,t={}){return Iy(Ny(e,t))}var Ty,Ry,Ay,Wl=w(()=>{"use strict";Ty=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],Ry="<!-- maind:conventions v1 begin -->",Ay="<!-- maind:conventions v1 end -->";s(Kl,"stripManagedConventionsBlock");s(Ey,"contentLines");s(Cy,"proseDelta");s(Iy,"computeAgentDocProse");s(Bl,"git");s(Ny,"gatherAgentDocProseFacts");s(Gl,"checkAgentDocProse")});var Oy,Dy,Vl=w(()=>{"use strict";Oy=[".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"],Dy=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 uI}from"node:child_process";import{existsSync as pI,readFileSync as fI}from"node:fs";import{join as mI}from"node:path";function My(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?[]:Qo(n.base).map(i=>i.value));for(let i of Qo(n.content)){let o=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,a=e.baseRef!==null&&!r.has(i.value);t.push({path:n.path,level:a?"open":"info",line:i.line,value:i.value,title:`${n.path}:${i.line}: unquoted plain scalar containing ": " \u2014 ${o}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function Py(e,t){try{return uI("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function $y(e,t={}){let n=Py(["ls-files","-z","--",...Oy],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(o=>{let a=mI(e,o);return{path:o,content:pI(a)?fI(a,"utf8"):null,base:i===null?null:Py(["show",`${i}:${o}`],e)}})}}function zl(e,t={}){return My($y(e,t))}var ql=w(()=>{"use strict";wi();Vl();s(My,"computeWorkflowYaml");s(Py,"git");s($y,"gatherWorkflowYamlFacts");s(zl,"checkWorkflowYaml")});import{readFileSync as hI}from"node:fs";import{join as gI,posix as yI}from"node:path";function Ly(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],o=e[n+1];if(i==="-"&&o==="-"){for(;n<r&&e[n]!==`
|
|
35
|
+
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function Ge(e){let t=[],n="",r=!1,i=!1,o=s(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function _t(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function _I(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!_t(a[1]).map(f=>Ge(f)?.name??"").filter(Boolean).includes("postgres"))return null;let c=/\bIN\s+SCHEMA\s+([\s\S]+?)(?=\s+FOR\s+ROLE\b|$)/i.exec(n);if(!c||!_t(c[1]).map(p=>Ge(p)?.name??"").filter(Boolean).includes("public"))return null;let d=_t(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Ge(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of _t(i)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...$i]};f[2]!=="("&&$i.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Fy(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(n)return null;let a=i.trim();if(bI.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!_t(l[1]).map(f=>Ge(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=_t(p).map(m=>Ge(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(f.length===0)return null;c=f}let d=_t(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Ge(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of _t(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase(),g=f[2]==="(";if(m==="ALL")return{tables:c,roles:d,writePrivs:[...$i]};!g&&$i.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function Yl(e){let t=new Map,n=[...e].sort((i,o)=>gt(i.version,o.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let o=Ly(i.content);for(let a of o.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=_I(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=Ge(l[2]);if(!p||p.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(p.name))continue;t.set(p.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(d){let p=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let f of _t(p)){let m=Ge(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=Ge(u[1]),f=Ge(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=Fy(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 Jl(e){let t=[];for(let[n,r]of Yl(e)){let i=[];r.anonAddressed||i.push("anon"),$i.every(o=>r.authWritesRevoked.has(o))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function jy(e){let t=Jl(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Jl(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function Hy(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Zl(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(_s)||t.endsWith(Xl))}function vI(e,t){try{let n=hI(e,"utf8");return n.length>t?null:n}catch{return null}}function kI(e,t,n,r,i){let o=I(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(o===null)return i.push(`could not diff ${t} against ${r} ${_s}`),null;let a=new Set,c=[];for(let u of o.split(`
|
|
36
|
+
`).filter(Boolean)){let[p,...f]=u.split(" ");p.startsWith("A")?a.add(f[0]):p.startsWith("R")?(c.push(f[0]),a.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!a.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=yI.basename(u),f=_r(p);if(f===null)continue;let m=I(e,["show",`${r}:${u}`]);if(m===null)return i.push(`could not read ${u} at ${r} ${Xl}`),null;l.push({name:p,version:f,content:m})}return l}function An(e,t={}){let n=t.maxFileBytes??wI,r=[],i=xn(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let o=t.includeBaseline!==!1,a=null;if(o)if(t.baseRef)a=t.baseRef;else{let f=Ti(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${_s}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of i){let m=[];for(let _ of f.files){let b=vI(gI(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:kI(e,f.dir,m,a,r);c.push(...jy({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:Yl(g).size})}let d=l.reduce((f,m)=>f+m.migrationCount,0),u=Hy(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 $i,bI,wI,_s,Xl,bs=w(()=>{"use strict";be();Ri();s(Ly,"stripSql");s(Ge,"normalizeQualifiedIdent");s(_t,"splitTopLevel");$i=["INSERT","UPDATE","DELETE"];s(_I,"parseDefaultAclTables");bI=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Fy,"parseTableRevoke");s(Yl,"foldTableAcl");s(Jl,"evaluateTableAcl");s(jy,"computeTableAclFindings");s(Hy,"deriveTableAclVerdict");wI=5e6,_s="\u2014 findings reported ungraded (open)",Xl="\u2014 baseline degraded";s(Zl,"isTableAclGraded");s(vI,"safeRead");s(kI,"baseFilesFor");s(An,"checkTableAclLint")});import{readFileSync as SI}from"node:fs";import{join as Ql}from"node:path";function td(e){return e.verdict!=="no_opinion"&&e.graded}function nd(e){let t=new Set;for(let n of e.matchAll(xI))t.add(n[1]);return t}function rd(e){return new Set([...e].map(t=>t.split("-")[0]))}function Vy(e){return e.split(`
|
|
37
37
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
38
|
-
`)}function
|
|
39
|
-
`).filter(Boolean)}function
|
|
40
|
-
`).filter(Boolean)),l=s(p=>c.has(p)?I(e,["show",`${o}:${p}`]):
|
|
41
|
-
`).filter(i=>i.length>0&&n.some(o=>OA(i,o)))}function OA(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let o=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?o.endsWith(r.slice(1)):o===r}function DA(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(i=>I(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Ul(e,t){try{let n=TA(e,"utf8");return n.length>t?null:n}catch{return null}}var vy,RA,CA,yy,IA,hs=v(()=>{"use strict";_e();s(Bl,"isThemeClassDriftGraded");vy=["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"],RA=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,CA=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+vy.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Gl,"extractTokens");s(Kl,"deriveNamespaces");s(wy,"stripCommentLines");s(Wl,"evaluateThemeClasses");s(gy,"findingKey");s(AA,"gradeAgainstBaseline");s(ky,"deriveThemeClassVerdict");yy=["*.ts","*.tsx","*.js","*.jsx"],IA=15e5;s(Vl,"isScannableSource");s(_y,"listTracked");s(Tn,"checkThemeClassDrift");s(NA,"baselineFindings");s(by,"listTrackedAt");s(OA,"matchesSourcePattern");s(DA,"resolveBaseRef");s(Ul,"safeRead")});function zl(e){return Ti[e].version}function wt(e,t,n,r){return{detector_id:e,detector_version:zl(e),state:t,finding_count:n,...r?{reason:r}:{}}}function V(e,t,n){return{summary:wt(e,t,0,n),findings:[]}}function Cy(e){return e==="open"||e==="warn"||e==="info"}function PA(e){let t="det_number_collisions";if(!e.ok)return V(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return V(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return V(t,"not_applicable","no numbered namespaces");if(!ll(n))return V(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!Cy(o.status))continue;let{level:a,baseline:c}=wr(o.status);i.push({detector_id:t,rule_id:gl,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:wt(t,"ran",i.length),findings:i}}function MA(e){let t="det_spec_drift";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return V(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return V(t,"not_applicable",n.reason??"no opinion");if(!Sl(n))return V(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Cy(i.status))continue;let{level:o,baseline:a}=wr(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:bl(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:wt(t,"ran",r.length),findings:r}}function $A(e){let t="det_theme_class_drift";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable","no theme tokens");if(!Bl(n))return V(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=wr(i.status);r.push({detector_id:t,rule_id:yl,level:o,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:wt(t,"ran",r.length),findings:r}}function LA(e){let t="det_table_acl_lint";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable","no supabase migrations");if(!jl(n))return V(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=wr(i.status);r.push({detector_id:t,rule_id:_l,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:wt(t,"ran",r.length),findings:r}}function FA(e){let t="det_changelog_duplicates";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return V(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,i.version],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function jA(e){let t="det_workflow_yaml";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return V(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,String(i.line)],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function HA(e){let t="det_release_claims";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?V(t,"ungraded",n.reason??"registry unreachable"):V(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function UA(e){let t="det_agent_doc_prose";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.files.length>0&&n.facts.baseRef===null?V(t,"ungraded",n.reason??"no base ref to grade against"):V(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function ql(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||gs[e.level]-gs[t.level]||Sy[e.baseline]-Sy[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Ey(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function BA(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Ri(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${o}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:zl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:o,count:1})}else{let o=`${i.detector_id}|${i.rule_id}`,a=n.get(o);a?(a.evidence.push(...i.evidence),a.count+=1,gs[i.level]<gs[a.level]&&(a.level=i.level)):n.set(o,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:zl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Ri(i.evidence),count:i.count});return r.sort(ql)}function GA(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function Oe(e){let t={det_number_collisions:PA(e.number),det_spec_drift:MA(e.spec),det_theme_class_drift:$A(e.theme),det_table_acl_lint:LA(e.acl),det_changelog_duplicates:FA(e.changelog),det_workflow_yaml:jA(e.workflow),det_release_claims:HA(e.release),det_agent_doc_prose:UA(e.agentDoc)},n=xy.map(l=>t[l].summary),r=xy.flatMap(l=>t[l].findings),i=BA(r),o=[...i].sort((l,d)=>Ey(l)-Ey(d)||ql(l,d)).slice(0,Ty).sort(ql),a=i.length-o.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Ri(l.evidence),title:l.title}));return{findings:o,coverage:GA(n,a),engines:n,local:c,truncated:a}}function vt(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 Yl(e){return e instanceof Error?e.message:String(e)}async function Ft(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Yl(t)}}}async function Xl(e,t={}){let n={...Ry,...t.engines};try{if(!Ay(e))return Oe(vt("not a git work tree"));let r=await Iy(e,n,t.baseRef),i=await Jl(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Oe({...r,number:i})}catch(r){return Oe(vt(`detector adapter failed: ${Yl(r)}`))}}async function Zl(e,t={}){let n={...Ry,...t.engines};try{if(!Ay(e)){let a=Oe(vt("not a git work tree"));return{commit:a,local:a}}let r=await Iy(e,n,t.baseRef),i=await Jl(e,n,t.baseRef,"commit"),o=await Jl(e,n,t.baseRef,"local");return{commit:Oe({...r,number:i}),local:Oe({...r,number:o})}}catch(r){let i=Oe(vt(`detector adapter failed: ${Yl(r)}`));return{commit:i,local:i}}}function Ay(e){return I(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function Iy(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Ft(()=>t.spec(e,r)),theme:await Ft(()=>t.theme(e,r)),acl:await Ft(()=>t.acl(e,r)),changelog:await Ft(()=>t.changelog(e,r)),workflow:await Ft(()=>t.workflow(e,r)),release:await Ft(()=>t.release(e,r)),agentDoc:await Ft(()=>t.agentDoc(e,r))}}function Jl(e,t,n,r,i){let o=r==="local";return Ft(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:o,includeWorktrees:i??o}))}var Ty,Ry,xy,gs,Sy,Ql=v(()=>{"use strict";_e();vl();Ei();Ai();Cl();Ol();Ml();ps();ms();hs();Ty=64,Ry={number:s((e,t)=>kn(e,t),"number"),spec:s((e,t)=>Sn(e,t),"spec"),theme:s((e,t)=>Tn(e,t),"theme"),acl:s((e,t)=>En(e,t),"acl"),changelog:s((e,t)=>El(e,t),"changelog"),workflow:s((e,t)=>Pl(e,t),"workflow"),release:s((e,t)=>Rl(e,t),"release"),agentDoc:s((e,t)=>Nl(e,t),"agentDoc")},xy=["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(zl,"versionOf");s(wt,"summary");s(V,"noFindings");s(Cy,"isFindingStatus");s(PA,"adaptNumber");s(MA,"adaptSpec");s($A,"adaptTheme");s(LA,"adaptAcl");s(FA,"adaptChangelog");s(jA,"adaptWorkflow");s(HA,"adaptRelease");s(UA,"adaptAgentDoc");gs={open:0,warn:1,info:2},Sy={introduced:0,pre_existing:1};s(ql,"compareWire");s(Ey,"capPriority");s(BA,"buildWire");s(GA,"deriveCoverage");s(Oe,"adaptDetectorReports");s(vt,"unavailableDetectorReports");s(Yl,"errorText");s(Ft,"attempt");s(Xl,"runRepoHealthDetectors");s(Zl,"runRepoHealthDetectorScopes");s(Ay,"insideWorkTree");s(Iy,"runSharedEngines");s(Jl,"runNumberEngine")});var Ny,ed=v(()=>{"use strict";Dl();Ny=[{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:cy},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function Oy(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Ny){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=KA(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function KA(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
42
|
-
`):t.readUntracked(e)}var
|
|
38
|
+
`)}function id(e){let t=rd(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=Vy(i),a=new Set;for(let c of o.matchAll(EI)){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 Uy(e){return`${e.file} ${e.klass}`}function TI(e,t){let n=t===null?null:new Set(t.map(Uy));return e.map(r=>({...r,status:n!==null&&n.has(Uy(r))?"info":"open"}))}function zy(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function od(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Ky(e,t){let n=I(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
39
|
+
`).filter(Boolean)}function Cn(e,t={}){let n=t.maxFileBytes??RI,r=new Set;for(let u of Ky(e,["*.css"])){let p=ed(Ql(e,u),n);if(p!==null)for(let f of nd(p))r.add(f)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>By.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):By,o=[];for(let u of Ky(e,i)){if(!od(u))continue;let p=ed(Ql(e,u),n);p!==null&&o.push({path:u,content:p})}let a=id({tokens:r,sources:o}),c=t.includeBaseline===!1?null:AI(e,i,n,t.baseRef),l=TI(a,c?.findings??null),d=zy(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:rd(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function AI(e,t,n,r){let i=r??II(e);if(i===null)return null;let o=I(e,["merge-base",i,"HEAD"])?.trim();if(!o)return null;let a=I(e,["diff","--name-only","--no-renames",o]);if(a===null)return null;let c=new Set(a.split(`
|
|
40
|
+
`).filter(Boolean)),l=s(p=>c.has(p)?I(e,["show",`${o}:${p}`]):ed(Ql(e,p),n),"atBase"),d=new Set;for(let p of Gy(e,o,["*.css"])){let f=l(p);if(f!==null)for(let m of nd(f))d.add(m)}if(d.size===0)return{findings:[],mergeBase:o};let u=[];for(let p of Gy(e,o,t)){if(!od(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:id({tokens:d,sources:u}),mergeBase:o}}function Gy(e,t,n){let r=I(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
41
|
+
`).filter(i=>i.length>0&&n.some(o=>CI(i,o)))}function CI(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let o=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?o.endsWith(r.slice(1)):o===r}function II(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(i=>I(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function ed(e,t){try{let n=SI(e,"utf8");return n.length>t?null:n}catch{return null}}var Wy,xI,EI,By,RI,ws=w(()=>{"use strict";be();s(td,"isThemeClassDriftGraded");Wy=["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"],xI=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,EI=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Wy.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(nd,"extractTokens");s(rd,"deriveNamespaces");s(Vy,"stripCommentLines");s(id,"evaluateThemeClasses");s(Uy,"findingKey");s(TI,"gradeAgainstBaseline");s(zy,"deriveThemeClassVerdict");By=["*.ts","*.tsx","*.js","*.jsx"],RI=15e5;s(od,"isScannableSource");s(Ky,"listTracked");s(Cn,"checkThemeClassDrift");s(AI,"baselineFindings");s(Gy,"listTrackedAt");s(CI,"matchesSourcePattern");s(II,"resolveBaseRef");s(ed,"safeRead")});function sd(e){return Ni[e].version}function wt(e,t,n,r){return{detector_id:e,detector_version:sd(e),state:t,finding_count:n,...r?{reason:r}:{}}}function q(e,t,n){return{summary:wt(e,t,0,n),findings:[]}}function Qy(e){return e==="open"||e==="warn"||e==="info"}function NI(e){let t="det_number_collisions";if(!e.ok)return q(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return q(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return q(t,"not_applicable","no numbered namespaces");if(!kl(n))return q(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!Qy(o.status))continue;let{level:a,baseline:c}=vr(o.status);i.push({detector_id:t,rule_id:Cl,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:wt(t,"ran",i.length),findings:i}}function OI(e){let t="det_spec_drift";if(!e.ok)return q(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return q(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return q(t,"not_applicable",n.reason??"no opinion");if(!Ll(n))return q(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Qy(i.status))continue;let{level:o,baseline:a}=vr(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Ol(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:wt(t,"ran",r.length),findings:r}}function DI(e){let t="det_theme_class_drift";if(!e.ok)return q(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return q(t,"not_applicable","no theme tokens");if(!td(n))return q(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=vr(i.status);r.push({detector_id:t,rule_id:Il,level:o,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:wt(t,"ran",r.length),findings:r}}function PI(e){let t="det_table_acl_lint";if(!e.ok)return q(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return q(t,"not_applicable","no supabase migrations");if(!Zl(n))return q(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=vr(i.status);r.push({detector_id:t,rule_id:Nl,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:wt(t,"ran",r.length),findings:r}}function MI(e){let t="det_changelog_duplicates";if(!e.ok)return q(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return q(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return q(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,i.version],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function $I(e){let t="det_workflow_yaml";if(!e.ok)return q(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return q(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return q(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,String(i.line)],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function LI(e){let t="det_release_claims";if(!e.ok)return q(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?q(t,"ungraded",n.reason??"registry unreachable"):q(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function FI(e){let t="det_agent_doc_prose";if(!e.ok)return q(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?q(t,"ungraded",n.reason??"no base ref to grade against"):q(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:wt(t,"ran",r.length),findings:r}}function ad(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||vs[e.level]-vs[t.level]||Jy[e.baseline]-Jy[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Yy(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function jI(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Oi(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${o}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:sd(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:o,count:1})}else{let o=`${i.detector_id}|${i.rule_id}`,a=n.get(o);a?(a.evidence.push(...i.evidence),a.count+=1,vs[i.level]<vs[a.level]&&(a.level=i.level)):n.set(o,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:sd(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Oi(i.evidence),count:i.count});return r.sort(ad)}function HI(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 Me(e){let t={det_number_collisions:NI(e.number),det_spec_drift:OI(e.spec),det_theme_class_drift:DI(e.theme),det_table_acl_lint:PI(e.acl),det_changelog_duplicates:MI(e.changelog),det_workflow_yaml:$I(e.workflow),det_release_claims:LI(e.release),det_agent_doc_prose:FI(e.agentDoc)},n=qy.map(l=>t[l].summary),r=qy.flatMap(l=>t[l].findings),i=jI(r),o=[...i].sort((l,d)=>Yy(l)-Yy(d)||ad(l,d)).slice(0,Xy).sort(ad),a=i.length-o.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Oi(l.evidence),title:l.title}));return{findings:o,coverage:HI(n,a),engines:n,local:c,truncated:a}}function bt(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e},changelog:{ok:!1,error:e},workflow:{ok:!1,error:e},release:{ok:!1,error:e},agentDoc:{ok:!1,error:e}}}function ld(e){return e instanceof Error?e.message:String(e)}async function Ft(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:ld(t)}}}async function dd(e,t={}){let n={...Zy,...t.engines};try{if(!e_(e))return Me(bt("not a git work tree"));let r=await t_(e,n,t.baseRef),i=await cd(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Me({...r,number:i})}catch(r){return Me(bt(`detector adapter failed: ${ld(r)}`))}}async function ud(e,t={}){let n={...Zy,...t.engines};try{if(!e_(e)){let a=Me(bt("not a git work tree"));return{commit:a,local:a}}let r=await t_(e,n,t.baseRef),i=await cd(e,n,t.baseRef,"commit"),o=await cd(e,n,t.baseRef,"local");return{commit:Me({...r,number:i}),local:Me({...r,number:o})}}catch(r){let i=Me(bt(`detector adapter failed: ${ld(r)}`));return{commit:i,local:i}}}function e_(e){return I(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function t_(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Ft(()=>t.spec(e,r)),theme:await Ft(()=>t.theme(e,r)),acl:await Ft(()=>t.acl(e,r)),changelog:await Ft(()=>t.changelog(e,r)),workflow:await Ft(()=>t.workflow(e,r)),release:await Ft(()=>t.release(e,r)),agentDoc:await Ft(()=>t.agentDoc(e,r))}}function cd(e,t,n,r,i){let o=r==="local";return Ft(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:o,includeWorktrees:i??o}))}var Xy,Zy,qy,vs,Jy,pd=w(()=>{"use strict";be();Dl();Ii();Pi();Ul();Wl();ql();ys();bs();ws();Xy=64,Zy={number:s((e,t)=>En(e,t),"number"),spec:s((e,t)=>Rn(e,t),"spec"),theme:s((e,t)=>Cn(e,t),"theme"),acl:s((e,t)=>An(e,t),"acl"),changelog:s((e,t)=>Fl(e,t),"changelog"),workflow:s((e,t)=>zl(e,t),"workflow"),release:s((e,t)=>Hl(e,t),"release"),agentDoc:s((e,t)=>Gl(e,t),"agentDoc")},qy=["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(sd,"versionOf");s(wt,"summary");s(q,"noFindings");s(Qy,"isFindingStatus");s(NI,"adaptNumber");s(OI,"adaptSpec");s(DI,"adaptTheme");s(PI,"adaptAcl");s(MI,"adaptChangelog");s($I,"adaptWorkflow");s(LI,"adaptRelease");s(FI,"adaptAgentDoc");vs={open:0,warn:1,info:2},Jy={introduced:0,pre_existing:1};s(ad,"compareWire");s(Yy,"capPriority");s(jI,"buildWire");s(HI,"deriveCoverage");s(Me,"adaptDetectorReports");s(bt,"unavailableDetectorReports");s(ld,"errorText");s(Ft,"attempt");s(dd,"runRepoHealthDetectors");s(ud,"runRepoHealthDetectorScopes");s(e_,"insideWorkTree");s(t_,"runSharedEngines");s(cd,"runNumberEngine")});var n_,fd=w(()=>{"use strict";Vl();n_=[{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:Dy},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function r_(e){let t=new Set;for(let[n,r]of e.paths)for(let i of n_){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=UI(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function UI(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
42
|
+
`):t.readUntracked(e)}var i_=w(()=>{"use strict";fd();s(r_,"scanRiskFlags");s(UI,"contentForPath")});var jt,md,Ht,Sr,Li,xr,hd,ks,Ss,xs,gd,o_,Er=w(()=>{"use strict";jt="3",md=`
|
|
43
43
|
CREATE TABLE IF NOT EXISTS meta (
|
|
44
44
|
key TEXT PRIMARY KEY,
|
|
45
45
|
value TEXT NOT NULL
|
|
@@ -127,20 +127,20 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
127
127
|
vec BLOB NOT NULL,
|
|
128
128
|
content_hash TEXT NOT NULL
|
|
129
129
|
);
|
|
130
|
-
`,Ht="schema_version",xr="last_index_commit",Oi="last_indexed_at",Sr="edges_dirty",nd="resolve_config_fp",ys="embed_recipe_version",_s="embed_model",bs="embed_dim",rd="last_synced_at",Py="last_synced_commit"});function id(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 My(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of id(e.name))t.add(i);for(let i of id(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function $y(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of id(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var od=v(()=>{"use strict";s(id,"splitIdentifier");s(My,"buildSearchText");s($y,"toFtsMatchQuery")});import{readFileSync as Ly}from"node:fs";import{posix as Fy}from"node:path";function jy(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function Rn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function Hy(e){return e==="added"?0:e==="modified"?1:2}function WA(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Di,sd=v(()=>{"use strict";hi();Oh();Lc();Ph();Fh();jc();Wh();_e();tg();Yc();sl();Ei();Ql();Ai();Dy();Er();od();Di=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(Ht),i=await this.store.countFiles()>0;(t.full||i&&r!==jt)&&await this.wipe();let o=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(o.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let b=Vc(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=Yh(this.repoRoot);let c=new Set(a.map(b=>b.path)),l=new Map(o.map(b=>[b.path,b])),d=o.length>0&&!t.full,u={filesScanned:a.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},p=!1,f=s(async()=>{p||(p=!0,await this.store.setMeta(Sr,"1"))},"markEdgesDirty");for(let b of o)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of a){m++;let w=Zh(this.repoRoot,b.path);if(!w){u.filesSkipped++;continue}let S=l.get(b.path);if(S&&S.mtimeMs===w.mtimeMs&&S.size===w.size){u.filesSkipped++;continue}let A=this.readRepoFile(b.path);if(A===null){u.filesSkipped++;continue}let k=ts(A);if(S&&S.contentHash===k){await this.store.upsertFile({...S,mtimeMs:w.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let E=await this.parser.parse(b.path,A,b.language),P=new Map;for(let N of E.nodes)P.set(N.nodeKey,My(N));let x={path:b.path,language:b.language,contentHash:k,mtimeMs:w.mtimeMs,size:w.size,indexedAt:n};await f(),await this.store.replaceFileNodes(x,E.nodes,P,{contains:E.edges,refs:E.refs,imports:E.imports,exports:E.exports}),u.filesParsed++,t.onProgress?.({path:b.path,done:m,total:a.length})}let g=Mh(this.repoRoot),y=await this.store.getMeta(nd)!==g.fingerprint;if(p||y||await this.store.getMeta(Sr)==="1"){let b=Gh(await this.store.getNameIndex()),w=new gr(g.config,b.files),S=Kh(await this.store.getAllFacts(),b,w);await this.store.replaceCrossFileEdges(S),await this.store.setMeta(nd,g.fingerprint),await this.store.setMeta(Sr,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...$c]),w=await this.store.getEmbeddingContentHashes(),S=[];for(let k of b){let E=Nh(k),P=ts(`${this.embedder.recipeVersion}\0${E}`);w.get(k.nodeKey)!==P&&S.push({nodeKey:k.nodeKey,text:E,hash:P})}let A=64;for(let k=0;k<S.length;k+=A){let E=S.slice(k,k+A),P=await this.embedder.embedDocuments(E.map(N=>N.text));await this.store.upsertEmbeddings(E.map((N,D)=>({nodeKey:N.nodeKey,dim:this.embedder.dim,vec:P[D],contentHash:N.hash})));let x=Math.min(k+A,S.length);t.onProgress?.({path:"embedding symbols",done:x,total:S.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(ys,this.embedder.recipeVersion),await this.store.setMeta(_s,this.embedder.model),await this.store.setMeta(bs,String(this.embedder.dim))}await this.store.setMeta(Ht,jt),await this.store.setMeta(Oi,String(n));let _=vi(this.repoRoot);return _&&await this.store.setMeta(xr,_),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let o of n)r[o.language]=o.count;let i=await this.store.getMeta(Oi);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(xr),schemaVersion:await this.store.getMeta(Ht),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Rn(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...jy(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Rn(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Dh(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of a){let d=await this.store.getNode(l.nodeKey);d&&c.push({...jy(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Rn(n.maxDepth,3,5),o=Rn(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let f=[];for(let m of u){let g=await this.store.neighbors(m,r,a,o);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=o)return c;let b=r==="out"?y.dstKey:y.srcKey;d.has(b)||(d.add(b),f.push(b))}}u=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=Ly(Fy.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(Rn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Vc(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Rn(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=es(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(vi(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return ag(this.repoRoot,n,t)}async checkDivergence(t={}){return xi(this.repoRoot,t)}async checkNumberCollisions(t={}){return kn(this.repoRoot,t)}async checkNumberForPath(t,n={}){return xn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Sn(this.repoRoot,t)}async reviewDetectors(t={}){return Xl(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Zl(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=es(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=eg(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Oy({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,Qh),"readUntracked")}),c=Jh(n.keys()),l=Rn(t.limit,64,t.attest?Mt: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&&ts(y)!==g.contentHash;_&&(p++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",w=i.get(f.path);for(let S of m)d.push(WA(S,b,w,_))}return d.sort((f,m)=>Hy(f.change)-Hy(m.change)||(f.filePath<m.filePath?-1:f.filePath>m.filePath?1:0)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:vi(this.repoRoot),dirty:zc(this.repoRoot),baseSha:t.since?ns(this.repoRoot,t.since):null,mergeBaseSha:t.since?Wc(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 Ly(Fy.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(jy,"toHit");s(Rn,"clampLimit");s(Hy,"changeRank");s(WA,"classifyReviewSymbol")});var Uy=v(()=>{"use strict";_e()});var VA,fV,By=v(()=>{"use strict";_e();VA=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],fV=new RegExp(VA.join("|"),"g")});import{existsSync as ad,readdirSync as zA,readFileSync as qA}from"node:fs";import{spawnSync as JA}from"node:child_process";import{dirname as YA,join as vs,posix as cd}from"node:path";function Ky(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 ${ld} 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 ${ld} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,f=r!==null&&r.ok===!1?r.detail:void 0,g={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(yt);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!o.has(p)).sort(yt),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(yt),m=e.remote.versions.filter(g=>!o.has(g)).sort(yt);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 Wy(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function zy(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
|
|
131
|
-
`).filter(Boolean).slice(-1)[0]}}function
|
|
132
|
-
`).map(i=>i.trim()).filter(Boolean)}}function
|
|
133
|
-
`)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!
|
|
134
|
-
|
|
135
|
-
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function
|
|
136
|
-
`,{encoding:"utf8",mode:384});try{
|
|
137
|
-
`,{encoding:"utf8",mode:384});try{
|
|
138
|
-
`,{encoding:"utf8",mode:384}),KI(a,o)}catch{}}function y_(e=Ke()){try{let t=JSON.parse(GI(g_(e),"utf8"));return t.v!==1||typeof t.at!="string"||!zI.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 zI,qI,JI,Ad=v(()=>{"use strict";se();zI=["ok","paired","auth_failed","not_paired"],qI="connection-state.json",JI=200;s(g_,"connectionStatePath");s(YI,"redactDetail");s(In,"writeConnectionState");s(y_,"readConnectionState")});var K,We=v(()=>{"use strict";K="0.97.0"});import{execFileSync as __}from"node:child_process";import{createHash as XI}from"node:crypto";function ZI(e){return XI("sha256").update(e).digest("hex")}function QI(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function Nr(e){let t=QI(e);return t?ZI(t):null}function Y(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&eN.test(e))return e;let t;try{t=__("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Nr(t):null}function Pe(e){let t;try{t=__("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Nr(t):null}var eN,be=v(()=>{"use strict";s(ZI,"sha256Hex");s(QI,"normalizeRemoteUrl");s(Nr,"projectKeyFromRemote");eN=/^[a-f0-9]{64}$/;s(Y,"computeProjectKey");s(Pe,"projectKeyForRepo")});import tN from"node:path";import{fileURLToPath as nN}from"node:url";function rN(e,t=tN.sep){return e.split(t).includes("_npx")}function ke(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",v_,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):rN(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function he(){try{let e=nN(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function it(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${b_(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:b_(n)).join(" ")}function Or(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(v_)}function Is(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function b_(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var v_,Gt=v(()=>{"use strict";v_="@maind-dev/mcp-bridge";s(rN,"isEphemeralEntry");s(ke,"resolveBridgeLaunch");s(he,"currentBridgeEntry");s(it,"launchToShellCommand");s(Or,"isNpxForm");s(Is,"isLegacyHookForm");s(b_,"shellQuote")});import*as F from"node:path";function x_(e){let t=e.launch??ke({entryPath:he(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}function E_(e){return Ps(e,"Claude")}function oN(e){return F.join(E_(e),S_)}function Ps(e,t){switch(e.platform){case"darwin":return F.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??F.join(e.homeDir,"AppData","Roaming");return F.join(n,t)}default:{let n=e.xdgConfigHome??F.join(e.homeDir,".config");return F.join(n,t)}}}function sN(e){return F.join(Ps(e,"Code"),"User")}function Os(e,t,n=[]){return{kind:"foreign-entries",dir:Ps(e,t),ours:["User",...n]}}function w_(e){return e.localAppData??F.join(e.homeDir,"AppData","Local")}function cN(e){let t=[{kind:"foreign-entries",dir:E_(e),ours:[S_]}];return e.platform==="darwin"?t.push({kind:"dir",path:F.join("/Applications","Claude.app")},{kind:"dir",path:F.join(e.homeDir,"Applications","Claude.app")}):e.platform==="win32"&&t.push({kind:"dir",path:F.join(w_(e),"AnthropicClaude")},{kind:"dir",path:F.join(w_(e),"Packages",aN)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Nn(e){return{evidence:[Os(e,"Cursor"),{kind:"foreign-entries",dir:F.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function T_(e){if(e.platform==="win32"){let t=e.appData??F.join(e.homeDir,"AppData","Roaming");return F.join(t,"devin")}return F.join(e.xdgConfigHome??F.join(e.homeDir,".config"),"devin")}function lN(e){return F.join(T_(e),"mcp_config.json")}function R_(e){return F.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function Ds(e){let t=[Os(e,"Devin",["mcp_config.json"]),{kind:"dir",path:F.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:T_(e),ours:["mcp_config.json"]}),t.push(Os(e,"Windsurf"),{kind:"foreign-entries",dir:F.dirname(R_(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 mN(e){return e===null?null:fN.exec(e)?.[1]??null}function A_(e,t){let n=C_.map(r=>F.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push(F.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of pN)for(let i of["/Applications",F.join(e.homeDir,"Applications")])n.push(F.join(i,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function I_(e){return e.clineDataDir?e.clineDataDir:F.join(e.clineDir??F.join(e.homeDir,".cline"),"data")}function hN(e){return e.clineMcpSettingsPath??F.join(I_(e),"settings","cline_mcp_settings.json")}function gN(e){return{evidence:[{kind:"foreign-entries",dir:I_(e),ours:["settings"]},...dN.map(t=>({kind:"dir",path:F.join(Ps(e,t),"User","globalStorage",k_)})),...A_(e,k_)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function N_(e){return e.continueGlobalDir??F.join(e.homeDir,".continue")}function yN(e){return F.join(N_(e),"mcpServers","maind.json")}function _N(e){return{evidence:[{kind:"foreign-entries",dir:N_(e),ours:["mcpServers"]},...A_(e,uN)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function O_(e){return e.codexHome??F.join(e.homeDir,".codex")}function bN(e){return F.join(O_(e),"config.toml")}function vN(e){let t=O_(e),n=F.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 wN(e){return F.join(sN(e),"mcp.json")}function Hi(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:F.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:F.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:oN(e),kind:"json",presence:cN(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:F.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Nn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:lN(e),kind:"json",presence:Ds(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:R_(e),kind:"json",presence:Ds(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:wN(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{evidence:[Os(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:hN(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:gN(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:yN(e),kind:"json",presence:_N(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:bN(e),kind:"toml",presence:vN(e)}]}function D_(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function P_(e){return e.jsonShape??iN}function Ui(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Ns(e.env.XDG_CONFIG_HOME),appData:Ns(e.env.APPDATA),localAppData:Ns(e.env.LOCALAPPDATA),clineDir:ji(e.env.CLINE_DIR),clineDataDir:ji(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:ji(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:ji(e.env.CONTINUE_GLOBAL_DIR),codexHome:ji(e.env.CODEX_HOME),bundleAppRoot:mN(e.bridgeEntry??null)}}function Ns(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ji(e){let t=Ns(e);return t!==null&&F.isAbsolute(t)?t:null}var iN,S_,aN,C_,dN,k_,uN,pN,fN,Id,On=v(()=>{"use strict";Gt();iN={serversKey:"mcpServers"};s(x_,"buildMaindServerEntry");S_="claude_desktop_config.json";s(E_,"claudeDesktopAppDataDir");s(oN,"claudeDesktopConfigPath");s(Ps,"editorAppDataDir");s(sN,"vsCodeUserDir");s(Os,"editorRan");s(w_,"localAppDataDir");aN="Claude_pzs8sxrjxfjjc";s(cN,"claudeDesktopPresence");s(Nn,"cursorPresence");s(T_,"devinConfigDir");s(lN,"devinMcpConfigPath");s(R_,"windsurfLegacyMcpConfigPath");s(Ds,"devinDesktopPresence");C_=[{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"}],dN=C_.map(e=>e.appData),k_="saoudrizwan.claude-dev",uN="continue.continue",pN=["AgentComposer"],fN=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(mN,"bundleAppRootOf");s(A_,"agentExtensionEvidence");s(I_,"clineDataDir");s(hN,"clineMcpSettingsPath");s(gN,"clinePresence");s(N_,"continueGlobalDir");s(yN,"continueMcpConfigPath");s(_N,"continuePresence");s(O_,"codexHomeDir");s(bN,"codexConfigPath");s(vN,"codexPresence");s(wN,"vsCodeUserMcpPath");s(Hi,"getClientTargets");s(D_,"filterTargetsByFamily");s(P_,"jsonShapeOf");Id=[...new Set(Hi({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(Ui,"makeDefaultContext");s(Ns,"nonEmpty");s(ji,"absoluteOrNull")});import*as L_ from"node:fs/promises";import*as Kt from"node:path";import*as F_ from"node:readline";async function j_(e){let t=Kt.resolve(e),n=t;for(;;){if(await H_(n))return n;let r=Kt.dirname(n);if(r===n)return t;n=r}}async function $s(e){let n=Kt.resolve(e),r=[];for(;;){await H_(n)&&r.push(n);let i=Kt.dirname(n);if(i===n)break;n=i}return r}async function H_(e){for(let t of xN)try{return await L_.access(Kt.join(e,t)),!0}catch{}return!1}async function U_(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
130
|
+
`,Ht="schema_version",Sr="last_index_commit",Li="last_indexed_at",xr="edges_dirty",hd="resolve_config_fp",ks="embed_recipe_version",Ss="embed_model",xs="embed_dim",gd="last_synced_at",o_="last_synced_commit"});function yd(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 s_(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of yd(e.name))t.add(i);for(let i of yd(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function a_(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of yd(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var _d=w(()=>{"use strict";s(yd,"splitIdentifier");s(s_,"buildSearchText");s(a_,"toFtsMatchQuery")});import{readFileSync as c_}from"node:fs";import{posix as l_}from"node:path";function d_(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 In(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function u_(e){return e==="added"?0:e==="modified"?1:2}function BI(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Fi,bd=w(()=>{"use strict";wi();rg();Yc();og();lg();Zc();gg();be();Tg();ll();bl();Ii();pd();Pi();i_();Er();_d();Fi=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(Ht),i=await this.store.countFiles()>0;(t.full||i&&r!==jt)&&await this.wipe();let o=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(o.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let b=ol(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=vg(this.repoRoot);let c=new Set(a.map(b=>b.path)),l=new Map(o.map(b=>[b.path,b])),d=o.length>0&&!t.full,u={filesScanned:a.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},p=!1,f=s(async()=>{p||(p=!0,await this.store.setMeta(xr,"1"))},"markEdgesDirty");for(let b of o)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of a){m++;let v=Sg(this.repoRoot,b.path);if(!v){u.filesSkipped++;continue}let x=l.get(b.path);if(x&&x.mtimeMs===v.mtimeMs&&x.size===v.size){u.filesSkipped++;continue}let C=this.readRepoFile(b.path);if(C===null){u.filesSkipped++;continue}let k=ss(C);if(x&&x.contentHash===k){await this.store.upsertFile({...x,mtimeMs:v.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let E=await this.parser.parse(b.path,C,b.language),P=new Map;for(let N of E.nodes)P.set(N.nodeKey,s_(N));let S={path:b.path,language:b.language,contentHash:k,mtimeMs:v.mtimeMs,size:v.size,indexedAt:n};await f(),await this.store.replaceFileNodes(S,E.nodes,P,{contains:E.edges,refs:E.refs,imports:E.imports,exports:E.exports}),u.filesParsed++,t.onProgress?.({path:b.path,done:m,total:a.length})}let g=sg(this.repoRoot),y=await this.store.getMeta(hd)!==g.fingerprint;if(p||y||await this.store.getMeta(xr)==="1"){let b=mg(await this.store.getNameIndex()),v=new gr(g.config,b.files),x=hg(await this.store.getAllFacts(),b,v);await this.store.replaceCrossFileEdges(x),await this.store.setMeta(hd,g.fingerprint),await this.store.setMeta(xr,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...Jc]),v=await this.store.getEmbeddingContentHashes(),x=[];for(let k of b){let E=ng(k),P=ss(`${this.embedder.recipeVersion}\0${E}`);v.get(k.nodeKey)!==P&&x.push({nodeKey:k.nodeKey,text:E,hash:P})}let C=64;for(let k=0;k<x.length;k+=C){let E=x.slice(k,k+C),P=await this.embedder.embedDocuments(E.map(N=>N.text));await this.store.upsertEmbeddings(E.map((N,D)=>({nodeKey:N.nodeKey,dim:this.embedder.dim,vec:P[D],contentHash:N.hash})));let S=Math.min(k+C,x.length);t.onProgress?.({path:"embedding symbols",done:S,total:x.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(ks,this.embedder.recipeVersion),await this.store.setMeta(Ss,this.embedder.model),await this.store.setMeta(xs,String(this.embedder.dim))}await this.store.setMeta(Ht,jt),await this.store.setMeta(Li,String(n));let _=Ei(this.repoRoot);return _&&await this.store.setMeta(Sr,_),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let o of n)r[o.language]=o.count;let i=await this.store.getMeta(Li);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(Sr),schemaVersion:await this.store.getMeta(Ht),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=In(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...d_(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=In(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:ig(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of a){let d=await this.store.getNode(l.nodeKey);d&&c.push({...d_(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=In(n.maxDepth,3,5),o=In(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let f=[];for(let m of u){let g=await this.store.neighbors(m,r,a,o);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=o)return c;let b=r==="out"?y.dstKey:y.srcKey;d.has(b)||(d.add(b),f.push(b))}}u=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=c_(l_.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(In(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=ol(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=In(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=os(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(Ei(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Og(this.repoRoot,n,t)}async checkDivergence(t={}){return Ai(this.repoRoot,t)}async checkNumberCollisions(t={}){return En(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Tn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Rn(this.repoRoot,t)}async reviewDetectors(t={}){return dd(this.repoRoot,t)}async reviewDetectorScopes(t={}){return ud(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=os(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Eg(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=r_({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,xg),"readUntracked")}),c=wg(n.keys()),l=In(t.limit,64,t.attest?Mt: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&&ss(y)!==g.contentHash;_&&(p++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",v=i.get(f.path);for(let x of m)d.push(BI(x,b,v,_))}return d.sort((f,m)=>u_(f.change)-u_(m.change)||(f.filePath<m.filePath?-1:f.filePath>m.filePath?1:0)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:Ei(this.repoRoot),dirty:sl(this.repoRoot),baseSha:t.since?as(this.repoRoot,t.since):null,mergeBaseSha:t.since?il(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 c_(l_.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(d_,"toHit");s(In,"clampLimit");s(u_,"changeRank");s(BI,"classifyReviewSymbol")});var p_=w(()=>{"use strict";be()});var KI,vz,f_=w(()=>{"use strict";be();KI=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],vz=new RegExp(KI.join("|"),"g")});import{existsSync as wd,readdirSync as GI,readFileSync as WI}from"node:fs";import{spawnSync as VI}from"node:child_process";import{dirname as zI,join as Es,posix as vd}from"node:path";function h_(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 ${kd} 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 ${kd} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,f=r!==null&&r.ok===!1?r.detail:void 0,g={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(gt);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!o.has(p)).sort(gt),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(gt),m=e.remote.versions.filter(g=>!o.has(g)).sort(gt);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function g_(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function __(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
|
|
131
|
+
`).filter(Boolean).slice(-1)[0]}}function m_(e,t,n){let r=e(t,qI,n);return r.ok===!1?__(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
132
|
+
`).map(i=>i.trim()).filter(Boolean)}}function b_(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 JI(e){let t=I(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=zI(t);return n===e?null:n}function YI(e,t,n){let r=vd.dirname(t),o=[{path:Es(e,r,"config.toml"),source:"worktree"}],a=JI(e);a&&o.push({path:Es(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(wd(c.path))try{let l=b_(WI(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 XI(e,t){let n=new Map,r=I(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=I(e,["rev-parse","--show-toplevel"])?.trim();for(let o of r.split(`
|
|
133
|
+
`)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!wd(a))continue;let c=Es(a,t);if(wd(c))try{for(let l of GI(c)){let d=_r(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function Sd(e,t={}){let n=t.runPsql??y_,r=t.timeoutMs??15e3,i=[],o=xn(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let p of o){let f=YI(e,p.dir,i),m=f.source==="missing"?null:m_(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?m_(n,t.remoteDbUrl,r):null,y=h_({dir:p.dir,projectRoot:Es(e,vd.dirname(vd.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:XI(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=g_(l),u={open:0,warn:1,info:2};return a.sort((p,f)=>u[p.status]-u[f.status]||p.id.localeCompare(f.id)),{ok:d==="in_sync",verdict:d,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var kd,y_,qI,w_=w(()=>{"use strict";be();Ri();kd=54322;s(h_,"evaluateLedgerProject");s(g_,"deriveLedgerVerdict");y_=s((e,t,n)=>{let r=VI("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"),qI="select version from supabase_migrations.schema_migrations order by version";s(__,"classifyLedgerError");s(m_,"readLedger");s(b_,"parseDbPort");s(JI,"mainWorktreeRoot");s(YI,"resolveConfig");s(XI,"gatherSiblingVersions");s(Sd,"checkMigrationLedgerDrift")});function $e(e){return typeof e=="string"?e:String(e??"")}function ji(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function xd(e){return{nodeKey:$e(e.node_key),kind:$e(e.kind),name:$e(e.name),qualifiedName:$e(e.qualified_name),filePath:$e(e.file_path),startLine:ji(e.start_line),endLine:ji(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function S_(e){return{path:$e(e.path),language:$e(e.language),contentHash:$e(e.content_hash),mtimeMs:ji(e.mtime_ms),size:ji(e.size),indexedAt:ji(e.indexed_at)}}function Ed(e){let t=new Map,n=s(i=>{let o=t.get(i);return o===void 0&&(o=e.prepare(i),t.set(i,o)),o},"stmt"),r=s(i=>{let o=n(Ut.meta).get(i);return o===void 0?null:$e(o.value)},"metaValue");return{meta(){let i=r(Ht),o=r(Li);return{schemaVersion:i,schemaCurrent:i===jt,edgesDirty:r(xr)==="1",lastIndexedAt:o===null?null:Number(o)}},file(i){let o=n(Ut.file).get(i);return o===void 0?null:S_(o)},files(i){let o=new Map;for(let a of new Set(i)){let c=n(Ut.file).get(a);c!==void 0&&o.set(a,S_(c))}return o},symbolsInFile(i,o=ZI){return n(Ut.symbolsInFile).all(i,o).map(xd)},symbolsNamed(i,o=QI){let a=new Map;for(let c of new Set(i)){let l=n(Ut.symbolsNamed).all(c,o);l.length>0&&a.set(c,l.map(xd))}return a},callersOfFile(i,o=eN){return n(Ut.callersOfFile).all(i,i,o).map(c=>({calleeKey:$e(c.callee_key),kind:$e(c.edge_kind),caller:xd(c)}))},importersOf(i,o=tN){let a=n(Ut.importersOf).all(tt(i),o),c=[];for(let l of a){let d=$e(l.src_key),u=d.endsWith(k_)?d.slice(0,-k_.length):d;u!==i&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function Hi(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var v_,Ut,ZI,QI,eN,tN,k_,Td=w(()=>{"use strict";Sn();Er();v_="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",Ut={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 ${v_} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${v_} 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 ?"},ZI=400,QI=8,eN=600,tN=200,k_="#<module>";s($e,"str");s(ji,"num");s(xd,"toSymbol");s(S_,"toFileRow");s(Ed,"createIndexReader");s(Hi,"isFileCurrent")});var Rd,Ad=w(()=>{"use strict";Rd="0.2.0"});function Cd(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:Mt,attest:!0}}function Id(e,t){let n=0,r=[];for(let o of e.symbols){let a=o.qualifiedName?o.qualifiedName:void 0;if(o.name.length===0||o.name.length>Ts||a!==void 0&&a.length>Rs){n+=1;continue}r.push({name:o.name,...a!==void 0?{qualified_name:a}:{},...o.kind&&o.kind.length<=E_?{kind:o.kind}:{},...o.language&&o.language.length<=T_?{language:o.language}:{},change:o.change,changed_line_count:Math.min(Math.max(0,o.changedLineCount),R_)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(o=>({detector_id:o.detector_id,detector_version:o.detector_version,state:o.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Rd},dropped:n}}function Nd(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 Od(e,t,n){let r=t,i=[];r===0?i.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):i.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&i.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&i.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let o=e.changedFiles-e.indexedFiles;return o>0&&i.push(`${o} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&i.push(`Symbol list truncated at ${Mt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&i.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),i.join(" ")}function Dd(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===x_&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===x_?{kind:"invalid_params",code:n,detail:r,issues:nN(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function nN(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 Pd(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 Ts,Rs,E_,T_,R_,x_,rN,A_=w(()=>{"use strict";wi();Ad();Ts=200,Rs=512,E_=64,T_=32,R_=1e4;s(Cd,"attestReviewOptions");s(Id,"buildAttestPayload");s(Nd,"attestPersistDecision");s(Od,"attestCoverageNote");x_=-32602;s(Dd,"classifyMcpErrorText");s(nN,"parseIssues");s(Pd,"isLegacyAttestRejection");rN=`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 Bt=w(()=>{"use strict";Jf();bd();ll();fd();be();ys();ql();Ul();Wl();bl();p_();f_();fl();Ii();ws();Pi();Ri();bs();w_();Dl();pd();Ii();Pi();ws();bs();ts();Yc();Er();Td();rs();Ad();A_()});import{execFileSync as iN}from"node:child_process";import{createHash as oN}from"node:crypto";import{mkdirSync as sN,readFileSync as aN,renameSync as cN,writeFileSync as lN}from"node:fs";import{dirname as C_,join as I_}from"node:path";function We(e=process.cwd()){try{let t=iN("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function Tr(e){return oN("sha256").update(e).digest("hex").slice(0,16)}function As(e){return I_(e,dN)}function N_(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function O_(e,t,n,r=new Date().toISOString()){try{if(!N_(n))return;let i={version:Md,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=As(e);sN(C_(o),{recursive:!0}),xi(C_(o));let a=`${o}.${process.pid}.tmp`;lN(a,JSON.stringify(i,null,2),"utf8"),cN(a,o)}catch{}}function Cs(e,t){try{let n=aN(As(e),"utf8"),r=JSON.parse(n);return r.version!==Md||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!N_(r.result)?null:{version:Md,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function D_(e,t,n=new Date){let r=uN(t.cached_at,n),i=t.result.instructions??"",o={...t.result,instructions:`${r}
|
|
134
|
+
|
|
135
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function uN(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${pN(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function pN(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let a=Math.floor(o/24);return`${a} day${a===1?"":"s"} ago`}var Md,dN,vt=w(()=>{"use strict";Bt();Md=1,dN=I_(".maind","conventions-cache.json");s(We,"resolveRepoRoot");s(Tr,"keyFingerprint");s(As,"cachePath");s(N_,"hasInstructions");s(O_,"writeConventionsCache");s(Cs,"readConventionsCache");s(D_,"buildCachedInitializeResponse");s(uN,"fallbackMarker");s(pN,"relativeAge")});import{existsSync as Ds,mkdirSync as SN,readFileSync as $_,writeFileSync as Hd,chmodSync as L_}from"node:fs";import{homedir as xN,hostname as EN,platform as jd,release as TN}from"node:os";import{randomUUID as RN}from"node:crypto";import{join as Nn}from"node:path";function Ve(){let e=xN(),t=process.env;if(jd()==="darwin")return Nn(e,"Library","Application Support","maind");if(jd()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Nn(e,"AppData","Roaming");return Nn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Nn(e,".config");return Nn(n,"maind")}function F_(e){Ds(e)||SN(e,{recursive:!0,mode:448})}function ne(){let e=Ve();F_(e);let t=Nn(e,AN);if(Ds(t)){let r=$_(t,"utf8").trim();if(NN(r))return r}let n=RN();Hd(t,n+`
|
|
136
|
+
`,{encoding:"utf8",mode:384});try{L_(t,384)}catch{}return n}function NN(e){return IN.test(e)}function Ud(){return Nn(Ve(),CN)}function On(e){let t=Ve();F_(t);let n=Ud();Hd(n,e+`
|
|
137
|
+
`,{encoding:"utf8",mode:384});try{L_(n,384)}catch{}}function z(){let e=Ud();if(!Ds(e))return null;let t=$_(e,"utf8").trim();return t.length>0?t:null}function Bi(){let e=Ud();Ds(e)&&Hd(e,"",{encoding:"utf8",mode:384})}function j_(){try{return`mcp-bridge-${EN()}`}catch{return"mcp-bridge"}}function Ps(e){return{os:`${jd()} ${TN()}`,ide:"mcp-bridge",ext_version:e,device_id:ne()}}var AN,CN,IN,ie=w(()=>{"use strict";s(Ve,"configDir");s(F_,"ensureDir");AN="device-id",CN="api-key";s(ne,"ensureDeviceId");IN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(NN,"isUuid");s(Ud,"apiKeyPath");s(On,"writeApiKey");s(z,"readApiKey");s(Bi,"clearApiKey");s(j_,"bridgeLabel");s(Ps,"clientMeta")});function Ki(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:ON}function Ar(e){return`${Ki()}/${e.replace(/^\/+/,"")}`}var ON,Cr=w(()=>{"use strict";ON="https://fn.maind.dev/functions/v1";s(Ki,"functionsOrigin");s(Ar,"functionsUrl")});import{mkdirSync as jN,readFileSync as HN,renameSync as UN,writeFileSync as BN}from"node:fs";import{join as KN}from"node:path";function U_(e=Ve()){return KN(e,WN)}function zN(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,VN)}function Dn(e,t,n){try{let r=n.dir??Ve();jN(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:zN(t),bridge_version:n.version},o=U_(r),a=`${o}.${process.pid}.tmp`;BN(a,JSON.stringify(i)+`
|
|
138
|
+
`,{encoding:"utf8",mode:384}),UN(a,o)}catch{}}function B_(e=Ve()){try{let t=JSON.parse(HN(U_(e),"utf8"));return t.v!==1||typeof t.at!="string"||!GN.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 GN,WN,VN,Bd=w(()=>{"use strict";ie();GN=["ok","paired","auth_failed","not_paired"],WN="connection-state.json",VN=200;s(U_,"connectionStatePath");s(zN,"redactDetail");s(Dn,"writeConnectionState");s(B_,"readConnectionState")});var U,ze=w(()=>{"use strict";U="0.98.0"});import{execFileSync as K_}from"node:child_process";import{createHash as qN}from"node:crypto";function JN(e){return qN("sha256").update(e).digest("hex")}function YN(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function Nr(e){let t=YN(e);return t?JN(t):null}function te(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&XN.test(e))return e;let t;try{t=K_("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Nr(t):null}function Le(e){let t;try{t=K_("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Nr(t):null}var XN,he=w(()=>{"use strict";s(JN,"sha256Hex");s(YN,"normalizeRemoteUrl");s(Nr,"projectKeyFromRemote");XN=/^[a-f0-9]{64}$/;s(te,"computeProjectKey");s(Le,"projectKeyForRepo")});import ZN from"node:path";import{fileURLToPath as QN}from"node:url";function eO(e,t=ZN.sep){return e.split(t).includes("_npx")}function xe(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",W_,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):eO(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 ge(){try{let e=QN(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function it(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${G_(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:G_(n)).join(" ")}function Or(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(W_)}function Ms(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function G_(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var W_,Kt=w(()=>{"use strict";W_="@maind-dev/mcp-bridge";s(eO,"isEphemeralEntry");s(xe,"resolveBridgeLaunch");s(ge,"currentBridgeEntry");s(it,"launchToShellCommand");s(Or,"isNpxForm");s(Ms,"isLegacyHookForm");s(G_,"shellQuote")});import*as F from"node:path";function q_(e){let t=e.launch??xe({entryPath:ge(),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 Y_(e){return js(e,"Claude")}function nO(e){return F.join(Y_(e),J_)}function js(e,t){switch(e.platform){case"darwin":return F.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??F.join(e.homeDir,"AppData","Roaming");return F.join(n,t)}default:{let n=e.xdgConfigHome??F.join(e.homeDir,".config");return F.join(n,t)}}}function rO(e){return F.join(js(e,"Code"),"User")}function Ls(e,t,n=[]){return{kind:"foreign-entries",dir:js(e,t),ours:["User",...n]}}function V_(e){return e.localAppData??F.join(e.homeDir,"AppData","Local")}function oO(e){let t=[{kind:"foreign-entries",dir:Y_(e),ours:[J_]}];return e.platform==="darwin"?t.push({kind:"dir",path:F.join("/Applications","Claude.app")},{kind:"dir",path:F.join(e.homeDir,"Applications","Claude.app")}):e.platform==="win32"&&t.push({kind:"dir",path:F.join(V_(e),"AnthropicClaude")},{kind:"dir",path:F.join(V_(e),"Packages",iO)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Pn(e){return{evidence:[Ls(e,"Cursor"),{kind:"foreign-entries",dir:F.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function X_(e){if(e.platform==="win32"){let t=e.appData??F.join(e.homeDir,"AppData","Roaming");return F.join(t,"devin")}return F.join(e.xdgConfigHome??F.join(e.homeDir,".config"),"devin")}function sO(e){return F.join(X_(e),"mcp_config.json")}function Z_(e){return F.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function Fs(e){let t=[Ls(e,"Devin",["mcp_config.json"]),{kind:"dir",path:F.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:X_(e),ours:["mcp_config.json"]}),t.push(Ls(e,"Windsurf"),{kind:"foreign-entries",dir:F.dirname(Z_(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 uO(e){return e===null?null:dO.exec(e)?.[1]??null}function eb(e,t){let n=Q_.map(r=>F.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push(F.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of lO)for(let i of["/Applications",F.join(e.homeDir,"Applications")])n.push(F.join(i,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function tb(e){return e.clineDataDir?e.clineDataDir:F.join(e.clineDir??F.join(e.homeDir,".cline"),"data")}function pO(e){return e.clineMcpSettingsPath??F.join(tb(e),"settings","cline_mcp_settings.json")}function fO(e){return{evidence:[{kind:"foreign-entries",dir:tb(e),ours:["settings"]},...aO.map(t=>({kind:"dir",path:F.join(js(e,t),"User","globalStorage",z_)})),...eb(e,z_)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function nb(e){return e.continueGlobalDir??F.join(e.homeDir,".continue")}function mO(e){return F.join(nb(e),"mcpServers","maind.json")}function hO(e){return{evidence:[{kind:"foreign-entries",dir:nb(e),ours:["mcpServers"]},...eb(e,cO)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function rb(e){return e.codexHome??F.join(e.homeDir,".codex")}function gO(e){return F.join(rb(e),"config.toml")}function yO(e){let t=rb(e),n=F.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 _O(e){return F.join(rO(e),"mcp.json")}function Wi(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:F.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:F.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:nO(e),kind:"json",presence:oO(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:F.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Pn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:sO(e),kind:"json",presence:Fs(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:Z_(e),kind:"json",presence:Fs(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:_O(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{evidence:[Ls(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:pO(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:fO(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:mO(e),kind:"json",presence:hO(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:gO(e),kind:"toml",presence:yO(e)}]}function ib(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function ob(e){return e.jsonShape??tO}function Vi(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:$s(e.env.XDG_CONFIG_HOME),appData:$s(e.env.APPDATA),localAppData:$s(e.env.LOCALAPPDATA),clineDir:Gi(e.env.CLINE_DIR),clineDataDir:Gi(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:Gi(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:Gi(e.env.CONTINUE_GLOBAL_DIR),codexHome:Gi(e.env.CODEX_HOME),bundleAppRoot:uO(e.bridgeEntry??null)}}function $s(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Gi(e){let t=$s(e);return t!==null&&F.isAbsolute(t)?t:null}var tO,J_,iO,Q_,aO,z_,cO,lO,dO,Kd,Mn=w(()=>{"use strict";Kt();tO={serversKey:"mcpServers"};s(q_,"buildMaindServerEntry");J_="claude_desktop_config.json";s(Y_,"claudeDesktopAppDataDir");s(nO,"claudeDesktopConfigPath");s(js,"editorAppDataDir");s(rO,"vsCodeUserDir");s(Ls,"editorRan");s(V_,"localAppDataDir");iO="Claude_pzs8sxrjxfjjc";s(oO,"claudeDesktopPresence");s(Pn,"cursorPresence");s(X_,"devinConfigDir");s(sO,"devinMcpConfigPath");s(Z_,"windsurfLegacyMcpConfigPath");s(Fs,"devinDesktopPresence");Q_=[{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"}],aO=Q_.map(e=>e.appData),z_="saoudrizwan.claude-dev",cO="continue.continue",lO=["AgentComposer"],dO=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(uO,"bundleAppRootOf");s(eb,"agentExtensionEvidence");s(tb,"clineDataDir");s(pO,"clineMcpSettingsPath");s(fO,"clinePresence");s(nb,"continueGlobalDir");s(mO,"continueMcpConfigPath");s(hO,"continuePresence");s(rb,"codexHomeDir");s(gO,"codexConfigPath");s(yO,"codexPresence");s(_O,"vsCodeUserMcpPath");s(Wi,"getClientTargets");s(ib,"filterTargetsByFamily");s(ob,"jsonShapeOf");Kd=[...new Set(Wi({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(Vi,"makeDefaultContext");s($s,"nonEmpty");s(Gi,"absoluteOrNull")});import*as cb from"node:fs/promises";import*as Gt from"node:path";import*as lb from"node:readline";async function db(e){let t=Gt.resolve(e),n=t;for(;;){if(await ub(n))return n;let r=Gt.dirname(n);if(r===n)return t;n=r}}async function Us(e){let n=Gt.resolve(e),r=[];for(;;){await ub(n)&&r.push(n);let i=Gt.dirname(n);if(i===n)break;n=i}return r}async function ub(e){for(let t of wO)try{return await cb.access(Gt.join(e,t)),!0}catch{}return!1}async function pb(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
139
139
|
Multiple project roots found between cwd and the filesystem root:
|
|
140
140
|
`),e.forEach((o,a)=>{process.stdout.write(` [${a+1}] ${o}
|
|
141
141
|
`)}),process.stdout.write(`
|
|
142
|
-
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=
|
|
143
|
-
`),null):e[i-1]}var
|
|
142
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=lb.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(o=>{n.question("",a=>o(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
|
|
143
|
+
`),null):e[i-1]}var wO,Wd=w(()=>{"use strict";wO=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];s(db,"detectProjectRoot");s(Us,"findAllProjectRoots");s(ub,"hasAnyMarker");s(pb,"disambiguateProjectRoot")});import{existsSync as vO,readdirSync as kO}from"node:fs";import*as ae from"node:fs/promises";import*as Bs from"node:path";async function Y(e){try{return await ae.readFile(e,"utf8")}catch(t){if(SO(t))return null;throw t}}async function Vd(e){await ae.mkdir(e,{recursive:!0})}async function V(e,t,n){let r=Bs.dirname(e);await Vd(r);let i=Bs.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await ae.writeFile(i,t,{encoding:"utf8",mode:n});try{await ae.rename(i,e)}catch(o){if(xO(o))try{await ae.copyFile(i,e),await ae.unlink(i).catch(()=>{}),n!==void 0&&await ae.chmod(e,n).catch(()=>{});return}catch(a){throw await ae.unlink(i).catch(()=>{}),a}throw await ae.unlink(i).catch(()=>{}),o}}async function fb(e,t){let n=await Y(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function SO(e){return mb(e)&&e.code==="ENOENT"}function xO(e){return!mb(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function mb(e){return typeof e=="object"&&e!==null&&"code"in e}var Wt,we=w(()=>{"use strict";Wt={exists:s(e=>vO(e),"exists"),readdir:s(e=>{try{return kO(e)}catch{return null}},"readdir")};s(Y,"readFileSafe");s(Vd,"ensureDir");s(V,"atomicWriteFile");s(fb,"hasLinePrefix");s(SO,"isNoEnt");s(xO,"isWindowsRenameFailure");s(mb,"isNodeError")});function EO(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function TO(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(`${r}-`)}function RO(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=>TO(r,e.id)):n.some(r=>!EO(r)&&!e.ours.includes(r))}function Dr(e,t){return e.evidence.some(n=>RO(n,t))}function hb(e,t){return Dr(Pn(e),t)}function gb(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||Dr(t.presence,r))return null;let i=r.exists(t.path);return{target:t.key,action:"merge",status:"skipped",detail:i?`${t.presence.skipDetail}; leftover file: maind-mcp-bridge doctor --remove-phantoms`:t.presence.skipDetail}}var Ks=w(()=>{"use strict";Mn();s(EO,"isNoise");s(TO,"isExtensionFolder");s(RO,"evidenceHolds");s(Dr,"clientPresent");s(hb,"cursorInstalled");s(gb,"presenceSkipRow")});function BO(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 KO(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
144
144
|
|
|
145
145
|
- My stack: \`__STACK__\`
|
|
146
146
|
- MCP endpoint: \`${e}\`
|
|
@@ -338,9 +338,15 @@ ask me to merge it manually into \`~/.claude/settings.json\` or
|
|
|
338
338
|
\`~/.claude/settings.local.json\`; do not auto-write hook JSON:
|
|
339
339
|
|
|
340
340
|
\`\`\`json
|
|
341
|
-
{ "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "
|
|
341
|
+
{ "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${kb}", "timeout": 5 } ] } ] } }
|
|
342
342
|
\`\`\`
|
|
343
343
|
|
|
344
|
+
The hook runs the bridge subcommand \`on-session-reminder\` (bridge 0.94.0 or
|
|
345
|
+
later). If a SessionStart entry already runs
|
|
346
|
+
\`cat ~/.claude/maind-session-start-reminder.md\`, that is the older form:
|
|
347
|
+
replace its command with the one above instead of adding a second entry \u2014
|
|
348
|
+
\`cat\` prints plain text into Cursor, which takes only JSON there.
|
|
349
|
+
|
|
344
350
|
## Session-start message
|
|
345
351
|
|
|
346
352
|
After setup, write this message to the clipboard when possible and print it as
|
|
@@ -375,7 +381,7 @@ written config.
|
|
|
375
381
|
|
|
376
382
|
--- Preamble block ---
|
|
377
383
|
|
|
378
|
-
${Pr}`}function
|
|
384
|
+
${Pr}`}function Fn(e,t,n,r={serversKey:"mcpServers"},i={}){let o=n?`
|
|
379
385
|
MAIND_CLIENT_FAMILY="${n}"`:"",a=n?' "$CONFIG_FILE" "$MAIND_MCP_URL" "$MAIND_CLIENT_FAMILY"':' "$CONFIG_FILE" "$MAIND_MCP_URL"',c=n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":"",l=r.entryType?`
|
|
380
386
|
type: "${r.entryType}",`:"",d=i.keepClientKeys?`const previous = config[serversKey].maind;
|
|
381
387
|
if (previous && typeof previous === "object") {
|
|
@@ -424,7 +430,7 @@ ${d}`:""}
|
|
|
424
430
|
config[serversKey].maind = server;
|
|
425
431
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
426
432
|
console.log("WROTE " + file);
|
|
427
|
-
NODE`}function
|
|
433
|
+
NODE`}function GO(e){return`#!/usr/bin/env bash
|
|
428
434
|
set -euo pipefail
|
|
429
435
|
|
|
430
436
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -477,7 +483,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
477
483
|
|
|
478
484
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
479
485
|
console.log("WROTE " + file);
|
|
480
|
-
NODE`}function
|
|
486
|
+
NODE`}function WO(e=qd){let t=`${e}${UO}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing, merges the MCP-server entry into every supported AI-client config it finds (Claude Code, Cursor, Devin Desktop (formerly Windsurf), Codex, Copilot, Claude Desktop, Cline, Continue), and writes the maind preamble block into CLAUDE.md / AGENTS.md / .cursorrules / .windsurfrules / .github/copilot-instructions.md. Idempotent \u2014 re-running is safe. Run from your project root.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install",extraVariants:[{label:"Non-interactive (CI / scripts)",description:"Skip every TTY prompt. Includes the SessionStart-hook merge into ~/.claude/settings.json \u2014 pass --no-hook to opt out. Useful for Docker, CI, and Dashboard-One-Click flows.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --full"},{label:"Filter to one client",description:"Install for a single client family instead of all detected ones. Replace `<family>` with one of claude-code, claude-desktop, cursor, windsurf (Devin Desktop, formerly Windsurf \u2014 `devin` works too), copilot, cline, continue, codex.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --client <family>"}]},{id:"ai-prompt",label:"AI agent prompt (Power-User / Air-gapped fallback)",description:"Pre-installer fallback: paste this prompt into your AI agent (Claude Code, Copilot, Cursor, Codex, \u2026) and let it orchestrate the install manually. Use this when `npx` is restricted (corporate, air-gapped), when your workspace has a custom layout the auto-detect can't resolve, or when you want to see every config block before it's written. The Quick Setup tab above is the recommended path for most users.",lang:"markdown",template:KO(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
|
|
481
487
|
"mcpServers": {
|
|
482
488
|
"maind": {
|
|
483
489
|
"command": "npx",
|
|
@@ -488,7 +494,7 @@ NODE`}function qN(e=Md){let t=`${e}${KN}`;return[{id:"bridge-installer",label:"Q
|
|
|
488
494
|
}
|
|
489
495
|
}
|
|
490
496
|
}
|
|
491
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:
|
|
497
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:Fn(".mcp.json",t,"claude-code")}]},{id:"claude-desktop",label:"Claude Desktop",description:"Browser-pairing desktop config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/Library/Application Support/Claude/claude_desktop_config.json",lang:"json",template:`{
|
|
492
498
|
"mcpServers": {
|
|
493
499
|
"maind": {
|
|
494
500
|
"command": "npx",
|
|
@@ -499,13 +505,13 @@ NODE`}function qN(e=Md){let t=`${e}${KN}`;return[{id:"bridge-installer",label:"Q
|
|
|
499
505
|
}
|
|
500
506
|
}
|
|
501
507
|
}
|
|
502
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:
|
|
508
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:Fn("$HOME/Library/Application Support/Claude/claude_desktop_config.json",t,"claude-desktop")}]},{id:"codex",label:"Codex CLI",description:"Browser-pairing Codex config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/.codex/config.toml",lang:"toml",template:`[mcp_servers.maind]
|
|
503
509
|
command = "npx"
|
|
504
510
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
505
511
|
|
|
506
512
|
[mcp_servers.maind.env]
|
|
507
513
|
MAIND_CLIENT_FAMILY = "codex"
|
|
508
|
-
MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:
|
|
514
|
+
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:GO(t)}]},{id:"copilot",label:"GitHub Copilot",description:'Browser-pairing workspace config for Copilot agent mode: `.vscode/mcp.json` in VS Code\'s own shape \u2014 `servers` (not `mcpServers`) with `"type": "stdio"`; VS Code ignores an `mcpServers` key silently. Uses `npx`, so the file carries no machine paths and can be committed for the whole team. The installer (`npx -y @maind-dev/mcp-bridge install --client copilot`) instead writes your personal user-profile mcp.json with absolute paths \u2014 same shape, one machine. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as GitHub Copilot. Replace `__STACK__` with your stack slugs.',filename:".vscode/mcp.json",lang:"json",template:`{
|
|
509
515
|
"servers": {
|
|
510
516
|
"maind": {
|
|
511
517
|
"type": "stdio",
|
|
@@ -517,7 +523,7 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
|
|
|
517
523
|
}
|
|
518
524
|
}
|
|
519
525
|
}
|
|
520
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:'Idempotent installer for the workspace `.vscode/mcp.json` read by VS Code Copilot. Creates `.vscode/` if needed, writes VS Code\'s `servers` shape with `"type": "stdio"`, replaces only the maind entry, and lets the bridge create a fresh device-bound key via browser pairing on first launch. Plain JSON only \u2014 a file with comments is reported and left untouched.',filename:"install-maind-copilot.sh",lang:"bash",template:
|
|
526
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:'Idempotent installer for the workspace `.vscode/mcp.json` read by VS Code Copilot. Creates `.vscode/` if needed, writes VS Code\'s `servers` shape with `"type": "stdio"`, replaces only the maind entry, and lets the bridge create a fresh device-bound key via browser pairing on first launch. Plain JSON only \u2014 a file with comments is reported and left untouched.',filename:"install-maind-copilot.sh",lang:"bash",template:Fn(".vscode/mcp.json",t,"copilot",{serversKey:"servers",entryType:"stdio"})}]},{id:"agent-preamble",label:"Agent preamble files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules, .windsurfrules + optional SessionStart reminder)",description:"Idempotent shell script that creates or extends SIX artefacts: the five agent-preamble files (CLAUDE.md / AGENTS.md / .github/copilot-instructions.md / .cursorrules / .windsurfrules) plus a SessionStart-Reminder file at ~/.claude/maind-session-start-reminder.md (for Claude Code users \u2014 referenced by an optional SessionStart-Hook). Existing installations are detected via grep on the line `## maind MCP integration` (matches both the legacy soft variant and the new hardened variant). The script also emits a copy-paste JSON snippet for merging the SessionStart-Hook (the bridge subcommand on-session-reminder, bridge 0.94.0 or later) into ~/.claude/settings.json \u2014 manual merge step because naive append breaks JSON syntax. Switching between agents later does not require any MCP re-config. Drift-note: the five preamble files carry duplicated content (single source: this snippet's heredoc).",filename:"writes CLAUDE.md + AGENTS.md + .github/copilot-instructions.md + .cursorrules + .windsurfrules + ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
|
|
521
527
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
522
528
|
# CLAUDE.md (Claude Code)
|
|
523
529
|
# AGENTS.md (Codex, Devin Desktop, newer Cursor \u2014 cross-agent standard)
|
|
@@ -526,7 +532,8 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
|
|
|
526
532
|
# .windsurfrules (Devin Desktop / Windsurf legacy)
|
|
527
533
|
# ~/.claude/maind-session-start-reminder.md (Claude Code SessionStart-Hook input)
|
|
528
534
|
# Plus emits a JSON snippet for manual merge into ~/.claude/settings.json
|
|
529
|
-
# (the SessionStart-Hook that
|
|
535
|
+
# (the SessionStart-Hook that adds the reminder to every new session \u2014 the
|
|
536
|
+
# bridge subcommand on-session-reminder, bridge 0.94.0 or later).
|
|
530
537
|
#
|
|
531
538
|
# Re-running this script is safe \u2014 it checks for an existing maind section first.
|
|
532
539
|
|
|
@@ -565,8 +572,11 @@ echo ""
|
|
|
565
572
|
echo "Optional next step \u2014 install the SessionStart-Hook for Claude Code users:"
|
|
566
573
|
echo " Merge this snippet into ~/.claude/settings.json (or settings.local.json):"
|
|
567
574
|
echo ""
|
|
568
|
-
echo ' { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "
|
|
575
|
+
echo ' { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "${kb}", "timeout": 5 } ] } ] } }'
|
|
569
576
|
echo ""
|
|
577
|
+
echo " \u2022 The hook runs the bridge subcommand on-session-reminder (bridge 0.94.0 or later)"
|
|
578
|
+
echo " \u2022 An entry that still runs 'cat ~/.claude/maind-session-start-reminder.md' is the"
|
|
579
|
+
echo " older form: replace its command instead of adding a second entry"
|
|
570
580
|
echo " \u2022 If 'hooks' object already exists: add only the SessionStart entry"
|
|
571
581
|
echo " \u2022 If 'hooks.SessionStart' array exists: append a new entry to it"
|
|
572
582
|
echo " \u2022 Do NOT just cat-append \u2014 naive append breaks JSON syntax"
|
|
@@ -583,7 +593,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
583
593
|
}
|
|
584
594
|
}
|
|
585
595
|
}
|
|
586
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:
|
|
596
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:Fn("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Devin Desktop (formerly Windsurf)",description:"Browser-pairing Devin Desktop config \u2014 Devin's own MCP file, which Devin Desktop's agent (Devin Local) and the Devin CLI read: `~/.config/devin/mcp_config.json` on macOS and Linux (`$XDG_CONFIG_HOME/devin/` when set), `%APPDATA%\\devin\\mcp_config.json` on Windows. Add the `maind` entry next to your other servers. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/.config/devin/mcp_config.json",lang:"json",template:`{
|
|
587
597
|
"mcpServers": {
|
|
588
598
|
"maind": {
|
|
589
599
|
"command": "npx",
|
|
@@ -594,7 +604,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
594
604
|
}
|
|
595
605
|
}
|
|
596
606
|
}
|
|
597
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Devin Desktop's ~/.config/devin/mcp_config.json (macOS and Linux; honours XDG_CONFIG_HOME). It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-devin-desktop.sh",lang:"bash",template:
|
|
607
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Devin Desktop's ~/.config/devin/mcp_config.json (macOS and Linux; honours XDG_CONFIG_HOME). It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-devin-desktop.sh",lang:"bash",template:Fn("${XDG_CONFIG_HOME:-$HOME/.config}/devin/mcp_config.json",t,"windsurf")}]},{id:"cline",label:"Cline",description:"Browser-pairing Cline config \u2014 one file for Cline in every editor (VS Code, Cursor, AgentComposer, \u2026), the Cline CLI and Cline Desktop (Cline 4.x; in Cline: MCP Servers \u2192 Configure \u2192 Configure MCP Servers opens it). Add the `maind` entry next to your other servers. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as Cline. Replace `__STACK__` with your stack slugs.",filename:"~/.cline/data/settings/cline_mcp_settings.json",lang:"json",template:`{
|
|
598
608
|
"mcpServers": {
|
|
599
609
|
"maind": {
|
|
600
610
|
"command": "npx",
|
|
@@ -606,7 +616,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
606
616
|
"disabled": false
|
|
607
617
|
}
|
|
608
618
|
}
|
|
609
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cline/data/settings/cline_mcp_settings.json. It merges the bridge-backed maind server, keeps your other servers and what you set on the entry in Cline (disabled, autoApprove, timeout), and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cline.sh",lang:"bash",template:
|
|
619
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cline/data/settings/cline_mcp_settings.json. It merges the bridge-backed maind server, keeps your other servers and what you set on the entry in Cline (disabled, autoApprove, timeout), and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cline.sh",lang:"bash",template:Fn("$HOME/.cline/data/settings/cline_mcp_settings.json",t,"cline",{serversKey:"mcpServers"},{keepClientKeys:!0})}]},{id:"continue",label:"Continue",description:"Browser-pairing Continue config as a file of its own: Continue loads every JSON file in `~/.continue/mcpServers/` (and in a workspace's `.continue/mcpServers/`) in this shape, so your `config.yaml` stays as it is. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as Continue. Replace `__STACK__` with your stack slugs.",filename:"~/.continue/mcpServers/maind.json",lang:"json",template:`{
|
|
610
620
|
"mcpServers": {
|
|
611
621
|
"maind": {
|
|
612
622
|
"command": "npx",
|
|
@@ -617,7 +627,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
617
627
|
}
|
|
618
628
|
}
|
|
619
629
|
}
|
|
620
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.continue/mcpServers/maind.json. It creates the folder if needed, merges the bridge-backed maind server, and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-continue.sh",lang:"bash",template:
|
|
630
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.continue/mcpServers/maind.json. It creates the folder if needed, merges the bridge-backed maind server, and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-continue.sh",lang:"bash",template:Fn("$HOME/.continue/mcpServers/maind.json",t,"continue")}]},{id:"langchain-ts",label:"LangChain / LangGraph (TS)",description:"Bridge-backed stdio MCP client. The bridge opens browser pairing, creates a fresh device-bound key, and forwards calls to the stack-aware maind endpoint. Replace `__STACK__` with your stack slugs.",filename:"agent.ts",lang:"ts",template:`import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
|
621
631
|
|
|
622
632
|
const mcp = new MultiServerMCPClient({
|
|
623
633
|
maind: {
|
|
@@ -638,7 +648,7 @@ const tools = await mcp.getTools();
|
|
|
638
648
|
"env": {
|
|
639
649
|
"MAIND_MCP_URL": "${t}"
|
|
640
650
|
}
|
|
641
|
-
}`}]}var
|
|
651
|
+
}`}]}var jO,HO,qd,UO,qJ,kb,Pr,JJ,Sb=w(()=>{"use strict";jO="__STACK__",HO="__INTENT__",qd="https://mcp.maind.dev/mcp",UO=`?stack=${jO}&intent=${HO}`;s(BO,"buildStackAwareEndpoint");qJ=BO(qd,{stack:["nextjs","supabase"],intent:"mixed"}),kb="npx -y @maind-dev/mcp-bridge on-session-reminder",Pr=`## maind MCP integration \u2014 Mandatory consultation
|
|
642
652
|
|
|
643
653
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
644
654
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -707,34 +717,38 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
707
717
|
If no path is discoverable, provide a guided fallback:
|
|
708
718
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
709
719
|
|
|
710
|
-
Full tool set + provenance via \`get_conventions\`.`;s(
|
|
711
|
-
`).trim(),{text:r}=
|
|
712
|
-
`)}function
|
|
720
|
+
Full tool set + provenance via \`get_conventions\`.`;s(KO,"buildAiPromptBody");s(Fn,"buildJsonConfigInstaller");s(GO,"buildCodexTomlInstaller");s(WO,"buildSnippetTemplates");JJ=WO(qd)});function VO(e){return`Project conventions \u2014 always-on policies served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on Codex session start, do not edit by hand.`}function Ws(e,t){let n=e.replace(/\r\n/g,`
|
|
721
|
+
`).trim(),{text:r}=zO(n,6e3);return[xb,VO(t),r,Eb].join(`
|
|
722
|
+
`)}function zO(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
|
|
713
723
|
`),r=s(a=>{let c=n.slice(a),l=c.filter(d=>/^- /.test(d)).length;return`\u2026 (${l>0?l:c.length} more via get_conventions)`},"tailFor"),i=[],o=0;for(let a=0;a<n.length;a++){let c=(i.length===0?0:1)+n[a].length,l=a+1<n.length?1+r(a+1).length:0;if(o+c+l>t){if(i.length===0){let u=r(1);i.push(n[0].slice(0,Math.max(0,t-u.length-1)))}let d=r(i.length);return{text:[...i,d].join(`
|
|
714
724
|
`),dropped:n.length-i.length}}i.push(n[a]),o+=c}return{text:i.join(`
|
|
715
|
-
`),dropped:0}}function
|
|
725
|
+
`),dropped:0}}function Tb(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Vs(e,t){return e.split(/\r?\n/).some(n=>n.startsWith(t))}function zs(e,t,n){let r=e.includes(`\r
|
|
716
726
|
`)?`\r
|
|
717
727
|
`:`
|
|
718
728
|
`,i=e.split(r),o=t.split(`
|
|
719
|
-
`),a=i.findIndex(g=>g.trim()===
|
|
720
|
-
`:null);if(o===null||!
|
|
721
|
-
`:
|
|
722
|
-
`;return await
|
|
729
|
+
`),a=i.findIndex(g=>g.trim()===xb);if(a>=0){let g=i.findIndex((b,v)=>v>a&&b.trim()===Eb);if(g<0)return{next:e,changed:!1,outcome:"damaged"};let y=i.slice(a,g+1);if(qO(y,o))return{next:e,changed:!1,outcome:"unchanged"};let _=[...i.slice(0,a),...o,...i.slice(g+1)].join(r);return{next:_,changed:_!==e,outcome:"replaced"}}let c=i.findIndex(g=>g.startsWith(n));if(c<0)return{next:e,changed:!1,outcome:"no-header"};let l=i.length,d=!1;for(let g=c+1;g<i.length;g++){if(/^\s{0,3}(```|~~~)/.test(i[g])){d=!d;continue}if(!d&&/^#{1,2}\s/.test(i[g])){l=g;break}}let u=l-1;for(;u>c&&i[u].trim()==="";)u--;let p=i.slice(0,u+1),f=i.slice(u+1),m=[...p,"",...o];return l===i.length?m.push(...f.length===0?[""]:f):((f.length===0||f[0].trim()!=="")&&m.push(""),m.push(...f)),{next:m.join(r),changed:!0,outcome:"inserted"}}function qO(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(n!==1&&e[n].replace(/\r$/,"")!==t[n])return!1;return!0}var xb,Eb,Jd=w(()=>{"use strict";xb="<!-- maind:conventions v1 begin -->",Eb="<!-- maind:conventions v1 end -->";s(VO,"renderConventionsLead");s(Ws,"renderConventionsBlock");s(zO,"capAtLineBoundary");s(Tb,"countConventions");s(Vs,"hasMaindSection");s(zs,"upsertConventionsBlock");s(qO,"sameConventions")});import*as ot from"node:path";function JO(e){return[{key:"preamble:CLAUDE.md",path:ot.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:ot.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:ot.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:ot.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:ot.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:ot.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}async function Rb(e,t=!1){let n=JO(e),r=[];for(let i of n)r.push(await XO(i,t));return e.conventions!==void 0&&r.push(await YO(e,t)),r}async function YO(e,t){let n=ot.join(e.projectRoot,"AGENTS.md"),r=s(i=>({target:Mr,action:"upsert",status:"skipped",detail:`conventions block: ${i}`}),"skip");try{let o=await Y(n)??(t?`${Pr}
|
|
730
|
+
`:null);if(o===null||!Vs(o,jn))return r("skipped (no maind header in AGENTS.md)");let a=await e.conventions();if(a===null||a.trim().length===0)return r("skipped (no conventions yet)");let c=Ws(a,{date:new Date().toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??U}),l=zs(o,c,jn);switch(l.outcome){case"unchanged":return r("unchanged");case"no-header":return r("skipped (no maind header in AGENTS.md)");case"damaged":return r("skipped (begin marker without end marker \u2014 remove the <!-- maind:conventions --> lines)");case"inserted":case"replaced":{let d=l.outcome==="inserted"?"insert":"refresh";return t?{target:Mr,action:"upsert",status:"would-merge",detail:`conventions block: would ${d}`}:(await V(n,l.next),{target:Mr,action:"upsert",status:"merged",detail:`conventions block: ${d==="insert"?"inserted":"refreshed"}`})}}}catch(i){let o=i instanceof Error?i.message:String(i);return{target:Mr,action:"upsert",status:"failed",detail:`conventions block: ${o}`}}}async function XO(e,t){try{if(e.mayNeedParentDir&&!t&&await Vd(ot.dirname(e.path)),await fb(e.path,jn))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await Y(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${Pr}
|
|
731
|
+
`:ZO(r)+`${Pr}
|
|
732
|
+
`;return await V(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}function ZO(e){return e.endsWith(`
|
|
723
733
|
|
|
724
734
|
`)?e:e.endsWith(`
|
|
725
735
|
`)?e+`
|
|
726
736
|
`:e+`
|
|
727
737
|
|
|
728
|
-
`}var $n,Mr,Ld=v(()=>{"use strict";X_();We();$d();xe();$n="## maind MCP integration",Mr="preamble:AGENTS.md#conventions";s(ZN,"buildPreambleTargets");s(tb,"writePreambleFiles");s(QN,"writeAgentsMdConventionsBlock");s(eO,"writeOnePreambleFile");s(tO,"ensureTrailingBlankLine")});import{existsSync as nO}from"node:fs";import*as nb from"node:path";function Te(e,t={},n=at){let r=t.fileExists??nO,i=t.expectedCommand??oO,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Fd(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=sO(o,a.event,a.subcommand),d=l===null&&a.supersedes?aO(o,a.event,a.supersedes.pattern):null;if(d!==null&&a.supersedes){let f=a.supersedes.replaceable.test(d);return{...c,status:"superseded",command:d,remedy:f?"run-install":"edit-command",detail:f?`${a.label} still runs \`${d}\` \u2014 plain text, which Cursor rejects (it imports this hook and takes only JSON at session start). \`install --hooks-only\` replaces that entry with '${a.subcommand}', which prints the same text in Claude Code.`:`${a.label} runs your own command on the reminder file (\`${d}\`) \u2014 left as it is; it prints plain text where Cursor takes only JSON. Replace its command with: ${i(a.subcommand)}`}}if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(Is(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(Or(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let p=cO(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 Hd(e){return e.some(t=>t.status!=="ok")}function Gs(e){return e.some(t=>t.remedy==="run-install")}function oO(e){return it(ke({entryPath:he(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function sO(e,t,n){return rb(e,t,r=>r.includes(n))}function aO(e,t,n){return rb(e,t,r=>n.test(r))}function rb(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Fd(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Fd(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function cO(e){for(let t of lO(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return nb.isAbsolute(t)?t:null;return null}function lO(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Fd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var st,jd,Ln,rO,iO,at,$r,ct=v(()=>{"use strict";Gt();st="on-session-briefing",jd=".claude/maind-session-start-reminder.md",Ln="on-session-reminder",rO=/maind-session-start-reminder\.md/,iO=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,at=[{event:"SessionStart",subcommand:Ln,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:rO,replaceable:iO},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:st,label:"SessionStart briefing hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-briefing' when a session starts (and again after a compaction) and adds your maind session briefing to the session context \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 kept under Claude Code's 10,000-character hook limit so it arrives whole. This is delivery, not enforcement: it never blocks anything, and it works with the guard pack off. UNLIKE the other core hooks it talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, project key and the client family 'claude-code' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most session starts add no network call; it keeps a per-session marker and a one-line log entry under ~/.maind/guard/. When the guard pack's guard-inject is wired too, that one stays silent, so the briefing arrives once."},{event:"UserPromptSubmit",subcommand:"on-prompt-context",label:"UserPromptSubmit context hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-prompt-context' each time you submit a prompt. It reads the PROMPT TEXT on this machine only and matches it against two local sources: the project conventions MAIND already cached here (.maind/conventions-cache.json, or the session-briefing cache ~/.maind/guard/briefing-cache.json) and the symbol NAMES in this repository's local code index (.maind/code-index.sqlite \u2014 index rows only, never file contents). When something matches, it adds at most ~2,000 characters for the model: the matching conventions, and the file:line of symbols the prompt names. The prompt is never uploaded, stored or logged; nothing leaves the machine, and no network call is made. Each convention and symbol is mentioned at most once per session (an empty marker file per item under ~/.maind/context/). It never blocks or rewrites a prompt."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PreToolUse",subcommand:"on-read-context",label:"PreToolUse read-context hook",timeout:5,matcher:"Read",consentDescription:"It runs 'maind-mcp-bridge on-read-context' before the Read tool opens a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents \u2014 and looks it up in this repository's local code index (.maind/code-index.sqlite): symbol names, kinds, line spans, each symbol's stored first declaration line, and the import-resolved call graph. Only if the index still matches that file on disk does it add at most ~1,500 characters for the model: which symbols other files call and from where, which files import it, and \u2014 when the Read covers only part of the file \u2014 an outline of the rest. A file the index does not cover, or one changed since it was indexed, gets nothing. Runs entirely on this machine; no network call, nothing is uploaded; at most once per file per session (an empty marker file under ~/.maind/context/). It never blocks a Read."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],$r=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off, and while the core on-session-briefing hook is wired \u2014 that one delivers the same briefing, guard or no guard."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. With the guard-difficulty hook also installed (ADR-360), block mode may in addition deny edits during an open difficulty episode until a maind consultation happens \u2014 reading only that hook's local log. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."},{event:"PostToolUseFailure",subcommand:"guard-difficulty",label:"Guard difficulty hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-difficulty' after a tool call FAILS (ADR-360). For Bash and for MCP tools other than maind's own it reads the tool NAME and, for Bash, the PROGRAM and subcommand of the command line (e.g. `pnpm test`) \u2014 never paths, flags, values, the error text or any output \u2014 and appends one line (time, 'fail', that program name) to a local per-session log in ~/.maind/guard/triggers/. File tools, lookups such as grep or ls, interrupts you caused and subagent calls are not counted. When four failed attempts follow each other without a ten-minute pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key like guard-inject \u2014 never tool data \u2014 and, if conv_consult_on_difficulty is on for you, adds ONE hint for the model to consult maind before the next attempt. Only in block mode ('guard mode block') and only if that convention is required does the gate hook then deny edits until a consultation happens (override: 'guard skip --kind difficulty'). Off on this machine: 'guard difficulty off'; off everywhere: switch the convention off in your maind settings. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-outcome",label:"Guard outcome hook",timeout:10,matcher:"Bash|mcp__.*",consentDescription:"It runs 'maind-mcp-bridge guard-outcome' after a Bash or MCP tool call SUCCEEDS (ADR-360). Test and build runs often end with exit code 0 because their output is piped through `tail` or `grep`, so for Bash it reads the LAST 8 KB of stdout/stderr on this machine to recognise a failure summary (e.g. '2 failed', 'error TS2322', 'ELIFECYCLE') and then discards it \u2014 no output is stored or sent. It writes the same kind of line as guard-difficulty (time, fail or ok, a program name such as `pnpm test`), and an 'ok' only for a program that already failed in this session: that is how a fixed problem is recognised. The log stays in ~/.maind/guard/triggers/; nothing leaves the machine. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-capture",label:"Guard capture hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-capture' when a turn ends (ADR-360). Only after a hard-won fix recorded by the guard-difficulty and guard-outcome hooks \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it holds the end of the turn ONCE per episode with a reason asking the agent to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'; off everywhere: the convention switch. Inactive while guard mode is off."}];s(Te,"inspectHookWiring");s(Hd,"hasWiringDrift");s(Gs,"needsInstallRun");s(oO,"defaultExpectedCommand");s(sO,"findCommand");s(aO,"findCommandMatching");s(rb,"findFirstCommand");s(cO,"extractScriptPath");s(lO,"tokenize");s(Fd,"isObject")});import{existsSync as dO,readFileSync as uO}from"node:fs";import{join as pO}from"node:path";function Ve(){return pO(Ke(),"config.json")}function te(){try{let e=Ve();if(!dO(e))return null;let t=JSON.parse(uO(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),typeof n.guard_difficulty=="boolean"&&(r.guard_difficulty=n.guard_difficulty),typeof n.guard_capture=="boolean"&&(r.guard_capture=n.guard_capture),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),Array.isArray(n.declined_hooks)&&(r.declined_hooks=n.declined_hooks.filter(i=>typeof i=="string")),typeof n.devin_hook_output=="boolean"&&(r.devin_hook_output=n.devin_hook_output),r}catch{return null}}var ze=v(()=>{"use strict";se();s(Ve,"bridgeConfigPath");s(te,"readBridgeConfig")});function fO(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===Ud?r.add(a.subcommand):(l.status==="created"||l.status==="merged"||l.status==="skipped"&&l.detail!==void 0&&/already runs maind /.test(l.detail))&&r.delete(a.subcommand))});let i=[...r].sort();return i.length===e.length&&i.every(a=>e.includes(a))?null:i}async function Bd(e,t,n=Ve()){try{let r={},i=await X(n);if(i!==null&&i.trim().length>0){let l=JSON.parse(i);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let o=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=fO(o,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await z(n,JSON.stringify(c,null,2)+`
|
|
729
|
-
`,384)}catch{}}var
|
|
738
|
+
`}var jn,Mr,Yd=w(()=>{"use strict";Sb();ze();Jd();we();jn="## maind MCP integration",Mr="preamble:AGENTS.md#conventions";s(JO,"buildPreambleTargets");s(Rb,"writePreambleFiles");s(YO,"writeAgentsMdConventionsBlock");s(XO,"writeOnePreambleFile");s(ZO,"ensureTrailingBlankLine")});import{existsSync as QO}from"node:fs";import*as Ab from"node:path";function Re(e,t={},n=at){let r=t.fileExists??QO,i=t.expectedCommand??nD,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Xd(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=rD(o,a.event,a.subcommand),d=l===null&&a.supersedes?iD(o,a.event,a.supersedes.pattern):null;if(d!==null&&a.supersedes){let f=a.supersedes.replaceable.test(d);return{...c,status:"superseded",command:d,remedy:f?"run-install":"edit-command",detail:f?`${a.label} still runs \`${d}\` \u2014 plain text, which Cursor rejects (it imports this hook and takes only JSON at session start). \`install --hooks-only\` replaces that entry with '${a.subcommand}', which prints the same text in Claude Code.`:`${a.label} runs your own command on the reminder file (\`${d}\`) \u2014 left as it is; it prints plain text where Cursor takes only JSON. Replace its command with: ${i(a.subcommand)}`}}if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(Ms(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(Or(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let p=oD(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 Qd(e){return e.some(t=>t.status!=="ok")}function qs(e){return e.some(t=>t.remedy==="run-install")}function nD(e){return it(xe({entryPath:ge(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function rD(e,t,n){return Cb(e,t,r=>r.includes(n))}function iD(e,t,n){return Cb(e,t,r=>n.test(r))}function Cb(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Xd(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Xd(a))continue;let c=a.command;if(typeof c=="string"&&n(c))return c}}return null}function oD(e){for(let t of sD(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Ab.isAbsolute(t)?t:null;return null}function sD(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Xd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var st,Zd,Hn,eD,tD,at,$r,ct=w(()=>{"use strict";Kt();st="on-session-briefing",Zd=".claude/maind-session-start-reminder.md",Hn="on-session-reminder",eD=/maind-session-start-reminder\.md/,tD=/^\s*cat\s+(['"]?)[^'"`;&|<>$]*maind-session-start-reminder\.md\1\s*$/,at=[{event:"SessionStart",subcommand:Hn,label:"SessionStart reminder hook",timeout:5,supersedes:{pattern:eD,replaceable:tD},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:st,label:"SessionStart briefing hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-briefing' when a session starts (and again after a compaction) and adds your maind session briefing to the session context \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 kept under Claude Code's 10,000-character hook limit so it arrives whole. This is delivery, not enforcement: it never blocks anything, and it works with the guard pack off. UNLIKE the other core hooks it talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, project key and the client family 'claude-code' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most session starts add no network call; it keeps a per-session marker and a one-line log entry under ~/.maind/guard/. When the guard pack's guard-inject is wired too, that one stays silent, so the briefing arrives once."},{event:"UserPromptSubmit",subcommand:"on-prompt-context",label:"UserPromptSubmit context hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-prompt-context' each time you submit a prompt. It reads the PROMPT TEXT on this machine only and matches it against two local sources: the project conventions MAIND already cached here (.maind/conventions-cache.json, or the session-briefing cache ~/.maind/guard/briefing-cache.json) and the symbol NAMES in this repository's local code index (.maind/code-index.sqlite \u2014 index rows only, never file contents). When something matches, it adds at most ~2,000 characters for the model: the matching conventions, and the file:line of symbols the prompt names. The prompt is never uploaded, stored or logged; nothing leaves the machine, and no network call is made. Each convention and symbol is mentioned at most once per session (an empty marker file per item under ~/.maind/context/). It never blocks or rewrites a prompt."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only. 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."}],$r=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off, and while the core on-session-briefing hook is wired \u2014 that one delivers the same briefing, guard or no guard."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. With the guard-difficulty hook also installed (ADR-360), block mode may in addition deny edits during an open difficulty episode until a maind consultation happens \u2014 reading only that hook's local log. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."},{event:"PostToolUseFailure",subcommand:"guard-difficulty",label:"Guard difficulty hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-difficulty' after a tool call FAILS (ADR-360). For Bash and for MCP tools other than maind's own it reads the tool NAME and, for Bash, the PROGRAM and subcommand of the command line (e.g. `pnpm test`) \u2014 never paths, flags, values, the error text or any output \u2014 and appends one line (time, 'fail', that program name) to a local per-session log in ~/.maind/guard/triggers/. File tools, lookups such as grep or ls, interrupts you caused and subagent calls are not counted. When four failed attempts follow each other without a ten-minute pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key like guard-inject \u2014 never tool data \u2014 and, if conv_consult_on_difficulty is on for you, adds ONE hint for the model to consult maind before the next attempt. Only in block mode ('guard mode block') and only if that convention is required does the gate hook then deny edits until a consultation happens (override: 'guard skip --kind difficulty'). Off on this machine: 'guard difficulty off'; off everywhere: switch the convention off in your maind settings. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-outcome",label:"Guard outcome hook",timeout:10,matcher:"Bash|mcp__.*",consentDescription:"It runs 'maind-mcp-bridge guard-outcome' after a Bash or MCP tool call SUCCEEDS (ADR-360). Test and build runs often end with exit code 0 because their output is piped through `tail` or `grep`, so for Bash it reads the LAST 8 KB of stdout/stderr on this machine to recognise a failure summary (e.g. '2 failed', 'error TS2322', 'ELIFECYCLE') and then discards it \u2014 no output is stored or sent. It writes the same kind of line as guard-difficulty (time, fail or ok, a program name such as `pnpm test`), and an 'ok' only for a program that already failed in this session: that is how a fixed problem is recognised. The log stays in ~/.maind/guard/triggers/; nothing leaves the machine. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-capture",label:"Guard capture hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-capture' when a turn ends (ADR-360). Only after a hard-won fix recorded by the guard-difficulty and guard-outcome hooks \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it holds the end of the turn ONCE per episode with a reason asking the agent to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'; off everywhere: the convention switch. Inactive while guard mode is off."}];s(Re,"inspectHookWiring");s(Qd,"hasWiringDrift");s(qs,"needsInstallRun");s(nD,"defaultExpectedCommand");s(rD,"findCommand");s(iD,"findCommandMatching");s(Cb,"findFirstCommand");s(oD,"extractScriptPath");s(sD,"tokenize");s(Xd,"isObject")});import{existsSync as aD,readFileSync as cD}from"node:fs";import{join as lD}from"node:path";function Ae(){return lD(Ve(),"config.json")}function ee(){try{let e=Ae();if(!aD(e))return null;let t=JSON.parse(cD(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),typeof n.guard_difficulty=="boolean"&&(r.guard_difficulty=n.guard_difficulty),typeof n.guard_capture=="boolean"&&(r.guard_capture=n.guard_capture),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),Array.isArray(n.declined_hooks)&&(r.declined_hooks=n.declined_hooks.filter(i=>typeof i=="string")),typeof n.devin_hook_output=="boolean"&&(r.devin_hook_output=n.devin_hook_output),typeof n.checkout_memory=="boolean"&&(r.checkout_memory=n.checkout_memory),r}catch{return null}}var Ce=w(()=>{"use strict";ie();s(Ae,"bridgeConfigPath");s(ee,"readBridgeConfig")});function dD(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===eu?r.add(a.subcommand):(l.status==="created"||l.status==="merged"||l.status==="skipped"&&l.detail!==void 0&&/already runs maind /.test(l.detail))&&r.delete(a.subcommand))});let i=[...r].sort();return i.length===e.length&&i.every(a=>e.includes(a))?null:i}async function tu(e,t,n=Ae()){try{let r={},i=await Y(n);if(i!==null&&i.trim().length>0){let l=JSON.parse(i);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let o=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=dD(o,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await V(n,JSON.stringify(c,null,2)+`
|
|
739
|
+
`,384)}catch{}}var eu,nu=w(()=>{"use strict";Ce();we();eu="user declined";s(dD,"nextDeclinedHooks");s(tu,"recordHookDecisions")});import*as Ib from"node:path";import*as Nb from"node:readline";async function uD(e,t){let n=Ib.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await Y(n)}catch(g){return{target:r,action:"merge",status:"failed",detail:`read: ${ru(g)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let g=JSON.parse(i);if(!qi(g))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};o=g}catch(g){return{target:r,action:"merge",status:"failed",detail:`parse: ${ru(g)}`}}}let c=mD(o,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};let l=t.supersedes?fD(o,t.event,t.supersedes.pattern):null;if(l!==null&&t.supersedes&&!t.supersedes.replaceable.test(l.command))return{target:r,action:"skip",status:"skipped",detail:`your own command already prints this (\`${l.command}\`) \u2014 left as it is; it prints plain text where Cursor takes only JSON. Replace its command with: ${t.command}`};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};let g=l!==null?`
|
|
730
740
|
Replace the ${t.event} hook \`${l.command}\` in ${n}?
|
|
731
741
|
${t.consentDescription}
|
|
732
742
|
[Y/n]: `:`
|
|
733
743
|
Merge a ${t.event} hook into ${n}?
|
|
734
744
|
${t.consentDescription}
|
|
735
|
-
[Y/n]: `;if(!await(e.prompt??
|
|
736
|
-
`,m=l===null?"":` (replaced \`${l.command}\`)`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:l===null?n:`${n} (would replace \`${l.command}\`)`};try{await
|
|
737
|
-
`,1)[0]??"").trim().slice(0,200)}function $O(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 LO(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=$O(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Zd(e,t,n,r){for(let i of LO(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function Ki(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let i=n;for(;i?.type==="member_expression";)i=i.childForFieldName("object");return i?.type==="this"?{name:t,receiver:"this.*"}:i?.type==="identifier"?{name:t,receiver:`${i.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function Jt(e){if(!e)return null;let t=e.type==="type_annotation"?e.namedChildren[0]??null:e;if(!t)return null;switch(t.type){case"type_identifier":return t.text;case"nested_type_identifier":return t.text.replace(/\s+/g,"");case"generic_type":return Jt(t.childForFieldName("name"));case"parenthesized_type":return Jt(t.namedChildren[0]??null);case"union_type":{let n=t.namedChildren.filter(r=>!(r.type==="literal_type"&&/^(null|undefined)$/.test(r.text))&&!(r.type==="predefined_type"&&/^(null|undefined|void)$/.test(r.text)));return n.length===1?Jt(n[0]):"#"}default:return"#"}}function jO(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Qd(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 Wi(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),o=Jt(n.childForFieldName("type"))??Qd(i)??(jO(i)?"#":null);o&&t.set(r.text,o)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=Jt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function Xt(e,t,n,r,i={locals:Wi(n)}){let o=new Set,a=s(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(o.has(d))return;o.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...FO]:["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 FO,zs=v(()=>{"use strict";s(Ws,"newResult");s(Yt,"line1");s(Vs,"signatureOf");s($O,"calleeName");s(LO,"collectCallTargets");s(Zd,"addCallRefs");s(Ki,"calleeRef");FO=["jsx_opening_element","jsx_self_closing_element"];s(Jt,"typeNameOf");s(jO,"isMethodCallResult");s(Qd,"newTypeOf");s(Wi,"collectTypeHints");s(Xt,"addTsRefs")});function bb(e,t){let n=Ws();for(let r of e.namedChildren)HO(r,t,n);return n}function vb(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function HO(e,t,n){let r=vb(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??BO(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=qs(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Zd(n,o.nodeKey,a,_b);return}case"class_definition":UO(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=qs(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function UO(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=qs(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=vb(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=qs(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&Zd(n,p.nodeKey,f,_b)}}function qs(e,t,n,r,i){return{nodeKey:nt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Yt(e.startPosition.row),endLine:Yt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Vs(e),doc:null}}function BO(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var _b,wb=v(()=>{"use strict";vn();zs();_b="call";s(bb,"extractPython");s(vb,"unwrapDecorated");s(HO,"handleTopLevel");s(UO,"addClass");s(qs,"makeNode");s(BO,"firstDottedName")});function xb(e,t){let n=Ws(),r=t.language!=="typescript";for(let i of e.namedChildren)KO(i,t,n,r);return zO(e,t,n),n}function GO(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function KO(e,t,n,r){if(e.type==="export_statement"&&WO(e,t,n,r))return;let i=GO(e),o=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":VO(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=kb(i,t,n,"function",r);o&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=JO(i,t,n,r);o&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":eu(i,t,n,"interface");return;case"type_alias_declaration":eu(i,t,n,"type_alias");return;case"enum_declaration":eu(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of i.namedChildren){if(a.type!=="variable_declarator")continue;let c=a.childForFieldName("name"),l=a.childForFieldName("value");if(!c||c.type!=="identifier"){l&&Xt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";kb(a,t,n,d?"function":"variable",r,c,l)}return}default:Xt(n,t.moduleKey,i,r);return}}function WO(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=nu(e.childForFieldName("source")),o=e.namedChildren.find(l=>l.type==="export_clause"),a=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),o)for(let l of o.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(a){let l=a.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(o){for(let l of o.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):Xt(n,t.moduleKey,c,r),!0):!1}function VO(e,t,n){let r=nu(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),o=[],a=s((c,l)=>{o.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")a("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&a("*",l)}else if(c.type==="named_imports")for(let l of c.namedChildren.filter(d=>d.type==="import_specifier")){let d=l.childForFieldName("name")?.text;d&&a(d,l.childForFieldName("alias")?.text??d)}o.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...o)}function zO(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,o=i?.type==="string"?nu(i):null;if(o===null)continue;let c=qO(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:o,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:o,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:o})}}function qO(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function kb(e,t,n,r,i,o,a){let l=(o??e.childForFieldName("name"))?.text;if(!l)return null;let d=Js(e,t,l,l,r);if(n.nodes.push(d),n.edges.push({srcKey:t.moduleKey,dstKey:d.nodeKey,kind:"contains"}),r==="function"){let u=a??e.childForFieldName("body")??e;Xt(n,d.nodeKey,u,i,{locals:Wi(e)})}else a&&Xt(n,d.nodeKey,a,i);return d}function eu(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=Js(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function JO(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let o=Js(e,t,i,i,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of a?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(p=>({kind:"implements",ref:tu(p)})):[{kind:"extends",ref:tu(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:f}of u)f&&n.refs.push({fromKey:o.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let c=e.childForFieldName("body");if(!c)return o;let l=YO(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&Xt(n,o.nodeKey,g,r,{locals:Wi(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,f=Js(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:o.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&Xt(n,f.nodeKey,m,r,{locals:Wi(d),thisFields:l})}return o}function YO(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),i=Jt(n.childForFieldName("type"))??Qd(n.childForFieldName("value"));r&&i&&t.set(r.text,i)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(a=>a.type==="accessibility_modifier"||a.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),o=Jt(r.childForFieldName("type"));i?.type==="identifier"&&o&&t.set(i.text,o)}return t}function Js(e,t,n,r,i){return{nodeKey:nt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Yt(e.startPosition.row),endLine:Yt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Vs(e),doc:null}}function tu(e){if(!e)return null;switch(e.type){case"generic_type":return tu(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 nu(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var Sb=v(()=>{"use strict";vn();zs();s(xb,"extractTypescript");s(GO,"unwrapExport");s(KO,"handleTopLevel");s(WO,"handleExportForm");s(VO,"addImport");s(zO,"collectDynamicImports");s(qO,"enclosingDeclarator");s(kb,"addFunctionLike");s(eu,"addSimpleNamed");s(JO,"addClass");s(YO,"classFieldTypes");s(Js,"makeNode");s(tu,"heritageRef");s(nu,"stringValue")});import{createRequire as XO}from"node:module";import{join as ZO}from"node:path";function Rb(e,t){return t?ZO(t,Eb[e]):XO(import.meta.url).resolve(`tree-sitter-wasms/out/${Eb[e]}`)}var Eb,Tb,Cb=v(()=>{"use strict";Eb={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Tb="tree-sitter.wasm";s(Rb,"grammarPath")});import{join as QO}from"node:path";import ru from"web-tree-sitter";var eD,Ys,Ab=v(()=>{"use strict";vn();Yo();wb();Sb();zs();Cb();eD=["typescript","tsx","javascript","python"],Ys=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await ru.init(this.assetDir?{locateFile:s(t=>QO(this.assetDir,t||Tb),"locateFile")}:void 0),this.parser=new ru,this.initialized=!0)}supports(t){return eD.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=o.rootNode,c=tt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Yt(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?bb(a,d):xb(a,d);return o.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await ru.Language.load(Rb(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as tD}from"node:module";function Ib(){return Xs("node:sqlite")}function Lr(){if(Vi)return Vi;try{let{DatabaseSync:e}=Ib(),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(),Vi={ok:!0}}finally{t.close()}}catch(e){Vi={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Vi}function nD(e){let{DatabaseSync:t}=Ib(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function rD(e){let t=Xs("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 Nb(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Zs(e){let t=Nb(),n=s(()=>{let{DatabaseSync:i}=Xs("node:sqlite"),o=new i(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>o.prepare(a),"prepare"),exec:s(a=>o.exec(a),"exec"),close:s(()=>o.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let i=Xs("better-sqlite3"),o=new i(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>o.prepare(a),"prepare"),exec:s(a=>{o.exec(a)},"exec"),close:s(()=>{o.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(i){try{return r()}catch(o){let a=s(c=>c instanceof Error?c.message:String(c),"reason");throw new Error(`no usable SQLite backend for a read-only open: node:sqlite (${a(i)}); better-sqlite3 (${a(o)})`)}}}function Qs(e){let t=Nb(),n=s(i=>{let o=i==="node:sqlite"?nD(e):rD(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=Lr();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=Lr();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var Xs,Vi,ea=v(()=>{"use strict";Xs=tD(import.meta.url);s(Ib,"loadBuiltin");Vi=null;s(Lr,"probeBuiltinSqlite");s(nD,"openBuiltin");s(rD,"openBetter");s(Nb,"backendOverride");s(Zs,"openSqliteReadOnly");s(Qs,"openSqliteDatabase")});function jb(e,t){return{refs:t.refs.map(n=>[e,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:t.imports.map(n=>[e,n.specifier,n.importedName??null,n.localName??null]),exports:t.exports.map(n=>[e,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function Hb(e,t,n,r){let i=new Map;for(let a of e)i.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let o=s(a=>i.get(String(a.file_path)),"entry");for(let a of t)o(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Hn(a.receiver),receiverType:Hn(a.receiver_type)});for(let a of n){let c=o(a);if(!c)continue;let l={fromModuleKey:tt(c.filePath),specifier:String(a.specifier),importedName:Hn(a.imported_name),localName:Hn(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:Hn(a.local_name),specifier:Hn(a.specifier),importedName:Hn(a.imported_name)};o(a)?.exports.push(c)}return[...i.values()]}var Ob,Db,Pb,Mb,$b,Lb,Fb,Hn,Ub=v(()=>{"use strict";vn();Ob=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Db="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Pb="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Mb="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",$b="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Lb="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Fb="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(jb,"factRows");Hn=s(e=>e==null?null:String(e),"str");s(Hb,"assembleFacts")});function ta(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 Bb,zi,Gb=v(()=>{"use strict";ea();Er();Ub();od();s(ta,"toNodeRow");Bb=400,zi=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Qs(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(td)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,i){this.db.transaction(()=>{this.deleteFileGraph(t.path);let a=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)a.run(l.nodeKey,l.kind,l.name,l.qualifiedName,l.filePath,l.language,l.startLine,l.endLine,l.startByte,l.endByte,l.signature,l.doc),c.run(l.nodeKey,r.get(l.nodeKey)??l.name);if(i){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let m of i.contains)l.run(m.srcKey,m.dstKey,m.kind);let d=jb(t.path,i),u=this.db.prepare(Db);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Pb);for(let m of d.imports)p.run(...m);let f=this.db.prepare(Mb);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 Hb(t,this.db.prepare($b).all(),this.db.prepare(Lb).all(),this.db.prepare(Fb).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let i of t)r.run(i.srcKey,i.dstKey,i.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?ta(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ta)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ta)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ta)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=$y(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
745
|
+
[Y/n]: `;if(!await(e.prompt??hD)(e.out,g))return{target:r,action:"skip",status:"skipped",detail:eu}}let d=o.hooks?.[t.event]??[],u;if(l!==null)u=d.map((g,y)=>y!==l.group?g:{...g,hooks:(g.hooks??[]).map((_,b)=>b===l.hook?{..._,command:t.command}:_)});else{let g={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]};u=[...d,g]}let p={...o,hooks:{...o.hooks??{},[t.event]:u}},f=JSON.stringify(p,null,2)+`
|
|
746
|
+
`,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 V(n,f,384)}catch(g){return{target:r,action:"merge",status:"failed",detail:`write: ${ru(g)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n+m}}function pD(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function iu(e,t){let n=e.launch??xe({entryPath:ge(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=it(n);return uD(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:pD(t),supersedes:t.supersedes,skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return Ms(i)?`${o}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:Or(i)?`${o}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:o},"skipDetail"),consentDescription:t.consentDescription})}async function ou(e){let t=[];for(let n of at)t.push(await iu(e,n));return t}function fD(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i=0;i<r.length;i++){let o=r[i];if(!qi(o))continue;let a=o.hooks;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=a[c];if(!qi(l))continue;let d=l.command;if(typeof d=="string"&&n.test(d))return{group:i,hook:c,command:d}}}return null}function mD(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!qi(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!qi(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function hD(e,t){e.write(t);let n=Nb.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function qi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ru(e){return e instanceof Error?e.message:String(e)}var su=w(()=>{"use strict";we();Kt();ct();nu();ct();s(uD,"mergeClaudeHook");s(pD,"targetKeyFor");s(iu,"mergeSubcommandHook");s(ou,"mergeAllSubcommandHooks");s(fD,"findHookEntry");s(mD,"findExistingHookCommand");s(hD,"promptYesNo");s(qi,"isObject");s(ru,"errMessage")});function au(){return{ultracode:!1,planMode:!1,autoMode:!1}}var cu=w(()=>{"use strict";s(au,"newModeState")});import{createReadStream as _D,existsSync as bD}from"node:fs";import{stat as wD}from"node:fs/promises";import{createInterface as vD}from"node:readline";async function lu(e){if(!e||!bD(e))return null;let t;try{t=await wD(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=_D(e,{encoding:"utf-8"}),l=vD({input:c});l.on("line",d=>{let u=d.trim();if(u){o++;try{let p=JSON.parse(u),f=p.message?.usage;if(!f)return;let m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=m??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(i+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:o,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var Pb=w(()=>{"use strict";s(lu,"summariseTranscript")});var Mb=w(()=>{"use strict"});function Ji(e){if(!e)return null;let t=null;for(let n of e.matchAll(SD)){let r=n[1].toLowerCase();kD.has(r)&&(t=r)}return t}var kD,SD,Js=w(()=>{"use strict";kD=new Set(["low","medium","high","xhigh","max"]),SD=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(Ji,"detectEffortLevel")});import{createReadStream as xD,existsSync as ED,readdirSync as TD}from"node:fs";import{basename as Fb,dirname as RD,join as $b}from"node:path";import{createInterface as AD}from"node:readline";function Hb(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!ND.test(n)||e.ids.includes(n)||e.ids.length>=jb||e.ids.push(n)}function OD(e,t){if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string"||!r.name.startsWith(Ys)||ID.has(r.name))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?Hb(e,i.session_id):r.name===`${Ys}announce_session`&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function DD(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 PD(e,t){if(!(e.pendingAnnounce.size===0||!Array.isArray(t)))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_result"||typeof r.tool_use_id!="string"||!e.pendingAnnounce.delete(r.tool_use_id))continue;let i=DD(r.content),o=null;try{let a=JSON.parse(i);a&&a.ok===!0&&(o=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(i);o=a?a[1]:null}Hb(e,o)}}function Lr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function $D(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=MD[r.name];if(!i||!r.input||typeof r.input!="object")continue;let o=r.input[i];typeof o=="string"&&o.length>0&&t.push(o)}return t}function Xs(e){let t=Fb(e).replace(/\.jsonl$/,""),n=$b(RD(e),t,"subagents"),r;try{r=TD(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>$b(n,i))}async function Lb(e,t,n,r,i,o){ED(e)&&await new Promise(a=>{let c=xD(e,{encoding:"utf-8"}),l=AD({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"){PD(o,f.message.content);return}if(f.message?.role!=="assistant")return;OD(o,f.message.content);let m=typeof f.message.id=="string"&&f.message.id?f.message.id:null,g=typeof f.requestId=="string"&&f.requestId?f.requestId:null,y=m??g??`${e}#${d}`,_=$D(f.message.content),b=r.get(y);if(b){for(let E of _)b.edited_paths.includes(E)||b.edited_paths.push(E);return}if(n.has(y))return;n.add(y);let v=f.message.usage??{},x=typeof f.timestamp=="string"?Date.parse(f.timestamp):Number.NaN,C=typeof f.message.model=="string"&&f.message.model?f.message.model:"",k={ts:Number.isFinite(x)?x:0,model:C||"<unknown>",synthetic:C===CD,input_tokens:Lr(v.input_tokens),output_tokens:Lr(v.output_tokens),cache_read_tokens:Lr(v.cache_read_input_tokens),cache_creation_tokens:Lr(v.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Lr(v.cache_creation?.ephemeral_1h_input_tokens),Lr(v.cache_creation_input_tokens)),sidechain:f.isSidechain===!0,stream:t,edited_paths:_,cwd:typeof f.cwd=="string"&&f.cwd?f.cwd:null};r.set(y,k),i.push(k)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function du(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function Yi(e){let t=new Set,n=new Map,r=[],i=e?Xs(e):[],o={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:i,coordination_ids:[]};let a=[];await Lb(e,Bn,t,n,a,o),du(a),r.push(...a);for(let c of i){let l=[],d=Fb(c).replace(/\.jsonl$/,"");o.pendingAnnounce.clear(),await Lb(c,d,t,n,l,o),du(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:i,coordination_ids:o.ids}}var Bn,CD,Ys,ID,ND,jb,MD,Zs=w(()=>{"use strict";Bn="main",CD="<synthetic>",Ys="mcp__maind__",ID=new Set([`${Ys}get_session_analysis`,`${Ys}get_session_cost_context`]),ND=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,jb=32;s(Hb,"addCoordinationId");s(OD,"noteCoordinationUse");s(DD,"resultText");s(PD,"noteAnnounceResult");MD={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(Lr,"num");s($D,"editedPathsOf");s(Xs,"subagentFilesOf");s(Lb,"readStream");s(du,"fillTimestamps");s(Yi,"collectTurns")});import{createReadStream as Ub,existsSync as LD}from"node:fs";import{createInterface as Bb}from"node:readline";function GD(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,a=e.get(o);if(!a){e.set(o,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function Qs(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function WD(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
747
|
+
`)}function VD(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function zD(e,t,n){return FD.test(e)?{polarity:-1,magnitude:Fr.rework,kind:"rework"}:n&&jD.test(e)?{polarity:-1,magnitude:Fr.correction,kind:"correction"}:HD.test(e)?{polarity:1,magnitude:Fr.acceptance,kind:"acceptance"}:t!==null&&VD(t,e)?{polarity:-1,magnitude:Fr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function qD(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:Kb,behaviour_measured:!0}}async function JD(e,t){for(let n of Xs(e))await new Promise(r=>{let i=Bb({input:Ub(n,{encoding:"utf-8"})});i.on("line",o=>{let a=o.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of Qs(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(ea))continue;let d=l.name.slice(ea.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function uu(e,t={}){let n=qD("");if(!e||!LD(e))return n;let r=t.turns??(await Yi(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(m=>{let g=Ub(e,{encoding:"utf-8"}),y=Bb({input:g}),_=s(b=>{let v=b.trim();if(!v)return;let x;try{x=JSON.parse(v)}catch{return}if(n.lines_seen++,!n.session_id){let j=x.sessionId??x.session_id;typeof j=="string"&&j&&(n.session_id=j)}x.type==="ai-title"&&typeof x.aiTitle=="string"&&x.aiTitle&&(n.ai_title=x.aiTitle),typeof x.slug=="string"&&x.slug&&(n.session_slug=x.slug);let C=x.message?.role,k=x.isSidechain===!0;if(C==="assistant")for(let j of Qs(x.message?.content)){if(j.type!=="tool_use"||typeof j.name!="string"||!j.name.startsWith(ea))continue;let W=j.name.slice(ea.length);W&&(n.maind_tool_calls??={},n.maind_tool_calls[W]=(n.maind_tool_calls[W]??0)+1)}if(k)return;if(C==="assistant"){let j=Qs(x.message?.content),W=!1;for(let ut of j)ut.type==="tool_use"&&(n.tool_calls++,W=!0,ut.name==="AskUserQuestion"&&n.agent_questions++);c=W;return}if(C!=="user")return;let E=Qs(x.message?.content),P=WD(E);if(P.includes(UD)){n.interrupts++,i.push({polarity:-1,magnitude:Fr.interrupt,kind:"interrupt"});return}if(E.some(j=>j.type==="tool_result"&&j.is_error===!0&&typeof j.content=="string"&&j.content.includes(BD))){n.tool_denials++,i.push({polarity:-1,magnitude:Fr.denial,kind:"denial"});return}if(E.some(j=>j.type==="tool_result")||!P.trim())return;n.user_turns++,n.user_chars+=P.length;let N=Ji(P);N&&(a=N);let D=zD(P,l,c);l=P,D.kind==="correction"?n.corrections++:D.kind==="rework"?n.reworks++:D.kind==="repeat"?n.repeated_instructions++:D.kind==="acceptance"&&n.acceptances++,D.polarity!==0&&i.push(D),c=!1},"processLine");y.on("line",b=>{try{_(b)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await JD(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||GD(o,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...o.values()].sort((m,g)=>m.first_ts-g.first_ts||m.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return i.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*KD+m.polarity*m.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=y,g>0&&i[g-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var ea,Kb,FD,jD,HD,UD,BD,KD,Fr,Gb=w(()=>{"use strict";Js();Zs();ea="mcp__maind__",Kb="2026-10-01",FD=/(\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,jD=/(\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,HD=/(\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,UD="[Request interrupted by user",BD="The user doesn't want to proceed with this tool use",KD=.7,Fr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(GD,"bumpModel");s(Qs,"asBlocks");s(WD,"textOf");s(VD,"isRepeat");s(zD,"classifyGenuine");s(qD,"emptyAnalysis");s(JD,"tallySubagentMaindCalls");s(uu,"analyzeSession")});function pu(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 fu(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 mu(e,t,n,r="unknown",i){let o={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...c}=n;o.session_span={...t,...c}}else o.session_span=t;return o}var Wb=w(()=>{"use strict";s(pu,"parseIngestResponse");s(fu,"describeSliceVerdict");s(mu,"ingestBody")});import{isAbsolute as Vb,relative as YD,resolve as zb,sep as qb}from"node:path";function Jb(e){return e>na[1]?"above_272k":e>na[0]?"band_200k_272k":"standard"}function Yb(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ta(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Xi(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=ta(d.from);typeof d.object_id!="string"||!hu.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ta(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=ta(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:ta(c.to)})}let o=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!hu.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&hu.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:o}}function ra(e,t){if(!Vb(e))return null;let n=YD(zb(t),zb(e));return!n||n==="."||n.startsWith("..")||Vb(n)?null:qb==="/"?n:n.split(qb).join("/")}function ZD(e,t){return t===""||e===t||e.startsWith(t+"/")}function yu(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Xb(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function _u(e,t){for(let n of Xb(t))if(ZD(e,n.path_prefix))return n.object_id;return null}function QD(e,t){for(let n of Xb(t))if(yu(e,n.path_prefix))return n.object_id;return null}function gu(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Zb(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>_u(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>gu(i,u));if(c.length)return c.sort((u,p)=>p.from-u.from||u.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(u=>gu(i,u));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>gu(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>yu(f.path_prefix,u))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=QD(f.path_prefix,o);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function bu(e,t,n){let r=t?.anchors??[],i=n.repoRoot,o=n.relativize??(i?_=>ra(_,i):null),a=s(_=>{if(!o)return[];let b=[];for(let v of _.edited_paths){let x=o(v);x!==null&&!b.includes(x)&&b.push(x)}return b},"relOf"),c=s(_=>{for(let b of _){let v=_u(b,r);if(v)return{object_id:v,rel:b}}return null},"firstAnchoredEdit"),l=new Map;for(let _ of e){let b=l.get(_.stream)??[];b.push(_),l.set(_.stream,b)}let d=[...l.entries()].sort(([_],[b])=>_===Bn?-1:b===Bn?1:0),u=[],p=s(_=>{let b=null;for(let v of u){if(v.ts>_&&_>0)break;b=v.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let v=b.map((C,k)=>({t:C,i:k,rels:a(C)})).sort((C,k)=>C.t.ts-k.t.ts||C.i-k.i),x=null;for(let C of v){let k=c(C.rels);if(k){x=k;break}}!x&&_!==Bn&&v.length&&(x=p(v[0].t.ts));for(let C of v){let k=c(C.rels);k&&(x=k),_===Bn&&u.push({ts:C.t.ts,seg:x});let E=C.t;if(E.input_tokens+E.output_tokens+E.cache_read_tokens+E.cache_creation_tokens===0)continue;let S=Zb(E,C.rels,x,t),N=Jb(E.input_tokens+E.cache_read_tokens+E.cache_creation_tokens),D=Yb(E.model),j=`${S.object_id??""}|${S.source}|${D}|${N}`,W=f.get(j);W||(W={object_id:S.object_id,attribution_source:S.source,model:D,context_tier:N,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},f.set(j,W)),W.input_tokens+=E.input_tokens,W.output_tokens+=E.output_tokens,W.cache_read_tokens+=E.cache_read_tokens,W.cache_creation_tokens+=E.cache_creation_tokens,W.cache_creation_1h_tokens+=E.cache_creation_1h_tokens,W.turns+=1,E.ts>0&&((W.firstMs===0||E.ts<W.firstMs)&&(W.firstMs=E.ts),E.ts>W.lastMs&&(W.lastMs=E.ts))}}let m=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:v,...x}=_;x.first_ts=new Date(b>0?b:m).toISOString(),x.last_ts=new Date(v>0?v:m).toISOString(),g.push(x)}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 na,XD,hu,wu=w(()=>{"use strict";Zs();na=[2e5,272e3];s(Jb,"contextTierOf");s(Yb,"normalizeModelId");XD=na[0],hu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(ta,"msOf");s(Xi,"parseCostContext");s(ra,"toRepoRelative");s(ZD,"underPrefix");s(yu,"prefixesOverlap");s(Xb,"sortedAnchors");s(_u,"anchorFor");s(QD,"bestAnchorOverlapping");s(gu,"inWindow");s(Zb,"assignTurn");s(bu,"sliceSession")});import{mkdirSync as eP,readFileSync as tP,renameSync as nP,writeFileSync as rP}from"node:fs";import{dirname as iP,isAbsolute as ia,sep as vu}from"node:path";function oP(e){let t=e.split(vu).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function sP(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function ku(e){let t=new Map,n=s(u=>{let p=t.get(u);if(p!==void 0)return p;let f=e.keyOfRoot(u);return t.set(u,f),f},"keyOf"),r=new Map,i=s(u=>{let p=r.get(u);if(p!==void 0)return p;let f=e.gitRoot(u);return r.set(u,f),f},"gitRoot"),o=new Map,a=[...(e.known??new Map).entries()].filter(([u])=>ia(u)).sort((u,p)=>p[0].length-u[0].length),c=new Map,l=s(u=>{if(!e.isDir)return null;let p=c.get(u);if(p!==void 0)return p;let f=d(u);return c.set(u,f),f},"byConvention"),d=s(u=>{if(!e.isDir)return null;let p=u.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let g=p.slice(0,f-1).join("/")||"/",y=p[f-1];for(let _=y.lastIndexOf("-");_>0;_=y.lastIndexOf("-",_-1)){let b=`${g==="/"?"":g}/${y.slice(0,_)}`;if(e.isDir(b)&&i(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!ia(u))return null;let p=u.split(vu).join("/"),f=oP(p),m=i(f);if(m){let g=n(m);return o.set(m,g),{root:m,key:g}}for(let[g,y]of a)if(!(!sP(p,g)||p===g)&&!(e.isDir&&e.isDir(g)))return{root:g,key:y};return l(f)},seenLive(){return[...o.entries()].map(([u,p])=>({root:u,key:p}))}}}function Su(e,t){let n=new Map;for(let a of e){let c=new Map;for(let l of a.edited_paths){let d=t.of(l);!d||!d.key||c.set(d.key,Math.max(c.get(d.key)??0,d.root.length))}for(let[l,d]of c){let u=n.get(l)??{turns:0,depth:0};u.turns+=1,u.depth=Math.max(u.depth,d),n.set(l,u)}}let r=null,i=0,o=0;for(let[a,c]of n)(c.turns>i||c.turns===i&&(c.depth>o||c.depth===o&&r!==null&&a<r))&&(r=a,i=c.turns,o=c.depth);return r}function xu(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:ra(n.split(vu).join("/"),r.root)}}function tw(e){try{let t=JSON.parse(tP(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 Zi(e){let t=new Map,n=tw(e);for(let[r,i]of Object.entries(n.checkouts)){if(!ia(r)||!i||typeof i!="object")continue;let o=typeof i.project_key=="string"&&ew.test(i.project_key)?i.project_key:null;t.set(r,o)}return t}function Qi(e,t,n=Date.now()){try{let r=tw(e),i=new Date(n).toISOString(),o=!1;for(let c of t){if(!ia(c.root))continue;let l=c.key&&ew.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>aP)&&(r.checkouts[c.root]={project_key:l,seen_at:i},o=!0)}for(let[c,l]of Object.entries(r.checkouts)){let d=Date.parse(l?.seen_at??"");(!Number.isFinite(d)||n-d>Qb)&&(delete r.checkouts[c],o=!0)}if(!o)return;eP(iP(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;rP(a,JSON.stringify(r),{mode:384}),nP(a,e)}catch{}}var Qb,aP,ew,nw=w(()=>{"use strict";wu();s(oP,"dirOf");s(sP,"within");s(ku,"createCheckoutResolver");s(Su,"dominantProjectKey");s(xu,"relativizerFor");Qb=90*24*60*60*1e3,aP=60*60*1e3,ew=/^[a-f0-9]{64}$/;s(tw,"readMemory");s(Zi,"loadCheckoutMemory");s(Qi,"rememberCheckouts")});import{homedir as cP}from"node:os";import{join as lP}from"node:path";var dP,Eu=w(()=>{"use strict";dP=lP(cP(),".codex","sessions")});var rw=w(()=>{"use strict";Eu()});var iw=w(()=>{"use strict"});import{createReadStream as pP,existsSync as fP}from"node:fs";import{createInterface as mP}from"node:readline";function ow(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function yP(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
748
|
+
`)}function cw(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 _P(e){let t=e.message?.role;if(t==="assistant")return{holder:ow(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=ow(e.message?.content),r=yP(n);return r.includes(hP)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(gP))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Tu(e){let t=cw("");if(!e||!fP(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let d=pP(e,{encoding:"utf-8"}),u=mP({input:d}),p=s(f=>{let m=f.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let b=g.sessionId??g.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||o!==null&&y<o)return;let _=_P(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,o!==null){let b=y-o;a==="agent"?i+=b:b>=sw*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<aw&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(b/1e3)}))}o=y,a=_.holder}},"processLine");u.on("line",f=>{try{p(f)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var hP,gP,sw,aw,lw=w(()=>{"use strict";hP="[Request interrupted by user",gP="The user doesn't want to proceed with this tool use",sw=60,aw=200;s(ow,"asBlocks");s(yP,"textOf");s(cw,"emptySpan");s(_P,"classify");s(Tu,"analyzeSpan")});import{createReadStream as bP,existsSync as wP}from"node:fs";import{createInterface as vP}from"node:readline";function SP(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function oa(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function xP(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
|
|
749
|
+
`)}return""}async function Ru(e,t={}){if(!e||!wP(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:au(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:au(),a=t.start??0;return await new Promise(c=>{let l=bP(e,{encoding:"utf-8",start:t.start??0}),d=vP({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=kP[m.attachment.type];b&&(o[SP(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=xP(m.message?.content),v=Ji(b);v&&(i=v);let x={session_id:g,ts:y,text:b,effort_directive:v};n.push({kind:"user",...x});return}if(_==="assistant"){let b=m.message?.usage,v=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,x=typeof m.requestId=="string"&&m.requestId?m.requestId:null,C=v??x,k=C!==null&&r.has(C);C!==null&&!k&&r.add(C);let E={session_id:g,ts:y,model:m.message?.model??null,input_tokens:k?0:oa(b?.input_tokens),output_tokens:k?0:oa(b?.output_tokens),cache_read_input_tokens:k?0:oa(b?.cache_read_input_tokens),cache_creation_input_tokens:k?0:oa(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...o.ultracode?{ultracode:!0}:{},...o.planMode?{planMode:!0}:{},...o.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...E})}});let u=s(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...o},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var kP,dw=w(()=>{"use strict";Js();cu();kP={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(SP,"modeFlagKey");s(oa,"num");s(xP,"extractUserText");s(Ru,"streamTranscript")});var uw=w(()=>{"use strict"});import{homedir as EP}from"node:os";import{join as TP}from"node:path";function Cu(e){return e.replace(/[/.]/g,"-")}var RP,Au,pw=w(()=>{"use strict";RP=EP(),Au=TP(RP,".claude","projects");s(Cu,"projectPathFromCwd")});var Kn=w(()=>{"use strict";cu();Pb();Mb();Gb();Wb();Zs();nw();Eu();rw();wu();iw();lw();dw();Js();uw();pw()});import{mkdir as AP,readFile as CP,writeFile as IP,rename as NP}from"node:fs/promises";import{existsSync as mw}from"node:fs";import{homedir as OP}from"node:os";import{join as hw}from"node:path";function fw(){return{config:null,sessions:{},pending_metrics:[]}}async function Z(){if(!mw(sa))return fw();try{let e=await CP(sa,"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)}
|
|
750
|
+
`),fw()}}async function lt(e){mw(ve)||await AP(ve,{recursive:!0,mode:448});let t=`${sa}.${process.pid}.tmp`;await IP(t,JSON.stringify(e,null,2),{mode:384}),await NP(t,sa)}function Iu(e){return e.thresholds??e.config?.thresholds??DP}var ve,sa,DP,Ie=w(()=>{"use strict";ve=hw(OP(),".maind"),sa=hw(ve,"state.json"),DP={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(fw,"emptyState");s(Z,"loadState");s(lt,"saveState");s(Iu,"resolveThresholds")});import{execFileSync as PP}from"node:child_process";import{existsSync as MP}from"node:fs";import{join as gw}from"node:path";function aa(e=$P()){return e?.checkout_memory===!0}function $P(){try{return ee()}catch{return null}}function LP(e){try{let t=PP("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?Nr(t):null}catch{return null}}function yw(e,t){try{if(!(t.isCheckoutRoot??(i=>MP(gw(i,".git"))))(e)||Zi(t.memoryPath).has(e))return!1;let r=(t.keyOf??LP)(e);return Qi(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var jr,ca=w(()=>{"use strict";Kn();Ce();Ie();he();jr=gw(ve,"checkout-roots.json");s(aa,"checkoutMemoryAllowed");s($P,"safeReadConfig");s(LP,"originKey");s(yw,"rememberEditCheckout")});import{existsSync as UP}from"node:fs";import{dirname as BP,join as bw}from"node:path";function Jt(e,t=UP){let n=e;for(;;){if(t(bw(n,".git")))return n;let r=BP(n);if(r===n)return null;n=r}}var qt,la=w(()=>{"use strict";qt=bw(".maind","code-index.sqlite");s(Jt,"findRepoRoot")});function da(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function Xt(e){return e+1}function ua(e){return(e.text.split(`
|
|
751
|
+
`,1)[0]??"").trim().slice(0,200)}function nM(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 rM(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=nM(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function $u(e,t,n,r){for(let i of rM(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function eo(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let i=n;for(;i?.type==="member_expression";)i=i.childForFieldName("object");return i?.type==="this"?{name:t,receiver:"this.*"}:i?.type==="identifier"?{name:t,receiver:`${i.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function Yt(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 Yt(t.childForFieldName("name"));case"parenthesized_type":return Yt(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?Yt(n[0]):"#"}default:return"#"}}function oM(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Lu(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 to(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),o=Yt(n.childForFieldName("type"))??Lu(i)??(oM(i)?"#":null);o&&t.set(r.text,o)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=Yt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function Zt(e,t,n,r,i={locals:to(n)}){let o=new Set,a=s(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(o.has(d))return;o.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...iM]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(eo(l.childForFieldName("function")));else if(l.type==="new_expression")a(eo(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(eo(d))}}var iM,pa=w(()=>{"use strict";s(da,"newResult");s(Xt,"line1");s(ua,"signatureOf");s(nM,"calleeName");s(rM,"collectCallTargets");s($u,"addCallRefs");s(eo,"calleeRef");iM=["jsx_opening_element","jsx_self_closing_element"];s(Yt,"typeNameOf");s(oM,"isMethodCallResult");s(Lu,"newTypeOf");s(to,"collectTypeHints");s(Zt,"addTsRefs")});function Iw(e,t){let n=da();for(let r of e.namedChildren)sM(r,t,n);return n}function Nw(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function sM(e,t,n){let r=Nw(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??cM(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=fa(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&$u(n,o.nodeKey,a,Cw);return}case"class_definition":aM(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=fa(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function aM(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=fa(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=Nw(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=fa(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&$u(n,p.nodeKey,f,Cw)}}function fa(e,t,n,r,i){return{nodeKey:nt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Xt(e.startPosition.row),endLine:Xt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:ua(e),doc:null}}function cM(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var Cw,Ow=w(()=>{"use strict";Sn();pa();Cw="call";s(Iw,"extractPython");s(Nw,"unwrapDecorated");s(sM,"handleTopLevel");s(aM,"addClass");s(fa,"makeNode");s(cM,"firstDottedName")});function Pw(e,t){let n=da(),r=t.language!=="typescript";for(let i of e.namedChildren)dM(i,t,n,r);return fM(e,t,n),n}function lM(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function dM(e,t,n,r){if(e.type==="export_statement"&&uM(e,t,n,r))return;let i=lM(e),o=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":pM(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=Dw(i,t,n,"function",r);o&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=hM(i,t,n,r);o&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":Fu(i,t,n,"interface");return;case"type_alias_declaration":Fu(i,t,n,"type_alias");return;case"enum_declaration":Fu(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of i.namedChildren){if(a.type!=="variable_declarator")continue;let c=a.childForFieldName("name"),l=a.childForFieldName("value");if(!c||c.type!=="identifier"){l&&Zt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";Dw(a,t,n,d?"function":"variable",r,c,l)}return}default:Zt(n,t.moduleKey,i,r);return}}function uM(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=Hu(e.childForFieldName("source")),o=e.namedChildren.find(l=>l.type==="export_clause"),a=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),o)for(let l of o.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(a){let l=a.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(o){for(let l of o.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):Zt(n,t.moduleKey,c,r),!0):!1}function pM(e,t,n){let r=Hu(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),o=[],a=s((c,l)=>{o.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")a("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&a("*",l)}else if(c.type==="named_imports")for(let l of c.namedChildren.filter(d=>d.type==="import_specifier")){let d=l.childForFieldName("name")?.text;d&&a(d,l.childForFieldName("alias")?.text??d)}o.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...o)}function fM(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,o=i?.type==="string"?Hu(i):null;if(o===null)continue;let c=mM(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:o,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:o,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:o})}}function mM(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function Dw(e,t,n,r,i,o,a){let l=(o??e.childForFieldName("name"))?.text;if(!l)return null;let d=ma(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;Zt(n,d.nodeKey,u,i,{locals:to(e)})}else a&&Zt(n,d.nodeKey,a,i);return d}function Fu(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=ma(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function hM(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let o=ma(e,t,i,i,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of a?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(p=>({kind:"implements",ref:ju(p)})):[{kind:"extends",ref:ju(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:f}of u)f&&n.refs.push({fromKey:o.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let c=e.childForFieldName("body");if(!c)return o;let l=gM(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&Zt(n,o.nodeKey,g,r,{locals:to(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,f=ma(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:o.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&Zt(n,f.nodeKey,m,r,{locals:to(d),thisFields:l})}return o}function gM(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),i=Yt(n.childForFieldName("type"))??Lu(n.childForFieldName("value"));r&&i&&t.set(r.text,i)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(a=>a.type==="accessibility_modifier"||a.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),o=Yt(r.childForFieldName("type"));i?.type==="identifier"&&o&&t.set(i.text,o)}return t}function ma(e,t,n,r,i){return{nodeKey:nt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Xt(e.startPosition.row),endLine:Xt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:ua(e),doc:null}}function ju(e){if(!e)return null;switch(e.type){case"generic_type":return ju(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 eo(e);default:return null}}function Hu(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var Mw=w(()=>{"use strict";Sn();pa();s(Pw,"extractTypescript");s(lM,"unwrapExport");s(dM,"handleTopLevel");s(uM,"handleExportForm");s(pM,"addImport");s(fM,"collectDynamicImports");s(mM,"enclosingDeclarator");s(Dw,"addFunctionLike");s(Fu,"addSimpleNamed");s(hM,"addClass");s(gM,"classFieldTypes");s(ma,"makeNode");s(ju,"heritageRef");s(Hu,"stringValue")});import{createRequire as yM}from"node:module";import{join as _M}from"node:path";function Fw(e,t){return t?_M(t,$w[e]):yM(import.meta.url).resolve(`tree-sitter-wasms/out/${$w[e]}`)}var $w,Lw,jw=w(()=>{"use strict";$w={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Lw="tree-sitter.wasm";s(Fw,"grammarPath")});import{join as bM}from"node:path";import Uu from"web-tree-sitter";var wM,ha,Hw=w(()=>{"use strict";Sn();ts();Ow();Mw();pa();jw();wM=["typescript","tsx","javascript","python"],ha=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Uu.init(this.assetDir?{locateFile:s(t=>bM(this.assetDir,t||Lw),"locateFile")}:void 0),this.parser=new Uu,this.initialized=!0)}supports(t){return wM.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=o.rootNode,c=tt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Xt(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?Iw(a,d):Pw(a,d);return o.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Uu.Language.load(Fw(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as vM}from"node:module";function Uw(){return ga("node:sqlite")}function Hr(){if(no)return no;try{let{DatabaseSync:e}=Uw(),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(),no={ok:!0}}finally{t.close()}}catch(e){no={ok:!1,reason:e instanceof Error?e.message:String(e)}}return no}function kM(e){let{DatabaseSync:t}=Uw(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function SM(e){let t=ga("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 Bw(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function ya(e){let t=Bw(),n=s(()=>{let{DatabaseSync:i}=ga("node:sqlite"),o=new i(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>o.prepare(a),"prepare"),exec:s(a=>o.exec(a),"exec"),close:s(()=>o.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let i=ga("better-sqlite3"),o=new i(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>o.prepare(a),"prepare"),exec:s(a=>{o.exec(a)},"exec"),close:s(()=>{o.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(i){try{return r()}catch(o){let a=s(c=>c instanceof Error?c.message:String(c),"reason");throw new Error(`no usable SQLite backend for a read-only open: node:sqlite (${a(i)}); better-sqlite3 (${a(o)})`)}}}function _a(e){let t=Bw(),n=s(i=>{let o=i==="node:sqlite"?kM(e):SM(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=Hr();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=Hr();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var ga,no,ba=w(()=>{"use strict";ga=vM(import.meta.url);s(Uw,"loadBuiltin");no=null;s(Hr,"probeBuiltinSqlite");s(kM,"openBuiltin");s(SM,"openBetter");s(Bw,"backendOverride");s(ya,"openSqliteReadOnly");s(_a,"openSqliteDatabase")});function Yw(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 Xw(e,t,n,r){let i=new Map;for(let a of e)i.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let o=s(a=>i.get(String(a.file_path)),"entry");for(let a of t)o(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Wn(a.receiver),receiverType:Wn(a.receiver_type)});for(let a of n){let c=o(a);if(!c)continue;let l={fromModuleKey:tt(c.filePath),specifier:String(a.specifier),importedName:Wn(a.imported_name),localName:Wn(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:Wn(a.local_name),specifier:Wn(a.specifier),importedName:Wn(a.imported_name)};o(a)?.exports.push(c)}return[...i.values()]}var Kw,Gw,Ww,Vw,zw,qw,Jw,Wn,Zw=w(()=>{"use strict";Sn();Kw=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Gw="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Ww="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Vw="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",zw="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",qw="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Jw="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(Yw,"factRows");Wn=s(e=>e==null?null:String(e),"str");s(Xw,"assembleFacts")});function wa(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 Qw,ro,ev=w(()=>{"use strict";ba();Er();Zw();_d();s(wa,"toNodeRow");Qw=400,ro=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=_a(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(md)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,i){this.db.transaction(()=>{this.deleteFileGraph(t.path);let a=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)a.run(l.nodeKey,l.kind,l.name,l.qualifiedName,l.filePath,l.language,l.startLine,l.endLine,l.startByte,l.endByte,l.signature,l.doc),c.run(l.nodeKey,r.get(l.nodeKey)??l.name);if(i){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let m of i.contains)l.run(m.srcKey,m.dstKey,m.kind);let d=Yw(t.path,i),u=this.db.prepare(Gw);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Ww);for(let m of d.imports)p.run(...m);let f=this.db.prepare(Vw);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 Xw(t,this.db.prepare(zw).all(),this.db.prepare(qw).all(),this.db.prepare(Jw).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let i of t)r.run(i.srcKey,i.dstKey,i.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?wa(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(wa)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(wa)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(wa)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=a_(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
738
752
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
739
753
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
740
754
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
@@ -747,7 +761,7 @@ ${t.consentDescription}
|
|
|
747
761
|
FROM nodes n
|
|
748
762
|
WHERE n.kind = 'module'
|
|
749
763
|
ORDER BY imports_in DESC, symbol_count DESC
|
|
750
|
-
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(o=>o.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let o=0;o<n.length;o+=
|
|
764
|
+
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(o=>o.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let o=0;o<n.length;o+=Qw)for(let a of n.slice(o,o+Qw))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let o of Kw)this.db.prepare(o).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
751
765
|
node_key, kind, name, qualified_name, file_path, language,
|
|
752
766
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
753
767
|
) 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)
|
|
@@ -757,48 +771,44 @@ ${t.consentDescription}
|
|
|
757
771
|
content_hash = excluded.content_hash,
|
|
758
772
|
mtime_ms = excluded.mtime_ms,
|
|
759
773
|
size = excluded.size,
|
|
760
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as iD}from"node:crypto";function Fr(e){return iD("sha256").update(e,"utf8").digest("hex")}function Kb(e){return{node_key_hash:Fr(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Fr(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Fr(e.signature):null}}function Wb(e){return{src_key_hash:Fr(e.srcKey),dst_key_hash:Fr(e.dstKey),kind:e.kind}}function Vb(e,t,n){return{node_key_hash:Fr(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var zb=v(()=>{"use strict";s(Fr,"sha256");s(Kb,"toCloudNode");s(Wb,"toCloudEdge");s(Vb,"toCloudEmbedding")});import{randomUUID as oD}from"node:crypto";function iu(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function qb(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Jb(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var jr,Hr,sD,ou=v(()=>{"use strict";Er();zb();jr=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Hr=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(xr),lastSyncedAt:qb(await this.store.getMeta(rd))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Kb),n=(await this.store.getAllEdges()).map(Wb),r=await this.store.getMeta(Ht)??jt,i=await this.store.getMeta(xr),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=oD(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},d=0,u=iu(t,this.chunk),p=iu(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(rd,String(Date.now())),i&&await this.store.setMeta(Py,i),{nodes:t.length,edges:n.length,pruned:Jb(g.nodes_deleted),edgesPruned:Jb(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Vb(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&o[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=iu(a,sD),l=0;for(let d of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:d}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(ys),n=await this.store.getMeta(_s),r=qb(await this.store.getMeta(bs));if(!t||!n||!r)throw new jr("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let o=i?.error;throw new jr(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},sD=250;s(iu,"chunkArray");s(qb,"numOrNull");s(Jb,"numOr0")});var au={};Q(au,{CodeIndexSync:()=>Hr,DEFAULT_DB_RELPATH:()=>su,SyncError:()=>jr,createCodeIndexSync:()=>cD,createNodeCodeIndex:()=>ra,openIndexReader:()=>lD,openSqliteDatabase:()=>Qs,openSqliteReadOnly:()=>Zs,probeBuiltinSqlite:()=>Lr});import{mkdirSync as aD}from"node:fs";import{posix as na}from"node:path";function ra(e){let t=e.dbPath??na.join(e.repoRoot,su);aD(na.dirname(t),{recursive:!0}),e.dbPath===void 0&&bi(na.dirname(t));let n=new zi(t),r=new Ys;return new Di({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function cD(e){let t=e.dbPath??na.join(e.repoRoot,su),n=e.projectKey??Rg(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 zi(t);return new Hr(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function lD(e){return pd(Zs(e).db)}var su,ia=v(()=>{"use strict";hl();Ab();sd();fd();Gb();ea();ou();Zo();ou();ea();su=".maind/code-index.sqlite";s(ra,"createNodeCodeIndex");s(cD,"createCodeIndexSync");s(lD,"openIndexReader")});import{execFileSync as Yb}from"node:child_process";import{existsSync as Xb,realpathSync as Zb}from"node:fs";import{createRequire as dD}from"node:module";import{basename as uD,dirname as pD,isAbsolute as Qb,join as fD,relative as ev,resolve as oa,sep as tv}from"node:path";function sa(){let e=Lr();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return dD(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 nv(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function Se(e=process.cwd()){try{let t=Yb("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 iv(e,t=Se(),n=process.cwd()){let r=Qb(e)?[e]:[oa(t,e),oa(n,e)];for(let i of r){let o=pD(i);if(!Xb(o))continue;let a;try{a=Zb(o)}catch{continue}let c=ov(a);if(c===null)continue;let l=ev(c,fD(a,uD(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(tv).join("/")}}return null}function Ur(e,t=Se(),n=process.cwd()){let r=Qb(e)?[e]:[oa(t,e),oa(n,e)];for(let i of r){if(!Xb(i))continue;let o;try{o=Zb(i)}catch{continue}let a=ov(o);if(a===null)continue;let c=ev(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(tv).join("/")}}return null}function ov(e){try{let t=Yb("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 sv(){return ra({repoRoot:Se()})}function av(e){return ra({repoRoot:e})}var rv,Zt=v(()=>{"use strict";ia();s(sa,"probeNativeStore");s(nv,"isNativeStoreUnavailable");rv="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(Se,"resolveRepoRoot");s(iv,"resolveRepoRootForPath");s(Ur,"resolveRepoRootForDir");s(ov,"gitToplevelOf");s(sv,"defaultEngineFactory");s(av,"engineForRoot")});async function Br(e){return xt("get_session_briefing",{tools:["claude-code"]},e)}async function xt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??qi,i=new AbortController,o=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:mD,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 cv(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let _=null;try{let b=JSON.parse(d);typeof b.result?.instructions=="string"&&(_=b.result.instructions)}catch{_=null}n.onInitialize(_)}if(!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(_=>_.text().catch(()=>"")).catch(()=>"");let p=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!p.ok)return null;let m=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await cv(p):await p.text();if(m.trim().length===0)return null;let g=JSON.parse(m);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(o)}}async function cv(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",a=s(()=>{if(i.length===0)return;let c=i.join(`
|
|
774
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as xM}from"node:crypto";function Ur(e){return xM("sha256").update(e,"utf8").digest("hex")}function tv(e){return{node_key_hash:Ur(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Ur(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Ur(e.signature):null}}function nv(e){return{src_key_hash:Ur(e.srcKey),dst_key_hash:Ur(e.dstKey),kind:e.kind}}function rv(e,t,n){return{node_key_hash:Ur(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var iv=w(()=>{"use strict";s(Ur,"sha256");s(tv,"toCloudNode");s(nv,"toCloudEdge");s(rv,"toCloudEmbedding")});import{randomUUID as EM}from"node:crypto";function Bu(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ov(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function sv(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Br,Kr,TM,Ku=w(()=>{"use strict";Er();iv();Br=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Kr=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(Sr),lastSyncedAt:ov(await this.store.getMeta(gd))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(tv),n=(await this.store.getAllEdges()).map(nv),r=await this.store.getMeta(Ht)??jt,i=await this.store.getMeta(Sr),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),c=EM(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},d=0,u=Bu(t,this.chunk),p=Bu(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(gd,String(Date.now())),i&&await this.store.setMeta(o_,i),{nodes:t.length,edges:n.length,pruned:sv(g.nodes_deleted),edgesPruned:sv(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>rv(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&o[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=Bu(a,TM),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(ks),n=await this.store.getMeta(Ss),r=ov(await this.store.getMeta(xs));if(!t||!n||!r)throw new Br("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let o=i?.error;throw new Br(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},TM=250;s(Bu,"chunkArray");s(ov,"numOrNull");s(sv,"numOr0")});var Wu={};X(Wu,{CodeIndexSync:()=>Kr,DEFAULT_DB_RELPATH:()=>Gu,SyncError:()=>Br,createCodeIndexSync:()=>AM,createNodeCodeIndex:()=>ka,openIndexReader:()=>CM,openSqliteDatabase:()=>_a,openSqliteReadOnly:()=>ya,probeBuiltinSqlite:()=>Hr});import{mkdirSync as RM}from"node:fs";import{posix as va}from"node:path";function ka(e){let t=e.dbPath??va.join(e.repoRoot,Gu);RM(va.dirname(t),{recursive:!0}),e.dbPath===void 0&&xi(va.dirname(t));let n=new ro(t),r=new ha;return new Fi({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function AM(e){let t=e.dbPath??va.join(e.repoRoot,Gu),n=e.projectKey??Zg(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 ro(t);return new Kr(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function CM(e){return Ed(ya(e).db)}var Gu,Sa=w(()=>{"use strict";Al();Hw();bd();Td();ev();ba();Ku();rs();Ku();ba();Gu=".maind/code-index.sqlite";s(ka,"createNodeCodeIndex");s(AM,"createCodeIndexSync");s(CM,"openIndexReader")});import{execFileSync as av}from"node:child_process";import{existsSync as cv,realpathSync as lv}from"node:fs";import{createRequire as IM}from"node:module";import{basename as NM,dirname as OM,isAbsolute as dv,join as DM,relative as uv,resolve as xa,sep as pv}from"node:path";function Ea(){let e=Hr();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return IM(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 fv(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 Ee(e=process.cwd()){try{let t=av("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 hv(e,t=Ee(),n=process.cwd()){let r=dv(e)?[e]:[xa(t,e),xa(n,e)];for(let i of r){let o=OM(i);if(!cv(o))continue;let a;try{a=lv(o)}catch{continue}let c=gv(a);if(c===null)continue;let l=uv(c,DM(a,NM(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(pv).join("/")}}return null}function Gr(e,t=Ee(),n=process.cwd()){let r=dv(e)?[e]:[xa(t,e),xa(n,e)];for(let i of r){if(!cv(i))continue;let o;try{o=lv(i)}catch{continue}let a=gv(o);if(a===null)continue;let c=uv(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(pv).join("/")}}return null}function gv(e){try{let t=av("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 yv(){return ka({repoRoot:Ee()})}function _v(e){return ka({repoRoot:e})}var mv,Qt=w(()=>{"use strict";Sa();s(Ea,"probeNativeStore");s(fv,"isNativeStoreUnavailable");mv="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(Ee,"resolveRepoRoot");s(hv,"resolveRepoRootForPath");s(Gr,"resolveRepoRootForDir");s(gv,"gitToplevelOf");s(yv,"defaultEngineFactory");s(_v,"engineForRoot")});async function Wr(e){return kt("get_session_briefing",{tools:["claude-code"]},e)}async function kt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??io,i=new AbortController,o=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:PM,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 bv(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let _=null;try{let b=JSON.parse(d);typeof b.result?.instructions=="string"&&(_=b.result.instructions)}catch{_=null}n.onInitialize(_)}if(!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(_=>_.text().catch(()=>"")).catch(()=>"");let p=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!p.ok)return null;let m=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await bv(p):await p.text();if(m.trim().length===0)return null;let g=JSON.parse(m);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(_=>_.type==="text"&&typeof _.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(o)}}async function bv(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",a=s(()=>{if(i.length===0)return;let c=i.join(`
|
|
761
775
|
`).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
762
|
-
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var
|
|
763
|
-
`,384)}var
|
|
776
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var io,PM,en=w(()=>{"use strict";io="https://mcp.maind.dev/mcp",PM="2025-06-18";s(Wr,"fetchSessionBriefing");s(kt,"fetchToolText");s(bv,"readSseMessage")});function wv(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 G(){let e=process.stdin;if(e.isTTY)return{};let t=[],n=0;return await new Promise(r=>{let i=!1,o,a=s(l=>{i||(i=!0,clearTimeout(o),r(l))},"settle"),c=s(l=>{clearTimeout(o),o=setTimeout(()=>{let d=n;setImmediate(()=>{i||n!==d||a(wv(t))})},l)},"arm");c(1e3),e.on("data",l=>{i||(t.push(typeof l=="string"?Buffer.from(l,"utf-8"):l),n+=1,c(200))}),e.on("end",()=>a(wv(t))),e.on("error",()=>a({}))})}function Vr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function je(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var ye=w(()=>{"use strict";s(wv,"parsePayload");s(G,"readHookInput");s(Vr,"transcriptPathOf");s(je,"toolFilePathOf")});function Vn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function zn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function oo(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function Ta(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Vu(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var so=w(()=>{"use strict";s(Vn,"denyPayload");s(zn,"advisoryPayload");s(oo,"postAdvisoryPayload");s(Ta,"postFailureAdvisoryPayload");s(Vu,"promptAdvisoryPayload")});function MM(e){return qn(e)&&/[\\/]\.claude[^\\/]*[\\/]projects[\\/]/.test(e)}function ao(e,t=process.env){return qn(e.cursor_version)?"cursor":MM(e.transcript_path)?"claude-code":qn(t.CURSOR_VERSION)?"cursor":qn(t.DEVIN_PROJECT_DIR)?"devin":qn(t.CLAUDE_PROJECT_DIR)||t.CLAUDECODE==="1"?"claude-code":"unknown"}function vv(e,t=process.env){return ao(e,t)==="cursor"}function tn(e){return e==="cursor"||e==="devin"}function qe(e,t=process.env){return tn(ao(e,t))}function $M(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 oe(e,t=process.env,n=ee){let r=ao(e,t);return{host:r,devinOutput:r==="devin"?$M(t,n()):!1}}function LM(e){switch(e.kind){case"text":return e.text;case"deny":return Vn(e.reason);case"context":switch(e.event){case"UserPromptSubmit":return Vu(e.text);case"PreToolUse":return zn(e.text);case"PostToolUse":return oo(e.text);case"PostToolUseFailure":return Ta(e.text)}}}function FM(e){return e.kind==="deny"?JSON.stringify({permission:"deny",user_message:e.reason,agent_message:e.reason}):null}function jM(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"?Vu(e.text):e.event==="PostToolUse"?oo(e.text):null}}function ce(e,t){switch(e.host){case"claude-code":case"unknown":return LM(t);case"cursor":return FM(t);case"devin":return e.devinOutput?jM(t):null}}function _e(e,t){let n=t.kind==="deny"?{kind:"deny",reason:"x"}:{...t,text:"x"};return ce(e,n)!==null}function Ra(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}function Aa(e,t=process.env){return e.host==="devin"&&qn(t.DEVIN_PROJECT_DIR)?t.DEVIN_PROJECT_DIR.trim():e.host==="cursor"&&qn(t.CURSOR_PROJECT_DIR)?t.CURSOR_PROJECT_DIR.trim():null}var qn,Ne=w(()=>{"use strict";Ce();so();qn=s(e=>typeof e=="string"&&e.trim().length>0,"filled");s(MM,"isClaudeCodeTranscript");s(ao,"detectHookHost");s(vv,"runsUnderCursor");s(tn,"isForeignHost");s(qe,"guardStandsDown");s($M,"devinOutputEnabled");s(oe,"resolveHookTarget");s(LM,"claudeCodeBytes");s(FM,"cursorBytes");s(jM,"devinBytes");s(ce,"renderHookOutput");s(_e,"hostDelivers");s(Ra,"writeHookStdout");s(Aa,"hostProjectDir")});import{existsSync as HM,readFileSync as UM}from"node:fs";import{join as zu}from"node:path";function kv(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function qu(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function xv(e,t={}){return e.some(n=>qu(Re(n,t,[Sv])[0]))}function Ca(e,t){let n=Re(e,t,[Sv])[0],r=Re(e,t,[BM])[0];return{channel:qu(n)?"core":qu(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function Ev(e,t){let n=[zu(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(zu(t,".claude","settings.json"),zu(t,".claude","settings.local.json")),n.map(r=>{try{return HM(r)?UM(r,"utf8"):null}catch{return null}})}var Sv,BM,Ia=w(()=>{"use strict";ct();s(kv,"hookOf");Sv=kv(at,st),BM=kv($r,"guard-inject");s(qu,"isRunnable");s(xv,"coreBriefingWiredIn");s(Ca,"briefingChannel");s(Ev,"claudeSettingsSources")});function Tv(e){return e==="on"?!0:e==="off"?!1:null}function le(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:Tv(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:Tv(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function Jn(e,t=Ae()){let n={};try{let i=await Y(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await V(t,JSON.stringify(r,null,2)+`
|
|
777
|
+
`,384)}var dt=w(()=>{"use strict";Ce();we();s(Tv,"envSwitch");s(le,"resolveGuardConfig");s(Jn,"writeGuardConfig")});function Oa(e){if(!e)return null;let t=e.split(`
|
|
764
778
|
`),n=t.findIndex(i=>i.startsWith("=== Project Conventions"));if(n<0)return null;let r=[];for(let i=n;i<t.length&&t[i].trim()!=="";i++)r.push(t[i]);return r.length>1?r.join(`
|
|
765
|
-
`):null}function
|
|
766
|
-
`),more:"get_session_briefing"}];let r=[];n.setup_advisory!==null&&n.setup_advisory!==void 0&&r.push({title:"Setup advisory (first session)",lines:[JSON.stringify(n.setup_advisory)],more:"get_agent_setup_guide"});let i=s((o,a)=>(o??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,o=>o.title?`- ${o.title}${o.id?` (${o.id})`:""}${o.summary?` \u2014 ${o.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,o=>o.id?`- ${o.id}${o.summary?`: ${o.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,o=>o.title?`- ${o.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,o=>o.id?`- ${o.id}${o.title?`: ${o.title}`:""}`:null),more:"search_lessons"}),r.filter(o=>o.lines.length>0)}function
|
|
767
|
-
`);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...
|
|
768
|
-
|
|
769
|
-
${d.title}`;if(
|
|
770
|
-
${d.lines[p]}`;if(
|
|
771
|
-
(+${d.lines.length-p} more \u2014 via ${d.more})`;
|
|
772
|
-
\u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;
|
|
773
|
-
`,complete:l}}var
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
`));try{
|
|
779
|
-
`)),
|
|
780
|
-
`)),this.machineLabel=lM(r?.machine_label),this.enabled=this.projectKey!==null&&!xu(n,r),this.workingPathsEnabled=oM(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??dM(n,iM(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<uw||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<uw||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<QP||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,rM).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(tM*2**(this.consecutiveFailures-1),nM);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let o=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${o} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:eM,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let o=await this.gitBranch();if(o&&(r.branch=o),this.lastBranch=o,o)try{let a=await this.gitBranchObject(o);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.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 i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let o=i;if(o.ok===!0&&typeof o.session_id=="string")try{this.identity.adopt(o.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let o={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};s(sM,"defaultGitBranchObject");s(aM,"normalizeObjectId");s(cM,"defaultGitBranch");s(lM,"normalizeMachineLabel");s(dM,"staticIdentity")});import{mkdirSync as mw,readdirSync as _w,readFileSync as uM,renameSync as hw,statSync as pM,unlinkSync as Eu,writeFileSync as gw}from"node:fs";import{homedir as fM}from"node:os";import{join as zr}from"node:path";function bw(){return zr(fM(),".maind","presence")}function vw(e,t){return zr(e,t)}function ww(e){let t=e.baseDir??bw(),n=vw(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=s(d=>{if(c!==null&&c!==d)try{Eu(c)}catch{}c=d},"replaceOwn");return{write(d,u){try{if(typeof d!="object"||d===null)return;let p=d;if(p.ok!==!0)return;let f={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[],...(()=>{let y=Io(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};mw(n,{recursive:!0,mode:448});let m=zr(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;gw(g,JSON.stringify(f),{mode:384}),hw(g,m),l(m),yw(n,a(),m)}catch{}},endSession(){try{c&&Eu(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:[],conflicts:[],announce_error:d};mw(n,{recursive:!0,mode:448});let f=zr(n,`${u.sessionId}.json`),m=`${f}.tmp-${r}`;gw(m,JSON.stringify(p),{mode:384}),hw(m,f),l(f),yw(n,a(),f)}catch{}}}}function yw(e,t,n){try{for(let r of _w(e)){if(!r.endsWith(".json"))continue;let i=zr(e,r);if(i!==n)try{t-pM(i).mtimeMs>mM&&Eu(i)}catch{}}}catch{}}function Jn(e,t=bw()){try{let n=vw(t,e),r=[];for(let i of _w(n))if(i.endsWith(".json"))try{let o=JSON.parse(uM(zr(n,i),"utf8")),a=hM(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function hM(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=Io(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var mM,Ra=v(()=>{"use strict";ai();mM=120*6e4;s(bw,"presenceSnapshotBaseDir");s(vw,"projectDir");s(ww,"createSnapshotStore");s(yw,"pruneStale");s(Jn,"readSnapshots");s(hM,"parseSnapshot")});import{execFileSync as TM}from"node:child_process";import{createHash as RM,randomUUID as CM}from"node:crypto";import{existsSync as AM,mkdirSync as IM,readdirSync as NM,readFileSync as Sw,renameSync as OM,statSync as Ru,unlinkSync as Ew,writeFileSync as DM}from"node:fs";import{homedir as PM}from"node:os";import{basename as MM,join as tn}from"node:path";function qr(e){return tn(e??tn(PM(),".maind","presence"),"identity")}function no(e,t){if(e){let n=MM(e).replace(/\.jsonl$/i,"");if(to.test(n))return n.toLowerCase()}return t&&to.test(t)?t.toLowerCase():null}function Tw(e){let t=e.nowMs??Date.now();IM(e.dir,{recursive:!0,mode:448});let n=tn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(Sw(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let o=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...o?{transcript_path:o}:{},...a?{model:a}:{}};DM(r,JSON.stringify(c,null,2)+`
|
|
781
|
-
`,{mode:384}),OM(r,n),HM(e.dir,t)}function Rw(e,t,n,r=Date.now()){try{let i=Ru(tn(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function Cw(e,t){try{Ew(tn(e,`${t}.json`))}catch{}}function HM(e,t){try{for(let n of NM(e))if(n.endsWith(".json"))try{let r=Ru(tn(e,n));t-r.mtimeMs>LM&&Ew(tn(e,n))}catch{}}catch{}}function UM(e){return Aw(e)?.file??null}function Aw(e){let t=tn(e.dir,`${e.agentPid}.json`);try{if(!AM(t))return null;let n=Ru(t);if(n.mtimeMs<e.bridgeStartMs-FM)return null;let r=JSON.parse(Sw(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!to.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!BM(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function xw(e){return e.replace(/\/+$/,"")}function BM(e,t){let n=xw(e),r=xw(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function GM(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=RM("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let o=i.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function KM(e){if(process.platform==="win32")return null;try{let t=TM("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function WM(){try{return oe()}catch{return null}}var to,$M,LM,FM,jM,Ca,Aa=v(()=>{"use strict";se();to=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$M=8,LM=48*60*6e4,FM=6e4,jM="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(qr,"identityDirPath");s(no,"transcriptStemOf");s(Tw,"writeAgentIdentityFile");s(Rw,"identityFileStale");s(Cw,"deleteAgentIdentityFile");s(HM,"pruneIdentityDir");s(UM,"readAgentIdentityFile");s(Aw,"readAgentIdentityEntry");s(xw,"normDir");s(BM,"sameSessionTree");s(GM,"uuidV5");s(KM,"processStartTime");Ca=class{static{s(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];stem=null;constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??qr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=to.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.stem=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??WM)(),o=(t.ppidStart??KM)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=GM(`${i}|${this.agentPid}|${o}|${t.projectKey}`,jM),this.source="derived";return}this.id=CM(),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(!to.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>$M&&this.aliases.shift())}activityAtMs(){return Aw({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 UM({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(WM,"defaultDeviceId")});function Cu(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Au=v(()=>{"use strict";s(Cu,"newModeState")});import{createReadStream as VM,existsSync as zM}from"node:fs";import{stat as qM}from"node:fs/promises";import{createInterface as JM}from"node:readline";async function Iu(e){if(!e||!zM(e))return null;let t;try{t=await qM(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=VM(e,{encoding:"utf-8"}),l=JM({input:c});l.on("line",d=>{let u=d.trim();if(u){o++;try{let p=JSON.parse(u),f=p.message?.usage;if(!f)return;let m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=m??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(i+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:o,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var Iw=v(()=>{"use strict";s(Iu,"summariseTranscript")});var Nw=v(()=>{"use strict"});function ro(e){if(!e)return null;let t=null;for(let n of e.matchAll(XM)){let r=n[1].toLowerCase();YM.has(r)&&(t=r)}return t}var YM,XM,Ia=v(()=>{"use strict";YM=new Set(["low","medium","high","xhigh","max"]),XM=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(ro,"detectEffortLevel")});import{createReadStream as ZM,existsSync as QM,readdirSync as e$}from"node:fs";import{basename as Pw,dirname as t$,join as Ow}from"node:path";import{createInterface as n$}from"node:readline";function $w(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!o$.test(n)||e.ids.includes(n)||e.ids.length>=Mw||e.ids.push(n)}function s$(e,t){if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string"||!r.name.startsWith(Na)||i$.has(r.name))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?$w(e,i.session_id):r.name===`${Na}announce_session`&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function a$(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 c$(e,t){if(!(e.pendingAnnounce.size===0||!Array.isArray(t)))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_result"||typeof r.tool_use_id!="string"||!e.pendingAnnounce.delete(r.tool_use_id))continue;let i=a$(r.content),o=null;try{let a=JSON.parse(i);a&&a.ok===!0&&(o=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(i);o=a?a[1]:null}$w(e,o)}}function Jr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function d$(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=l$[r.name];if(!i||!r.input||typeof r.input!="object")continue;let o=r.input[i];typeof o=="string"&&o.length>0&&t.push(o)}return t}function Oa(e){let t=Pw(e).replace(/\.jsonl$/,""),n=Ow(t$(e),t,"subagents"),r;try{r=e$(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>Ow(n,i))}async function Dw(e,t,n,r,i,o){QM(e)&&await new Promise(a=>{let c=ZM(e,{encoding:"utf-8"}),l=n$({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"){c$(o,f.message.content);return}if(f.message?.role!=="assistant")return;s$(o,f.message.content);let m=typeof f.message.id=="string"&&f.message.id?f.message.id:null,g=typeof f.requestId=="string"&&f.requestId?f.requestId:null,y=m??g??`${e}#${d}`,_=d$(f.message.content),b=r.get(y);if(b){for(let E of _)b.edited_paths.includes(E)||b.edited_paths.push(E);return}if(n.has(y))return;n.add(y);let w=f.message.usage??{},S=typeof f.timestamp=="string"?Date.parse(f.timestamp):Number.NaN,A=typeof f.message.model=="string"&&f.message.model?f.message.model:"",k={ts:Number.isFinite(S)?S:0,model:A||"<unknown>",synthetic:A===r$,input_tokens:Jr(w.input_tokens),output_tokens:Jr(w.output_tokens),cache_read_tokens:Jr(w.cache_read_input_tokens),cache_creation_tokens:Jr(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Jr(w.cache_creation?.ephemeral_1h_input_tokens),Jr(w.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,k),i.push(k)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function Nu(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function io(e){let t=new Set,n=new Map,r=[],i=e?Oa(e):[],o={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:i,coordination_ids:[]};let a=[];await Dw(e,Yn,t,n,a,o),Nu(a),r.push(...a);for(let c of i){let l=[],d=Pw(c).replace(/\.jsonl$/,"");o.pendingAnnounce.clear(),await Dw(c,d,t,n,l,o),Nu(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:i,coordination_ids:o.ids}}var Yn,r$,Na,i$,o$,Mw,l$,Da=v(()=>{"use strict";Yn="main",r$="<synthetic>",Na="mcp__maind__",i$=new Set([`${Na}get_session_analysis`,`${Na}get_session_cost_context`]),o$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Mw=32;s($w,"addCoordinationId");s(s$,"noteCoordinationUse");s(a$,"resultText");s(c$,"noteAnnounceResult");l$={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(Jr,"num");s(d$,"editedPathsOf");s(Oa,"subagentFilesOf");s(Dw,"readStream");s(Nu,"fillTimestamps");s(io,"collectTurns")});import{createReadStream as Lw,existsSync as u$}from"node:fs";import{createInterface as Fw}from"node:readline";function _$(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,a=e.get(o);if(!a){e.set(o,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function Pa(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function b$(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
782
|
-
`)}function v$(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function w$(e,t,n){return p$.test(e)?{polarity:-1,magnitude:Yr.rework,kind:"rework"}:n&&f$.test(e)?{polarity:-1,magnitude:Yr.correction,kind:"correction"}:m$.test(e)?{polarity:1,magnitude:Yr.acceptance,kind:"acceptance"}:t!==null&&v$(t,e)?{polarity:-1,magnitude:Yr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function k$(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:jw,behaviour_measured:!0}}async function x$(e,t){for(let n of Oa(e))await new Promise(r=>{let i=Fw({input:Lw(n,{encoding:"utf-8"})});i.on("line",o=>{let a=o.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of Pa(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Ma))continue;let d=l.name.slice(Ma.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Ou(e,t={}){let n=k$("");if(!e||!u$(e))return n;let r=t.turns??(await io(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(m=>{let g=Lw(e,{encoding:"utf-8"}),y=Fw({input:g}),_=s(b=>{let w=b.trim();if(!w)return;let S;try{S=JSON.parse(w)}catch{return}if(n.lines_seen++,!n.session_id){let j=S.sessionId??S.session_id;typeof j=="string"&&j&&(n.session_id=j)}S.type==="ai-title"&&typeof S.aiTitle=="string"&&S.aiTitle&&(n.ai_title=S.aiTitle),typeof S.slug=="string"&&S.slug&&(n.session_slug=S.slug);let A=S.message?.role,k=S.isSidechain===!0;if(A==="assistant")for(let j of Pa(S.message?.content)){if(j.type!=="tool_use"||typeof j.name!="string"||!j.name.startsWith(Ma))continue;let W=j.name.slice(Ma.length);W&&(n.maind_tool_calls??={},n.maind_tool_calls[W]=(n.maind_tool_calls[W]??0)+1)}if(k)return;if(A==="assistant"){let j=Pa(S.message?.content),W=!1;for(let pt of j)pt.type==="tool_use"&&(n.tool_calls++,W=!0,pt.name==="AskUserQuestion"&&n.agent_questions++);c=W;return}if(A!=="user")return;let E=Pa(S.message?.content),P=b$(E);if(P.includes(h$)){n.interrupts++,i.push({polarity:-1,magnitude:Yr.interrupt,kind:"interrupt"});return}if(E.some(j=>j.type==="tool_result"&&j.is_error===!0&&typeof j.content=="string"&&j.content.includes(g$))){n.tool_denials++,i.push({polarity:-1,magnitude:Yr.denial,kind:"denial"});return}if(E.some(j=>j.type==="tool_result")||!P.trim())return;n.user_turns++,n.user_chars+=P.length;let N=ro(P);N&&(a=N);let D=w$(P,l,c);l=P,D.kind==="correction"?n.corrections++:D.kind==="rework"?n.reworks++:D.kind==="repeat"?n.repeated_instructions++:D.kind==="acceptance"&&n.acceptances++,D.polarity!==0&&i.push(D),c=!1},"processLine");y.on("line",b=>{try{_(b)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await x$(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||_$(o,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...o.values()].sort((m,g)=>m.first_ts-g.first_ts||m.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return i.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*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&&i[g-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var Ma,jw,p$,f$,m$,h$,g$,y$,Yr,Hw=v(()=>{"use strict";Ia();Da();Ma="mcp__maind__",jw="2026-10-01",p$=/(\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,f$=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,m$=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,h$="[Request interrupted by user",g$="The user doesn't want to proceed with this tool use",y$=.7,Yr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(_$,"bumpModel");s(Pa,"asBlocks");s(b$,"textOf");s(v$,"isRepeat");s(w$,"classifyGenuine");s(k$,"emptyAnalysis");s(x$,"tallySubagentMaindCalls");s(Ou,"analyzeSession")});function Du(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 Pu(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 Mu(e,t,n,r="unknown",i){let o={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...c}=n;o.session_span={...t,...c}}else o.session_span=t;return o}var Uw=v(()=>{"use strict";s(Du,"parseIngestResponse");s(Pu,"describeSliceVerdict");s(Mu,"ingestBody")});import{isAbsolute as Bw,relative as S$,resolve as Gw,sep as Kw}from"node:path";function Ww(e){return e>La[1]?"above_272k":e>La[0]?"band_200k_272k":"standard"}function Vw(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function $a(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function oo(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=$a(d.from);typeof d.object_id!="string"||!$u.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:$a(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=$a(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:$a(c.to)})}let o=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!$u.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&$u.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:o}}function Fa(e,t){if(!Bw(e))return null;let n=S$(Gw(t),Gw(e));return!n||n==="."||n.startsWith("..")||Bw(n)?null:Kw==="/"?n:n.split(Kw).join("/")}function T$(e,t){return t===""||e===t||e.startsWith(t+"/")}function Fu(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function zw(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function ju(e,t){for(let n of zw(t))if(T$(e,n.path_prefix))return n.object_id;return null}function R$(e,t){for(let n of zw(t))if(Fu(e,n.path_prefix))return n.object_id;return null}function Lu(e,t){return e>=t.from&&(t.to===null||e<t.to)}function qw(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>ju(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Lu(i,u));if(c.length)return c.sort((u,p)=>p.from-u.from||u.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(u=>Lu(i,u));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>Lu(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>Fu(f.path_prefix,u))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=R$(f.path_prefix,o);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function Hu(e,t,n){let r=t?.anchors??[],i=n.repoRoot,o=n.relativize??(i?_=>Fa(_,i):null),a=s(_=>{if(!o)return[];let b=[];for(let w of _.edited_paths){let S=o(w);S!==null&&!b.includes(S)&&b.push(S)}return b},"relOf"),c=s(_=>{for(let b of _){let w=ju(b,r);if(w)return{object_id:w,rel:b}}return null},"firstAnchoredEdit"),l=new Map;for(let _ of e){let b=l.get(_.stream)??[];b.push(_),l.set(_.stream,b)}let d=[...l.entries()].sort(([_],[b])=>_===Yn?-1:b===Yn?1:0),u=[],p=s(_=>{let b=null;for(let w of u){if(w.ts>_&&_>0)break;b=w.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of d){let w=b.map((A,k)=>({t:A,i:k,rels:a(A)})).sort((A,k)=>A.t.ts-k.t.ts||A.i-k.i),S=null;for(let A of w){let k=c(A.rels);if(k){S=k;break}}!S&&_!==Yn&&w.length&&(S=p(w[0].t.ts));for(let A of w){let k=c(A.rels);k&&(S=k),_===Yn&&u.push({ts:A.t.ts,seg:S});let E=A.t;if(E.input_tokens+E.output_tokens+E.cache_read_tokens+E.cache_creation_tokens===0)continue;let x=qw(E,A.rels,S,t),N=Ww(E.input_tokens+E.cache_read_tokens+E.cache_creation_tokens),D=Vw(E.model),j=`${x.object_id??""}|${x.source}|${D}|${N}`,W=f.get(j);W||(W={object_id:x.object_id,attribution_source:x.source,model:D,context_tier:N,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},f.set(j,W)),W.input_tokens+=E.input_tokens,W.output_tokens+=E.output_tokens,W.cache_read_tokens+=E.cache_read_tokens,W.cache_creation_tokens+=E.cache_creation_tokens,W.cache_creation_1h_tokens+=E.cache_creation_1h_tokens,W.turns+=1,E.ts>0&&((W.firstMs===0||E.ts<W.firstMs)&&(W.firstMs=E.ts),E.ts>W.lastMs&&(W.lastMs=E.ts))}}let m=n.nowMs??Date.now(),g=[];for(let _ of f.values()){let{firstMs:b,lastMs:w,...S}=_;S.first_ts=new Date(b>0?b:m).toISOString(),S.last_ts=new Date(w>0?w:m).toISOString(),g.push(S)}let y={lease:0,binding:1,claim:2,path:3,none:4};return g.sort((_,b)=>y[_.attribution_source]-y[b.attribution_source]||(_.object_id??"").localeCompare(b.object_id??"")||_.model.localeCompare(b.model)||_.context_tier.localeCompare(b.context_tier)),g}var La,E$,$u,Uu=v(()=>{"use strict";Da();La=[2e5,272e3];s(Ww,"contextTierOf");s(Vw,"normalizeModelId");E$=La[0],$u=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s($a,"msOf");s(oo,"parseCostContext");s(Fa,"toRepoRelative");s(T$,"underPrefix");s(Fu,"prefixesOverlap");s(zw,"sortedAnchors");s(ju,"anchorFor");s(R$,"bestAnchorOverlapping");s(Lu,"inWindow");s(qw,"assignTurn");s(Hu,"sliceSession")});import{mkdirSync as C$,readFileSync as A$,renameSync as I$,writeFileSync as N$}from"node:fs";import{dirname as O$,isAbsolute as ja,sep as Bu}from"node:path";function D$(e){let t=e.split(Bu).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function P$(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function Gu(e){let t=new Map,n=s(u=>{let p=t.get(u);if(p!==void 0)return p;let f=e.keyOfRoot(u);return t.set(u,f),f},"keyOf"),r=new Map,i=s(u=>{let p=r.get(u);if(p!==void 0)return p;let f=e.gitRoot(u);return r.set(u,f),f},"gitRoot"),o=new Map,a=[...(e.known??new Map).entries()].filter(([u])=>ja(u)).sort((u,p)=>p[0].length-u[0].length),c=new Map,l=s(u=>{if(!e.isDir)return null;let p=c.get(u);if(p!==void 0)return p;let f=d(u);return c.set(u,f),f},"byConvention"),d=s(u=>{if(!e.isDir)return null;let p=u.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let g=p.slice(0,f-1).join("/")||"/",y=p[f-1];for(let _=y.lastIndexOf("-");_>0;_=y.lastIndexOf("-",_-1)){let b=`${g==="/"?"":g}/${y.slice(0,_)}`;if(e.isDir(b)&&i(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(u){if(!ja(u))return null;let p=u.split(Bu).join("/"),f=D$(p),m=i(f);if(m){let g=n(m);return o.set(m,g),{root:m,key:g}}for(let[g,y]of a)if(!(!P$(p,g)||p===g)&&!(e.isDir&&e.isDir(g)))return{root:g,key:y};return l(f)},seenLive(){return[...o.entries()].map(([u,p])=>({root:u,key:p}))}}}function Ku(e,t){let n=new Map;for(let a of e){let c=new Map;for(let l of a.edited_paths){let d=t.of(l);!d||!d.key||c.set(d.key,Math.max(c.get(d.key)??0,d.root.length))}for(let[l,d]of c){let u=n.get(l)??{turns:0,depth:0};u.turns+=1,u.depth=Math.max(u.depth,d),n.set(l,u)}}let r=null,i=0,o=0;for(let[a,c]of n)(c.turns>i||c.turns===i&&(c.depth>o||c.depth===o&&r!==null&&a<r))&&(r=a,i=c.turns,o=c.depth);return r}function Wu(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:Fa(n.split(Bu).join("/"),r.root)}}function Xw(e){try{let t=JSON.parse(A$(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 so(e){let t=new Map,n=Xw(e);for(let[r,i]of Object.entries(n.checkouts)){if(!ja(r)||!i||typeof i!="object")continue;let o=typeof i.project_key=="string"&&Yw.test(i.project_key)?i.project_key:null;t.set(r,o)}return t}function ao(e,t,n=Date.now()){try{let r=Xw(e),i=new Date(n).toISOString(),o=!1;for(let c of t){if(!ja(c.root))continue;let l=c.key&&Yw.test(c.key)?c.key:null,d=r.checkouts[c.root],u=Date.parse(d?.seen_at??"");(!d||d.project_key!==l||!Number.isFinite(u)||n-u>M$)&&(r.checkouts[c.root]={project_key:l,seen_at:i},o=!0)}for(let[c,l]of Object.entries(r.checkouts)){let d=Date.parse(l?.seen_at??"");(!Number.isFinite(d)||n-d>Jw)&&(delete r.checkouts[c],o=!0)}if(!o)return;C$(O$(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;N$(a,JSON.stringify(r),{mode:384}),I$(a,e)}catch{}}var Jw,M$,Yw,Zw=v(()=>{"use strict";Uu();s(D$,"dirOf");s(P$,"within");s(Gu,"createCheckoutResolver");s(Ku,"dominantProjectKey");s(Wu,"relativizerFor");Jw=90*24*60*60*1e3,M$=60*60*1e3,Yw=/^[a-f0-9]{64}$/;s(Xw,"readMemory");s(so,"loadCheckoutMemory");s(ao,"rememberCheckouts")});import{homedir as $$}from"node:os";import{join as L$}from"node:path";var F$,Vu=v(()=>{"use strict";F$=L$($$(),".codex","sessions")});var Qw=v(()=>{"use strict";Vu()});var ek=v(()=>{"use strict"});import{createReadStream as H$,existsSync as U$}from"node:fs";import{createInterface as B$}from"node:readline";function tk(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function W$(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
783
|
-
`)}function ik(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 V$(e){let t=e.message?.role;if(t==="assistant")return{holder:tk(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=tk(e.message?.content),r=W$(n);return r.includes(G$)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(K$))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function zu(e){let t=ik("");if(!e||!U$(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let d=H$(e,{encoding:"utf-8"}),u=B$({input:d}),p=s(f=>{let m=f.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let b=g.sessionId??g.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||o!==null&&y<o)return;let _=V$(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,o!==null){let b=y-o;a==="agent"?i+=b:b>=nk*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<rk&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(b/1e3)}))}o=y,a=_.holder}},"processLine");u.on("line",f=>{try{p(f)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var G$,K$,nk,rk,ok=v(()=>{"use strict";G$="[Request interrupted by user",K$="The user doesn't want to proceed with this tool use",nk=60,rk=200;s(tk,"asBlocks");s(W$,"textOf");s(ik,"emptySpan");s(V$,"classify");s(zu,"analyzeSpan")});import{createReadStream as z$,existsSync as q$}from"node:fs";import{createInterface as J$}from"node:readline";function X$(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function Ha(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Z$(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
|
|
784
|
-
`)}return""}async function qu(e,t={}){if(!e||!q$(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Cu(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:Cu(),a=t.start??0;return await new Promise(c=>{let l=z$(e,{encoding:"utf-8",start:t.start??0}),d=J$({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=Y$[m.attachment.type];b&&(o[X$(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(_==="user"){let b=Z$(m.message?.content),w=ro(b);w&&(i=w);let S={session_id:g,ts:y,text:b,effort_directive:w};n.push({kind:"user",...S});return}if(_==="assistant"){let b=m.message?.usage,w=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,S=typeof m.requestId=="string"&&m.requestId?m.requestId:null,A=w??S,k=A!==null&&r.has(A);A!==null&&!k&&r.add(A);let E={session_id:g,ts:y,model:m.message?.model??null,input_tokens:k?0:Ha(b?.input_tokens),output_tokens:k?0:Ha(b?.output_tokens),cache_read_input_tokens:k?0:Ha(b?.cache_read_input_tokens),cache_creation_input_tokens:k?0:Ha(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...o.ultracode?{ultracode:!0}:{},...o.planMode?{planMode:!0}:{},...o.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...E})}});let u=s(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...o},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var Y$,sk=v(()=>{"use strict";Ia();Au();Y$={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(X$,"modeFlagKey");s(Ha,"num");s(Z$,"extractUserText");s(qu,"streamTranscript")});var ak=v(()=>{"use strict"});import{homedir as Q$}from"node:os";import{join as eL}from"node:path";function Yu(e){return e.replace(/[/.]/g,"-")}var tL,Ju,ck=v(()=>{"use strict";tL=Q$(),Ju=eL(tL,".claude","projects");s(Yu,"projectPathFromCwd")});var Xn=v(()=>{"use strict";Au();Iw();Nw();Hw();Uw();Da();Zw();Vu();Qw();Uu();ek();ok();sk();Ia();ak();ck()});import{parse as dL}from"jsonc-parser";function Xu(e,t){let n=e.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),r=t.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0);for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function Qu(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!a)return null;let c=/^\s*command\s*=\s*"([^"]*)"/m.exec(a[1]),l=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(a[1]);return c?{command:c[1],args:l?[...l[1].matchAll(/"([^"]*)"/g)].map(d=>d[1]):[]}:null}let t=[],n=dL(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,i=r.servers?.maind??r.mcpServers?.maind,o=i?.transport??i;return!o||typeof o.command!="string"?null:{command:o.command,args:Array.isArray(o.args)?o.args.filter(a=>typeof a=="string"):[]}}function Xr(e,t){let n=`npm i -g ${Zn}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Ba(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(p=>p.bridgeVersion).filter(p=>p!==null)],r=e.latestVersion??n.sort(Xu).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=e.nodeTrees.filter(p=>p.bridgeVersion!==null);if(e.nodeTrees.length>0){let p=e.pathWinner?.node??null,f=e.nodeTrees.find(g=>g.node===p);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):f&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${f.node} tree (${f.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let g=e.nodeTrees.find(y=>y.node===e.nvmDefault);g&&g.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${g.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Xr(r,g.node)})}if(new Set(i.map(g=>g.bridgeVersion)).size>1)for(let g of i.filter(y=>Xu(y.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${g.node} carries bridge ${g.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Xr(r,g.node)})}let o=!1,a=new Map,c=s((p,f)=>{let m=a.get(p)??{version:e.installVersionOf(p),clients:[]};m.clients.push(f),a.set(p,m)},"noteInstall");for(let p of e.clientConfigs){let f=Qu(p);if(f===null)continue;if(p.present===!1){t.push({check:"client-config",level:"warn",message:`${p.label}: ${p.path} names maind, but the client is not installed \u2014 nothing reads this file (a leftover of an earlier install).`,fix:"maind-mcp-bridge doctor --remove-phantoms"});continue}if(o=!0,/(^|\/)npx(\.cmd)?$/.test(f.command)&&f.args.some(y=>y.includes(Zn))){t.push({check:"client-config",level:"warn",message:`${p.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${Xr(r)}, then set "command": "maind-mcp-bridge" (no args) in ${p.path}`});continue}let g=/(^|[\\/])node(\.exe)?$/.test(f.command);if(g&&f.args.length>0){let y=f.args[0];if(!e.fileExists(y)){t.push({check:"client-config",level:"error",message:`${p.label} runs ${y}, which does not exist.`,fix:`re-run \`npx -y ${Zn}@${r} install\` to rewrite the entry`});continue}c(y,p.label)}else if(f.command.includes("/")||f.command.includes("\\")){if(!e.fileExists(f.command)){t.push({check:"client-config",level:"error",message:`${p.label} points at ${f.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${p.path} (after ${Xr(r)})`});continue}}else if(f.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${p.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:Xr(r,e.nvmDefault)});continue}g||(f.command.includes("/")||f.command.includes("\\")?c(f.command,p.label):f.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,p.label)),t.push({check:"client-config",level:"ok",message:`${p.label}: ${[f.command,...f.args].join(" ")}`})}if(o||t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${Zn} install`}),e.latestVersion!==null)for(let[p,f]of a){let m=f.clients.join(", ");if(f.version===null)t.push({check:"version",level:"info",message:`${m}: cannot tell which bridge version ${p} is.`});else if(Xu(f.version,e.latestVersion)<0){let g=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(p)?.[1]??null;t.push({check:"version",level:"warn",message:`${m} run bridge ${f.version} (${p}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:g?Xr(e.latestVersion,g):`npx -y ${Zn}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${m} run bridge ${f.version} (published: ${e.latestVersion}).`})}for(let{dir:p,maind:f}of e.npxStaleDirs)t.push({check:"npx-cache",level:f?"error":"info",message:f?`a half-built better-sqlite3 was left in ${p} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${p} (another tool's npx entry, not maind's).`,fix:`rm -rf '${p.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!uk.test(e.deviceId))&&t.push({check:"credentials",level:"error",message:"no valid device id \u2014 the server binds keys to a device, so every call ends in 401 invalid_or_device_required.",fix:"maind-mcp-bridge --reauth"}),l===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):pL.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&uk.test(e.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=e.connection;if(d===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):d.outcome==="ok"||d.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):t.push({check:"connection",level:"error",message:d.outcome==="auth_failed"?`the server rejected the last connection (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"}),e.claudeSettings!==null){let p=Te(e.claudeSettings,{fileExists:s(m=>e.fileExists(m),"fileExists")}),f=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let m of p){if(m.status==="missing"||m.status==="superseded")continue;if(m.status!=="ok"){t.push({check:"hooks",level:m.status==="broken"?"error":"warn",message:m.detail});continue}let g=m.command?/(\S+\/build\/index\.js)/.exec(m.command)?.[1]??null:null,y=g?e.installVersionOf(g):null;y!==null&&f!==null&&y!==f&&t.push({check:"hooks",level:"warn",message:`${m.event}/${m.subcommand} runs bridge ${y}, the MCP server runs ${f} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${m.subcommand}`})}t.some(m=>m.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}if(e.claudeSettings!==null){let p=e.guardMode??"off",f=da(e.claudeSettings,{guardMode:p,fileExists:s(_=>e.fileExists(_),"fileExists")}),g=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Zn}`)} install --hooks-only`,y=(e.declinedHooks??[]).includes(st);f.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${st} hook).`}):f.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${st} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):f.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${p}); without the core ${st} hook it stops when the guard is switched off.`,fix:g}):y?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${st} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:g}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${st}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:g})}if(e.claudeSettings!==null){let p=Te(e.claudeSettings,{fileExists:s(f=>e.fileExists(f),"fileExists")},[uL])[0];if(p.status==="superseded"){let f=e.foreignHookHosts??[],m=f.includes("cursor"),g=(e.declinedHooks??[]).includes(Ln),y=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Zn}`),_=p.remedy==="run-install"?`${y} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${y} ${Ln}`,b=m?`Cursor, installed here, imports it from ~/.claude/settings.json and takes only JSON at session start \u2014 it gets plain text it cannot parse${f.includes("devin")?"; Devin Local gets text whose handling it does not document":""}`:f.includes("devin")?"Devin Local, installed here, runs it too and documents only JSON context for hooks":"it is fine in Claude Code, but Cursor and Devin Local, which import the same hooks, would get plain text";t.push({check:"hook-hosts",level:m&&!g?"warn":"info",message:`the SessionStart reminder hook still runs \`${p.command}\` \u2014 ${b}. ${Ln} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:_})}}let u=e.context??null;if(u!==null&&e.claudeSettings!==null){let p=Te(e.claudeSettings,{fileExists:s(f=>e.fileExists(f),"fileExists")}).filter(f=>(f.subcommand==="on-prompt-context"||f.subcommand==="on-read-context")&&f.status!=="missing").map(f=>f.subcommand);if(p.length>0){let f=t.length;u.sqlite.ok?u.repoRoot!==null&&!u.indexPresent&&t.push({check:"context",level:"info",message:`${u.repoRoot} has no code index \u2014 on-read-context stays silent there, and on-prompt-context can only match conventions.`,fix:"ask your agent to run codebase_index once (or run `maind index` in the repo); the Stop hook keeps it fresh after that"}):t.push({check:"context",level:"warn",message:`${p.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${u.sqlite.reason}). They stay silent.`,fix:"update Node to >= 22.16 (builtin SQLite), or run `npm rebuild better-sqlite3` in the bridge's install prefix"}),p.includes("on-prompt-context")&&u.repoRoot!==null&&!u.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${u.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===f&&t.push({check:"context",level:"ok",message:`${p.join(" and ")}: code index and cached conventions present${u.repoRoot?` for ${u.repoRoot}`:""}.`})}}return t}function pk(e){let t=e.filter(i=>i.level==="error"&&Zu.includes(i.check)).sort((i,o)=>Zu.indexOf(i.check)-Zu.indexOf(o.check)),n=t[0];if(n===void 0)return fL(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 fL(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?mL(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 mL(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?null:`[maind] setup gap \u2014 ${t.message}`+(t.fix?` To switch to it, run in a terminal (asks consent, replaces only that entry): ${t.fix}`:"")}function fk(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,c)=>n[a.level]-n[c.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),i=e.filter(a=>a.level==="error").length,o=e.filter(a=>a.level==="warn").length;return r.push("",i+o===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${o} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
779
|
+
`):null}function KM(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(`
|
|
780
|
+
`),more:"get_session_briefing"}];let r=[];n.setup_advisory!==null&&n.setup_advisory!==void 0&&r.push({title:"Setup advisory (first session)",lines:[JSON.stringify(n.setup_advisory)],more:"get_agent_setup_guide"});let i=s((o,a)=>(o??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,o=>o.title?`- ${o.title}${o.id?` (${o.id})`:""}${o.summary?` \u2014 ${o.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,o=>o.id?`- ${o.id}${o.summary?`: ${o.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,o=>o.title?`- ${o.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,o=>o.id?`- ${o.id}${o.title?`: ${o.title}`:""}`:null),more:"search_lessons"}),r.filter(o=>o.lines.length>0)}function Da(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
|
|
781
|
+
`);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...KM(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
|
|
782
|
+
|
|
783
|
+
${d.title}`;if(Na(c+u)>a){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let f=`
|
|
784
|
+
${d.lines[p]}`;if(Na(c+f)<=a){c+=f;continue}l=!1;let m=`
|
|
785
|
+
(+${d.lines.length-p} more \u2014 via ${d.more})`;Na(c+m)<=r&&(c+=m);break}if(!l)break}if(!l){let d=`
|
|
786
|
+
\u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;Na(c+d)<=r&&(c+=d)}return{text:c+`
|
|
787
|
+
`,complete:l}}var Na,Pa=w(()=>{"use strict";Na=s(e=>Buffer.byteLength(e,"utf8"),"bytes");s(Oa,"extractConventionsBlock");s(KM,"briefingSections");s(Da,"composeInjection")});import{existsSync as Av}from"node:fs";import{mkdir as GM,readFile as WM,readdir as VM,rename as zM,stat as qM,unlink as JM,writeFile as YM}from"node:fs/promises";import{join as co}from"node:path";function Cv(e){return co(Ju,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function St(e){try{let t=Cv(e);if(!Av(t))return{};let n=JSON.parse(await WM(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Te(e,t){await GM(Ju,{recursive:!0,mode:448});let n=Cv(e),r=`${n}.tmp`;await YM(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await zM(r,n)}async function Iv(e=7*24*60*60*1e3,t=Date.now()){await Rv(Ju,".json",e,t),await Rv(Yu,".jsonl",e,t)}async function Rv(e,t,n,r){try{if(!Av(e))return;for(let i of await VM(e)){if(!i.endsWith(t))continue;let o=co(e,i);try{let a=await qM(o);r-a.mtimeMs>n&&await JM(o)}catch{}}}catch{}}var Je,Ju,Yu,xt=w(()=>{"use strict";Ie();Je=co(ve,"guard"),Ju=co(Je,"sessions"),Yu=co(Je,"triggers");s(Cv,"sessionFile");s(St,"loadGuardSession");s(Te,"saveGuardSession");s(Iv,"sweepOldGuardSessions");s(Rv,"sweepDir")});import{existsSync as XM}from"node:fs";import{appendFile as ZM,mkdir as QM,open as e$}from"node:fs/promises";import{join as t$}from"node:path";async function Q(e){try{await QM(Je,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
788
|
+
`;await ZM(Yn,t,{mode:384})}catch{}}async function Nv(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(!XM(Yn))return t;let n=await e$(Yn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),o=Buffer.alloc(r-i);await n.read(o,0,o.length,i);let c=o.toString("utf8").split(`
|
|
789
|
+
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Yn,Et=w(()=>{"use strict";xt();Yn=t$(Je,"events.jsonl");s(Q,"appendGuardEvent");s(Nv,"readGuardEventCounts")});var $v={};X($v,{BRIEFING_CACHE_FILE:()=>zr,UNAVAILABLE_LINE:()=>Pv,carriesBriefing:()=>Dv,deliverSessionBriefing:()=>Ma,formatInjection:()=>Mv,resolveBriefingInjection:()=>qr,runGuardInject:()=>p$,runsUnderCursor:()=>vv});import{existsSync as n$}from"node:fs";import{mkdir as r$,readFile as i$,rename as o$,writeFile as s$}from"node:fs/promises";import{homedir as a$}from"node:os";import{dirname as c$,join as l$}from"node:path";async function qr(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??zr,o=n.fetcher??Wr,a=await g$(i),c=a!==null&&a.format===Ov&&r-Date.parse(a.fetched_at)<d$&&a.project_key===e,l=s(p=>p.conventions?{conventions:p.conventions}:{},"withConventions");if(c)return{text:a.text,via:"cache",...l(a)};let d=null,u=await o({onInitialize:s(p=>{d=Oa(p)},"onInitialize"),apiKey:t,deviceId:_$(),projectKey:e,bridgeVersion:U,timeoutMs:u$});if(u!==null){let p=d;return await y$(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:Ov,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return a!==null?{text:a.text,via:"stale-cache",...l(a)}:{text:null,via:"none"}}async function p$(){try{if(le().mode==="off")return 0;let t=await G();return xv(Ev(a$(),h$(t)))?0:await Ma("guard",t)}catch{return 0}}function Dv(e){return e==="resume"||e==="fork"}function f$(e,t){let n=Aa(e,t);if(n===null)return te();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:Le(n)}function m$(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Ma(e,t,n={}){let r=n.env??process.env,i=oe(t,r,n.readConfig??ee);if(!_e(i,{kind:"text",event:"SessionStart"}))return 0;let o=n.write??m$,a=s(async b=>{let v=ce(i,{kind:"text",event:"SessionStart",text:b});v!==null&&await o(v)},"write"),c=tn(i.host)?{host:i.host}:{},l=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(l===null)return 0;await Iv();let d=typeof t.source=="string"?t.source:"startup";if(Dv(d)){let b=await St(l);return await Te(l,{...b,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??(()=>f$(i,r)))(),m=await qr(f,u,n.inject),g=await St(l);if(m.text===null)return await Te(l,{...g,inject_failed:!0}),await Q({event:"inject_fail",session_id:l,cwd:p,project_key:f??void 0,...e==="core"?{detail:"core"}:{},...c}),await a(Pv),0;let y=Mv(m.text,m.via,m.conventions??null,e);await a(y.text),await Te(l,{...g,injected:!0});let _=y.complete?m.via:`${m.via}+budget`;return await Q({event:"inject_ok",session_id:l,cwd:p,project_key:f??void 0,detail:e==="core"?`core:${_}`:_,...c}),0}function h$(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 Mv(e,t,n=null,r="guard"){let i=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",o=`Session briefing${n?" + project conventions":""}`,a=(r==="core"?`[maind] ${o}, delivered by the bridge's session-start hook (ADR-359)${i} \u2014 `:`[maind guard] ${o}, injected deterministically (ADR-284)${i} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return Da(a,n,e)}async function g$(e){try{if(!n$(e))return null;let t=JSON.parse(await i$(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 y$(e,t){try{await r$(c$(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await s$(n,JSON.stringify(t,null,2),{mode:384}),await o$(n,e)}catch{}}function _$(){try{return ne()}catch{return null}}var zr,d$,Ov,u$,Pv,Xn=w(()=>{"use strict";Ce();ie();ye();Ne();Ia();he();ze();dt();Pa();Et();xt();en();zr=l$(Je,"briefing-cache.json"),d$=12*60*60*1e3,Ov=2,u$=3e3;s(qr,"resolveBriefingInjection");s(p$,"runGuardInject");s(Dv,"carriesBriefing");s(f$,"sessionProjectKey");s(m$,"writeStdout");s(Ma,"deliverSessionBriefing");Pv=`[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.
|
|
790
|
+
`;s(h$,"projectDirOf");s(Mv,"formatInjection");s(g$,"readCache");s(y$,"writeCache");s(_$,"safeDeviceId")});var zv={};X(zv,{AGENTS_MD_READER_FAMILIES:()=>Uv,AGENTS_MD_REFRESH_DEBUG_ENV:()=>Gv,AGENTS_MD_REFRESH_INTERVAL_MS:()=>Bv,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>Kv,AGENTS_MD_REFRESH_STATE_FILE:()=>Hv,gitToplevel:()=>Wv,loadConventionsForAgentsMd:()=>$a,readsAgentsMd:()=>Jr,refreshAgentsMdConventions:()=>Xu,refreshAgentsMdForSession:()=>N$});import{execFileSync as b$}from"node:child_process";import{createHash as w$}from"node:crypto";import{mkdir as v$,readFile as k$,realpath as S$,rename as x$,writeFile as E$}from"node:fs/promises";import{dirname as T$,isAbsolute as R$,join as jv,relative as A$,resolve as C$}from"node:path";function Jr(e){return e!==null&&Uv.includes(e)}async function $a(e,t,n){if(e===null)return null;let r=n.clientFamily??"codex",i=await qr(t,e,{fetcher:n.allowFetch?o=>Wr({...o,clientFamily:r}):async()=>null});return i.text===null?null:i.conventions??null}async function Xu(e,t){let n=t.err??(r=>process.stderr.write(`${r}
|
|
791
|
+
`));try{if(!Jr(e))return{status:"skipped",reason:"family"};let r=t.env??process.env;if(D$(r))return{status:"skipped",reason:"opt-out"};let i=t.cwd??process.cwd(),o=(t.gitToplevel??Wv)(i);if(o===null)return Zu(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 ${i} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Fv(o),c=[];for(let C of await(t.findRoots??Us)(i)){let k=await Fv(C);O$(k,a)&&!c.includes(k)&&c.push(k)}c.includes(a)||c.push(a);let l=null,d=null;for(let C of c){let k=jv(C,"AGENTS.md"),E=await Y(k);if(E!==null&&Vs(E,jn)){l=k,d=E;break}}if(l===null||d===null)return Zu(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 no AGENTS.md with the "${jn}" header between the working directory and ${a} (the bridge never writes above the repository root)`),{status:"skipped",reason:"no-agents-md-in-repo"};let u=t.nowMs??Date.now(),p=t.stateFile??Hv,f=await M$(p),m=P$(l),g=f.roots[m]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<Bv)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((C,k)=>$a(k,C,{allowFetch:!0,clientFamily:e??void 0})))(t.projectKey,t.apiKey);if(_===null||_.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=Ws(_,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??U}),v=zs(d,b,jn);if(v.outcome==="damaged")return n(`maind: AGENTS.md conventions block not refreshed \u2014 begin marker without end marker in ${l}; remove the <!-- maind:conventions --> lines and the bridge re-inserts the block`),{status:"skipped",reason:"damaged"};if(v.outcome==="no-header")return{status:"skipped",reason:"no-agents-md-in-repo"};if(v.changed&&await V(l,v.next),await $$(p,f,m,u),!v.changed)return{status:"unchanged",file:l};let x=Tb(b);return n(`maind: AGENTS.md conventions block refreshed (${x} conventions)`),{status:"refreshed",file:l,conventions:x,inserted:v.outcome==="inserted"}}catch(r){let i=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md conventions block not refreshed \u2014 ${i}`),{status:"failed",error:i}}}async function N$(e,t){let n=await Xu(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-agents-md-in-repo"||t.listRoots===void 0)return n;let r=t.env??process.env,i=t.err??(l=>process.stderr.write(`${l}
|
|
792
|
+
`)),o;try{o=await t.listRoots()}catch{o=null}if(o===null||o.length===0)return Zu(r)&&i("maind: AGENTS.md conventions block skipped \u2014 the working directory gave no repository with our AGENTS.md, "+(o===null?"and the client offers no workspace roots (no MCP roots capability, or no answer)":"and the client lists no workspace roots")),n;let a=t.cwd??process.cwd(),c=n;for(let l of o){if(l===a)continue;let d=await Xu(e,{...t,cwd:l,projectKey:(t.projectKeyFor??Le)(l)??t.projectKey});Lv(d)>Lv(c)&&(c=d)}return c}function Lv(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function Wv(e){try{let t=b$("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 O$(e,t){let n=A$(t,e);return n===""||!n.startsWith("..")&&!R$(n)}async function Fv(e){try{return await S$(e)}catch{return C$(e)}}function D$(e){return Vv(e[Kv])}function Zu(e){return Vv(e[Gv])}function Vv(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function P$(e){return w$("sha256").update(e).digest("hex")}async function M$(e){let t={version:1,roots:{}};try{let n=JSON.parse(await k$(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[i,o]of Object.entries(n.roots))o&&typeof o.checked_at=="string"&&(r[i]={checked_at:o.checked_at});return{version:1,roots:r}}catch{return t}}async function $$(e,t,n,r){let i={};for(let[a,c]of Object.entries(t.roots)){let l=Date.parse(c.checked_at);!Number.isNaN(l)&&r-l<I$&&(i[a]=c)}i[n]={checked_at:new Date(r).toISOString()},await v$(T$(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await E$(o,JSON.stringify({version:1,roots:i},null,2),{mode:384}),await x$(o,e)}var Hv,Uv,Bv,Kv,Gv,I$,La=w(()=>{"use strict";en();Xn();xt();Jd();we();Yd();Wd();he();ze();Hv=jv(Je,"agents-md-refresh.json"),Uv=["codex","cursor","windsurf","copilot"];s(Jr,"readsAgentsMd");Bv=12*60*60*1e3,Kv="MAIND_NO_AGENTS_MD_REFRESH",Gv="MAIND_DEBUG",I$=30*24*60*60*1e3;s($a,"loadConventionsForAgentsMd");s(Xu,"refreshAgentsMdConventions");s(N$,"refreshAgentsMdForSession");s(Lv,"rank");s(Wv,"gitToplevel");s(O$,"isWithin");s(Fv,"realpathOrResolve");s(D$,"isOptedOut");s(Zu,"isDebug");s(Vv,"isSet");s(P$,"fileKey");s(M$,"readState");s($$,"writeState")});import{mkdirSync as ek,rmdirSync as tk,statSync as U$}from"node:fs";import{join as nk}from"node:path";import{setTimeout as B$}from"node:timers/promises";function rk(e){return nk(e,".maind","index-refresh.lock")}function Ha(e,t=Date.now()){let n=rk(e);try{if(t-U$(n).mtimeMs<K$)return!1;tk(n)}catch{}try{return ek(n,{recursive:!1}),!0}catch{return!1}}function lo(e){try{tk(rk(e))}catch{}}async function ik(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(a=>B$(a).then(()=>{})),o=r()+(n.waitMs??3e4);try{ek(nk(e,".maind"),{recursive:!0})}catch{}for(;!Ha(e,r());){if(r()>=o)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{lo(e)}}var K$,Qu=w(()=>{"use strict";K$=30*6e4;s(rk,"lockPath");s(Ha,"acquireLock");s(lo,"releaseLock");s(ik,"withIndexLock")});import{execFile as wk}from"node:child_process";import{randomUUID as pL}from"node:crypto";function _L(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return op.test(t)?t:pL()}function sp(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function bL(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 wL(e){return await new Promise(t=>{wk("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(vL(r))})})}function vL(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 kL(){return await new Promise(e=>{wk("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 SL(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function xL(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=op.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{op.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var bk,vk,fL,mL,hL,gL,yL,op,Ga,ap=w(()=>{"use strict";Ce();bk=45e3,vk=3e4,fL=5,mL=120,hL=3e4,gL=15*6e4,yL=1500,op=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(_L,"resolveClientSessionId");s(sp,"autoAnnounceDisabled");s(bL,"autoWorkingPathsEnabled");Ga=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??kL,this.gitBranchObject=t.gitBranchObject??wL,this.log=t.log??(i=>process.stderr.write(i+`
|
|
793
|
+
`)),this.machineLabel=SL(r?.machine_label),this.enabled=this.projectKey!==null&&!sp(n,r),this.workingPathsEnabled=bL(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??xL(n,_L(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<bk||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<bk||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<fL||(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,yL).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(hL*2**(this.consecutiveFailures-1),gL);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let o=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${o} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:mL,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let o=await this.gitBranch();if(o&&(r.branch=o),this.lastBranch=o,o)try{let a=await this.gitBranchObject(o);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.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 i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let o=i;if(o.ok===!0&&typeof o.session_id=="string")try{this.identity.adopt(o.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let o={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};s(wL,"defaultGitBranchObject");s(vL,"normalizeObjectId");s(kL,"defaultGitBranch");s(SL,"normalizeMachineLabel");s(xL,"staticIdentity")});import{mkdirSync as kk,readdirSync as Tk,readFileSync as EL,renameSync as Sk,statSync as TL,unlinkSync as cp,writeFileSync as xk}from"node:fs";import{homedir as RL}from"node:os";import{join as Yr}from"node:path";function Rk(){return Yr(RL(),".maind","presence")}function Ak(e,t){return Yr(e,t)}function Ck(e){let t=e.baseDir??Rk(),n=Ak(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=s(d=>{if(c!==null&&c!==d)try{cp(c)}catch{}c=d},"replaceOwn");return{write(d,u){try{if(typeof d!="object"||d===null)return;let p=d;if(p.ok!==!0)return;let f={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[],...(()=>{let y=Mo(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};kk(n,{recursive:!0,mode:448});let m=Yr(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;xk(g,JSON.stringify(f),{mode:384}),Sk(g,m),l(m),Ek(n,a(),m)}catch{}},endSession(){try{c&&cp(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:[],conflicts:[],announce_error:d};kk(n,{recursive:!0,mode:448});let f=Yr(n,`${u.sessionId}.json`),m=`${f}.tmp-${r}`;xk(m,JSON.stringify(p),{mode:384}),Sk(m,f),l(f),Ek(n,a(),f)}catch{}}}}function Ek(e,t,n){try{for(let r of Tk(e)){if(!r.endsWith(".json"))continue;let i=Yr(e,r);if(i!==n)try{t-TL(i).mtimeMs>AL&&cp(i)}catch{}}}catch{}}function Xr(e,t=Rk()){try{let n=Ak(t,e),r=[];for(let i of Tk(n))if(i.endsWith(".json"))try{let o=JSON.parse(EL(Yr(n,i),"utf8")),a=CL(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function CL(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=Mo(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var AL,Wa=w(()=>{"use strict";pi();AL=120*6e4;s(Rk,"presenceSnapshotBaseDir");s(Ak,"projectDir");s(Ck,"createSnapshotStore");s(Ek,"pruneStale");s(Xr,"readSnapshots");s(CL,"parseSnapshot")});import{execFileSync as HL}from"node:child_process";import{createHash as UL,randomUUID as BL}from"node:crypto";import{existsSync as KL,mkdirSync as GL,readdirSync as WL,readFileSync as Ok,renameSync as VL,statSync as dp,unlinkSync as Dk,writeFileSync as zL}from"node:fs";import{homedir as qL}from"node:os";import{basename as JL,join as nn}from"node:path";function Zr(e){return nn(e??nn(qL(),".maind","presence"),"identity")}function fo(e,t){if(e){let n=JL(e).replace(/\.jsonl$/i,"");if(po.test(n))return n.toLowerCase()}return t&&po.test(t)?t.toLowerCase():null}function Pk(e){let t=e.nowMs??Date.now();GL(e.dir,{recursive:!0,mode:448});let n=nn(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(Ok(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let o=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...o?{transcript_path:o}:{},...a?{model:a}:{}};zL(r,JSON.stringify(c,null,2)+`
|
|
794
|
+
`,{mode:384}),VL(r,n),eF(e.dir,t)}function Mk(e,t,n,r=Date.now()){try{let i=dp(nn(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function $k(e,t){try{Dk(nn(e,`${t}.json`))}catch{}}function eF(e,t){try{for(let n of WL(e))if(n.endsWith(".json"))try{let r=dp(nn(e,n));t-r.mtimeMs>XL&&Dk(nn(e,n))}catch{}}catch{}}function tF(e){return Lk(e)?.file??null}function Lk(e){let t=nn(e.dir,`${e.agentPid}.json`);try{if(!KL(t))return null;let n=dp(t);if(n.mtimeMs<e.bridgeStartMs-ZL)return null;let r=JSON.parse(Ok(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!po.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!nF(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function Nk(e){return e.replace(/\/+$/,"")}function nF(e,t){let n=Nk(e),r=Nk(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function rF(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=UL("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let o=i.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function iF(e){if(process.platform==="win32")return null;try{let t=HL("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function oF(){try{return ne()}catch{return null}}var po,YL,XL,ZL,QL,Va,za=w(()=>{"use strict";ie();po=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,YL=8,XL=48*60*6e4,ZL=6e4,QL="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(Zr,"identityDirPath");s(fo,"transcriptStemOf");s(Pk,"writeAgentIdentityFile");s(Mk,"identityFileStale");s($k,"deleteAgentIdentityFile");s(eF,"pruneIdentityDir");s(tF,"readAgentIdentityFile");s(Lk,"readAgentIdentityEntry");s(Nk,"normDir");s(nF,"sameSessionTree");s(rF,"uuidV5");s(iF,"processStartTime");Va=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??Zr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=po.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.stem=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??oF)(),o=(t.ppidStart??iF)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=rF(`${i}|${this.agentPid}|${o}|${t.projectKey}`,QL),this.source="derived";return}this.id=BL(),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(!po.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>YL&&this.aliases.shift())}activityAtMs(){return Lk({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 tF({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(oF,"defaultDeviceId")});import{parse as mF}from"jsonc-parser";function up(e,t){let n=e.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),r=t.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0);for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function fp(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!a)return null;let c=/^\s*command\s*=\s*"([^"]*)"/m.exec(a[1]),l=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(a[1]);return c?{command:c[1],args:l?[...l[1].matchAll(/"([^"]*)"/g)].map(d=>d[1]):[]}:null}let t=[],n=mF(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,i=r.servers?.maind??r.mcpServers?.maind,o=i?.transport??i;return!o||typeof o.command!="string"?null:{command:o.command,args:Array.isArray(o.args)?o.args.filter(a=>typeof a=="string"):[]}}function Qr(e,t){let n=`npm i -g ${er}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Ja(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(p=>p.bridgeVersion).filter(p=>p!==null)],r=e.latestVersion??n.sort(up).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=e.nodeTrees.filter(p=>p.bridgeVersion!==null);if(e.nodeTrees.length>0){let p=e.pathWinner?.node??null,f=e.nodeTrees.find(g=>g.node===p);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):f&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${f.node} tree (${f.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let g=e.nodeTrees.find(y=>y.node===e.nvmDefault);g&&g.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${g.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Qr(r,g.node)})}if(new Set(i.map(g=>g.bridgeVersion)).size>1)for(let g of i.filter(y=>up(y.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${g.node} carries bridge ${g.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Qr(r,g.node)})}let o=!1,a=new Map,c=s((p,f)=>{let m=a.get(p)??{version:e.installVersionOf(p),clients:[]};m.clients.push(f),a.set(p,m)},"noteInstall");for(let p of e.clientConfigs){let f=fp(p);if(f===null)continue;if(p.present===!1){t.push({check:"client-config",level:"warn",message:`${p.label}: ${p.path} names maind, but the client is not installed \u2014 nothing reads this file (a leftover of an earlier install).`,fix:"maind-mcp-bridge doctor --remove-phantoms"});continue}if(o=!0,/(^|\/)npx(\.cmd)?$/.test(f.command)&&f.args.some(y=>y.includes(er))){t.push({check:"client-config",level:"warn",message:`${p.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${Qr(r)}, then set "command": "maind-mcp-bridge" (no args) in ${p.path}`});continue}let g=/(^|[\\/])node(\.exe)?$/.test(f.command);if(g&&f.args.length>0){let y=f.args[0];if(!e.fileExists(y)){t.push({check:"client-config",level:"error",message:`${p.label} runs ${y}, which does not exist.`,fix:`re-run \`npx -y ${er}@${r} install\` to rewrite the entry`});continue}c(y,p.label)}else if(f.command.includes("/")||f.command.includes("\\")){if(!e.fileExists(f.command)){t.push({check:"client-config",level:"error",message:`${p.label} points at ${f.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${p.path} (after ${Qr(r)})`});continue}}else if(f.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${p.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:Qr(r,e.nvmDefault)});continue}g||(f.command.includes("/")||f.command.includes("\\")?c(f.command,p.label):f.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,p.label)),t.push({check:"client-config",level:"ok",message:`${p.label}: ${[f.command,...f.args].join(" ")}`})}if(o||t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${er} install`}),e.latestVersion!==null)for(let[p,f]of a){let m=f.clients.join(", ");if(f.version===null)t.push({check:"version",level:"info",message:`${m}: cannot tell which bridge version ${p} is.`});else if(up(f.version,e.latestVersion)<0){let g=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(p)?.[1]??null;t.push({check:"version",level:"warn",message:`${m} run bridge ${f.version} (${p}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:g?Qr(e.latestVersion,g):`npx -y ${er}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${m} run bridge ${f.version} (published: ${e.latestVersion}).`})}for(let{dir:p,maind:f}of e.npxStaleDirs)t.push({check:"npx-cache",level:f?"error":"info",message:f?`a half-built better-sqlite3 was left in ${p} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${p} (another tool's npx entry, not maind's).`,fix:`rm -rf '${p.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!Hk.test(e.deviceId))&&t.push({check:"credentials",level:"error",message:"no valid device id \u2014 the server binds keys to a device, so every call ends in 401 invalid_or_device_required.",fix:"maind-mcp-bridge --reauth"}),l===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):gF.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&Hk.test(e.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=e.connection;if(d===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):d.outcome==="ok"||d.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):t.push({check:"connection",level:"error",message:d.outcome==="auth_failed"?`the server rejected the last connection (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"}),e.claudeSettings!==null){let p=Re(e.claudeSettings,{fileExists:s(m=>e.fileExists(m),"fileExists")}),f=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let m of p){if(m.status==="missing"||m.status==="superseded")continue;if(m.status!=="ok"){t.push({check:"hooks",level:m.status==="broken"?"error":"warn",message:m.detail});continue}let g=m.command?/(\S+\/build\/index\.js)/.exec(m.command)?.[1]??null:null,y=g?e.installVersionOf(g):null;y!==null&&f!==null&&y!==f&&t.push({check:"hooks",level:"warn",message:`${m.event}/${m.subcommand} runs bridge ${y}, the MCP server runs ${f} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${m.subcommand}`})}t.some(m=>m.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}if(e.claudeSettings!==null){let p=e.guardMode??"off",f=Ca(e.claudeSettings,{guardMode:p,fileExists:s(_=>e.fileExists(_),"fileExists")}),g=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${er}`)} install --hooks-only`,y=(e.declinedHooks??[]).includes(st);f.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${st} hook).`}):f.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${st} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):f.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${p}); without the core ${st} hook it stops when the guard is switched off.`,fix:g}):y?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${st} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:g}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${st}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:g})}if(e.claudeSettings!==null){let p=Re(e.claudeSettings,{fileExists:s(f=>e.fileExists(f),"fileExists")},[hF])[0];if(p.status==="superseded"){let f=e.foreignHookHosts??[],m=f.includes("cursor"),g=(e.declinedHooks??[]).includes(Hn),y=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${er}`),_=p.remedy==="run-install"?`${y} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${y} ${Hn}`,b=m?`Cursor, installed here, imports it from ~/.claude/settings.json and takes only JSON at session start \u2014 it gets plain text it cannot parse${f.includes("devin")?"; Devin Local gets text whose handling it does not document":""}`:f.includes("devin")?"Devin Local, installed here, runs it too and documents only JSON context for hooks":"it is fine in Claude Code, but Cursor and Devin Local, which import the same hooks, would get plain text";t.push({check:"hook-hosts",level:m&&!g?"warn":"info",message:`the SessionStart reminder hook still runs \`${p.command}\` \u2014 ${b}. ${Hn} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:_})}}let u=e.context??null;if(u!==null&&e.claudeSettings!==null){let p=Re(e.claudeSettings,{fileExists:s(f=>e.fileExists(f),"fileExists")}).filter(f=>(f.subcommand==="on-prompt-context"||f.subcommand==="on-read-context")&&f.status!=="missing").map(f=>f.subcommand);if(p.length>0){let f=t.length;u.sqlite.ok?u.repoRoot!==null&&!u.indexPresent&&t.push({check:"context",level:"info",message:`${u.repoRoot} has no code index \u2014 on-read-context stays silent there, and on-prompt-context can only match conventions.`,fix:"ask your agent to run codebase_index once (or run `maind index` in the repo); the Stop hook keeps it fresh after that"}):t.push({check:"context",level:"warn",message:`${p.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${u.sqlite.reason}). They stay silent.`,fix:"update Node to >= 22.16 (builtin SQLite), or run `npm rebuild better-sqlite3` in the bridge's install prefix"}),p.includes("on-prompt-context")&&u.repoRoot!==null&&!u.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${u.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===f&&t.push({check:"context",level:"ok",message:`${p.join(" and ")}: code index and cached conventions present${u.repoRoot?` for ${u.repoRoot}`:""}.`})}}return t}function Uk(e){let t=e.filter(i=>i.level==="error"&&pp.includes(i.check)).sort((i,o)=>pp.indexOf(i.check)-pp.indexOf(o.check)),n=t[0];if(n===void 0)return yF(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 yF(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?_F(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 _F(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?null:`[maind] setup gap \u2014 ${t.message}`+(t.fix?` To switch to it, run in a terminal (asks consent, replaces only that entry): ${t.fix}`:"")}function Bk(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,c)=>n[a.level]-n[c.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),i=e.filter(a=>a.level==="error").length,o=e.filter(a=>a.level==="warn").length;return r.push("",i+o===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${o} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
785
795
|
`)+`
|
|
786
|
-
`}var
|
|
787
|
-
`,i),a=o===-1?e.length:o+1,c=e.slice(i,o===-1?e.length:o).replace(/\r$/,"");if(n!==null||r>0){let l=
|
|
796
|
+
`}var er,hF,gF,Hk,pp,Ya=w(()=>{"use strict";Ia();ct();er="@maind-dev/mcp-bridge",hF=at.find(e=>e.subcommand===Hn),gF=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,Hk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(up,"compareVersions");s(fp,"maindEntry");s(Qr,"installFix");s(Ja,"diagnose");pp=["connection","client-config","npx-cache","hooks"];s(Uk,"sessionStartLine");s(yF,"briefingGapLine");s(_F,"hookHostsGapLine");s(Bk,"renderFindings")});import{parse as Wk}from"smol-toml";function Vk(e){let t;try{t=Wk(e)}catch{return null}if(!Tt(t)||!Tt(t.mcp_servers)||!Tt(t.mcp_servers.maind))return null;let n=Object.keys(t.mcp_servers).filter(u=>u!=="maind").length,r=Object.keys(t).filter(u=>u!=="mcp_servers"),i=[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[]],o=kF(e);if(o===null)return{action:"manual",next:null,stays:i};let a=bF(o),l=o.some(u=>u.comment&&!a.some(([p,f])=>u.start>=p&&u.end<=f))?[...i,"comments"]:i;if(l.length===0)return{action:"delete",next:null,stays:l};if(a.length===0)return{action:"manual",next:null,stays:l};let d=wF(e,a);return vF(t,d)?{action:"edit",next:d,stays:l}:{action:"manual",next:null,stays:l}}function bF(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.kind!=="header"||i.path?.[0]!=="mcp_servers"||i.path[1]!=="maind")continue;let o=r;for(let c=r+1;c<e.length&&e[c].kind!=="header";c++)(e[c].kind==="keyval"||e[c].kind==="continuation")&&(o=c);let a=r;for(;a>0&&e[a-1].kind==="blank";)a--;t.push([e[a].start,e[o].end])}let n=[];for(let[r,i]of t){let o=n.at(-1);o!==void 0&&r<=o[1]?o[1]=Math.max(o[1],i):n.push([r,i])}return n}function wF(e,t){let n=e;for(let[r,i]of[...t].reverse())n=n.slice(0,r)+n.slice(i);return t[0]?.[0]===0&&(n=n.replace(/^(?:[ \t]*\r?\n)+/,"")),n}function vF(e,t){let n;try{n=Wk(t)}catch{return!1}if(!Tt(n))return!1;let r={...e.mcp_servers};delete r.maind;let i={...e,mcp_servers:r};return mp(Kk(i),Kk(n))}function Kk(e){if(!Tt(e.mcp_servers)||Object.keys(e.mcp_servers).length>0)return e;let t={...e};return delete t.mcp_servers,t}function mp(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&JSON.stringify(e)===JSON.stringify(t);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>mp(n,t[r]));if(Tt(e)||Tt(t)){if(!Tt(e)||!Tt(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>r in t&&mp(e[r],t[r]))}return Object.is(e,t)}function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function kF(e){let t=[],n=null,r=0;for(let i=0;i<e.length;){let o=e.indexOf(`
|
|
797
|
+
`,i),a=o===-1?e.length:o+1,c=e.slice(i,o===-1?e.length:o).replace(/\r$/,"");if(n!==null||r>0){let l=Gk(c,0,n,r);if(l===null)return null;({open:n,depth:r}=l),t.push({start:i,end:a,kind:"continuation",comment:l.comment})}else{let l=c.search(/[^ \t]/);if(l===-1)t.push({start:i,end:a,kind:"blank",comment:!1});else if(c[l]==="#")t.push({start:i,end:a,kind:"comment",comment:!0});else if(c[l]==="["){let d=SF(c,l);if(d===null)return null;let u=c.slice(d.end).trimStart();if(u.length>0&&!u.startsWith("#"))return null;t.push({start:i,end:a,kind:"header",comment:u.length>0,path:d.path})}else{let d=Gk(c,l,null,0);if(d===null)return null;({open:n,depth:r}=d),t.push({start:i,end:a,kind:"keyval",comment:d.comment})}}i=a}return n===null&&r===0?t:null}function Gk(e,t,n,r){let i=t;for(;i<e.length;){if(n!==null){let a=hp(e,i,n);if(a===-1)return{open:n,depth:r,comment:!1};n=null,i=a;continue}let o=e[i];if(o==="#")return{open:n,depth:r,comment:!0};if(o==='"'||o==="'"){if(e.startsWith(o.repeat(3),i)){n=o==='"'?'"""':"'''",i+=3;continue}let a=hp(e,i+1,o);if(a===-1)return null;i=a;continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r<0))return null;i++}return{open:n,depth:r,comment:!1}}function hp(e,t,n){if(n==="'"||n==="'''"){let r=e.indexOf(n,t);if(r===-1)return-1;let i=r+n.length;if(n==="'''")for(;i<r+5&&e[i]==="'";)i++;return i}for(let r=t;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(n==='"'&&e[r]==='"')return r+1;if(n==='"""'&&e.startsWith('"""',r)){let i=r+3;for(;i<r+5&&e[i]==='"';)i++;return i}r++}return-1}function SF(e,t){let n=e[t+1]==="[",r=n?"]]":"]",i=t+(n?2:1),o=[];for(;;){for(;e[i]===" "||e[i]===" ";)i++;let a=xF(e,i);if(a===null)return null;for(o.push(a.value),i=a.end;e[i]===" "||e[i]===" ";)i++;if(e[i]==="."){i++;continue}return e.startsWith(r,i)?{path:o,end:i+r.length}:null}}function xF(e,t){if(e[t]==='"'){let r=hp(e,t+1,'"');if(r===-1)return null;try{return{value:JSON.parse(e.slice(t,r)),end:r}}catch{return null}}if(e[t]==="'"){let r=e.indexOf("'",t+1);return r===-1?null:{value:e.slice(t+1,r),end:r+1}}let n=/^[A-Za-z0-9_-]+/.exec(e.slice(t));return n===null?null:{value:n[0],end:t+n[0].length}}var zk=w(()=>{"use strict";s(Vk,"planTomlPhantomRemoval");s(bF,"maindTableRanges");s(wF,"applyCut");s(vF,"sameWithoutMaind");s(Kk,"dropEmptyServers");s(mp,"sameValue");s(Tt,"isTable");s(kF,"scanLines");s(Gk,"scanValue");s(hp,"closeOf");s(SF,"parseHeader");s(xF,"readKey")});import{findNodeAtLocation as EF,parse as qk,parseTree as TF,stripComments as RF}from"jsonc-parser";function Jk(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||fp(n)===null)continue;if(n.kind==="toml"){let f=AF(n,n.raw);f!==null&&t.push(f);continue}let r=[],i=qk(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!gp(i))continue;let o=gp(i.servers)&&"maind"in i.servers?"servers":"mcpServers",a=i[o];if(!gp(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(i).filter(f=>f!==o),d=RF(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=CF(n.raw,[o,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${o}.maind by hand \u2014 it cannot be cut out cleanly; stays: ${u}`}:{label:n.label,path:n.path,action:"edit",raw:n.raw,next:p,keeps:`remove ${o}.maind; stays: ${u}`})}return t}function AF(e,t){let n=Vk(t);if(n===null)return null;let r={label:e.label,path:e.path,raw:t},i=n.stays.length>0?`; stays: ${n.stays.join(", ")}`:"";switch(n.action){case"delete":return{...r,action:"delete",next:null,keeps:null};case"edit":return{...r,action:"edit",next:n.next,keeps:`remove [mcp_servers.maind]${i}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove [mcp_servers.maind] by hand \u2014 it cannot be cut out cleanly${i}`}}}function CF(e,t){let n=TF(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:EF(n,[...t])?.parent,i=r?.parent?.children;if(r===void 0||r.type!=="property"||i===void 0)return null;let o=i.indexOf(r),a=r.offset,c=r.offset+r.length;if(o+1<i.length)c=i[o+1].offset;else if(o>0){let u=i[o-1];a=u.offset+u.length}else{let u=r.parent;u!==void 0&&e.slice(u.offset+1,r.offset).trim()===""&&(a=u.offset+1);let p=/^\s*,/.exec(e.slice(c));p&&(c+=p[0].length)}let l=e.slice(0,a)+e.slice(c),d=[];return qk(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function Yk(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
|
|
788
798
|
`;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(`
|
|
789
799
|
`)+`
|
|
790
|
-
`}function
|
|
791
|
-
`);continue}if(
|
|
792
|
-
`),n++;continue}try{r.action==="delete"?
|
|
800
|
+
`}function gp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Xk=w(()=>{"use strict";Ya();zk();s(Jk,"planPhantomRemovals");s(AF,"tomlRemoval");s(CF,"withoutProperty");s(Yk,"renderPhantomPlan");s(gp,"isObject")});var nS={};X(nS,{contextProbe:()=>tS,realProbe:()=>go,resolveNvmAlias:()=>eS,runDoctor:()=>KF});import{execFileSync as IF}from"node:child_process";import{existsSync as mo,readFileSync as NF,readdirSync as yp,realpathSync as OF,unlinkSync as DF}from"node:fs";import{homedir as ho,platform as Xa}from"node:os";import{delimiter as PF,dirname as Zk,join as ue}from"node:path";function Rt(e){try{return mo(e)?NF(e,"utf8"):null}catch{return null}}function MF(){try{let e=IF(Xa()==="win32"?"npm.cmd":"npm",["view",Qk,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function _p(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ue(ho(),".nvm")}function $F(){let e=ue(_p(),"versions","node"),t=[];try{t=yp(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Rt(ue(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),i=null;try{i=r?JSON.parse(r).version??null:null}catch{i=null}return{node:n,bridgeVersion:i}})}function eS(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(d[p]!==u[p])return(d[p]??0)-(u[p]??0);return 0});if(r==="node"||r==="stable")return i.at(-1)??null;let o=r.startsWith("v")?r:`v${r}`;if(t.includes(o))return o;let a=o.endsWith(".")?o:`${o}.`;return i.filter(c=>c.startsWith(a)).at(-1)??null}function LF(e){let t=Rt(ue(_p(),"alias","default"));return t===null?null:eS(t,e.map(n=>n.node),n=>{let r=Rt(ue(_p(),"alias",n));return r===null?null:r})}function FF(){let e=Xa()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(PF))if(t)for(let n of e){let r=ue(t,n);if(mo(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function jF(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Xa()==="win32"?ue(process.env.LOCALAPPDATA??ue(ho(),"AppData","Local"),"npm-cache"):ue(ho(),".npm"),t=ue(e,"_npx"),n=[],r=[];try{r=yp(t)}catch{return[]}for(let i of r)try{let o=yp(ue(t,i,"node_modules"));o.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:ue(t,i),maind:o.includes("@maind-dev")})}catch{}return n}function HF(e){let t;try{t=Zk(OF(e))}catch{return null}for(let n=0;n<6;n++){let r=Rt(ue(t,"package.json"));if(r!==null)try{let o=JSON.parse(r);if(o.name===Qk)return o.version??null}catch{}let i=Zk(t);if(i===t)break;t=i}return null}function tS(e){let t=Jt(e),n=!1;try{let i=Rt(zr);n=i!==null&&typeof JSON.parse(i).conventions=="string"}catch{n=!1}let r=Ea();return{repoRoot:t,indexPresent:t!==null&&mo(ue(t,qt)),conventionsCached:n||t!==null&&mo(ue(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function go(e=process.cwd(),t={}){let n=$F(),r=Rt(ue(Ve(),"device-id")),i=Vi({projectRoot:e,homeDir:ho(),platform:Xa(),env:process.env,bridgeEntry:ge()}),o=null;try{o=z()}catch{o=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=ee(),l=xe({entryPath:ge(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:U,latestVersion:t.offline===!0?null:MF(),nodeTrees:n,nvmDefault:LF(n),pathWinner:FF(),clientConfigs:Wi(i).map(d=>({label:d.label,path:d.path,kind:d.kind,raw:Rt(d.path),present:d.presence===void 0?null:Dr(d.presence,Wt)})),npxStaleDirs:jF(),connection:B_(),claudeSettings:Rt(ue(ho(),".claude","settings.json")),fileExists:s(d=>mo(d),"fileExists"),installVersionOf:HF,deviceId:r===null?null:r.trim(),apiKey:o,envApiKey:a.length>0?a:null,guardMode:le(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?it(l):null,context:t.offline===!0?null:tS(e),foreignHookHosts:UF(i)}}function UF(e){let t=[];try{Dr(Pn(e),Wt)&&t.push("cursor"),Dr(Fs(e),Wt)&&t.push("devin")}catch{}return t}async function BF(e){let t=Jk(go(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(Yk(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
|
|
801
|
+
`);continue}if(Rt(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
|
|
802
|
+
`),n++;continue}try{r.action==="delete"?DF(r.path):await V(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
|
|
793
803
|
`)}catch(i){process.stdout.write(` failed ${r.path}: ${i instanceof Error?i.message:String(i)}
|
|
794
|
-
`),n++}}return n>0?1:0}async function
|
|
795
|
-
`):process.stdout.write(
|
|
804
|
+
`),n++}}return n>0?1:0}async function KF(e){if(e.includes("--remove-phantoms"))return BF(e.includes("--yes"));let t=Ja(go());return e.includes("--json")?process.stdout.write(JSON.stringify({version:U,findings:t},null,2)+`
|
|
805
|
+
`):process.stdout.write(Bk(t)),t.some(n=>n.level==="error")?1:0}var Qk,bp=w(()=>{"use strict";Ce();Bd();Xn();la();Qt();ie();dt();Kt();we();Mn();Ks();ze();Ya();Xk();Qk="@maind-dev/mcp-bridge";s(Rt,"readOrNull");s(MF,"latestVersion");s(_p,"nvmDir");s($F,"nodeTrees");s(eS,"resolveNvmAlias");s(LF,"nvmDefault");s(FF,"pathWinner");s(jF,"npxStaleDirs");s(HF,"installVersionOf");s(tS,"contextProbe");s(go,"realProbe");s(UF,"foreignHookHosts");s(BF,"removePhantoms");s(KF,"runDoctor")});function rS(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function oS(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,o=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of o){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(u)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function ei(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function yo(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function sS(e,t,n){let r=n.maxAgeMs??iS,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=oS(e,o),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)rS(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 ${yo(l.last_seen_seconds+o)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${yo(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(rS(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${yo(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${yo(o)} ago, advisory \u2014 never a lock):
|
|
796
806
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
797
807
|
`)+`
|
|
798
|
-
Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function
|
|
799
|
-
${m}`:m}var
|
|
808
|
+
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 aS(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 cS(e,t,n,r=iS,i=null){if(!e)return null;let o=n-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let a=o/1e3,c=oS(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",f=u>0?`, ${u} presence-only`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${yo(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
809
|
+
${m}`:m}var iS,wp=w(()=>{"use strict";s(rS,"prefixConflict");iS=10*6e4;s(oS,"parsePeers");s(ei,"selectOwnSnapshot");s(yo,"ageDisplay");s(sS,"adviseOnPath");s(aS,"claimedIdentity");s(cS,"sessionStartSummary")});function dS(e){let t=[];for(let n of uS(e)){let r=YF(n);r&&!t.includes(r)&&t.push(r)}return t}function uS(e){let t=[],n="",r=null,i=0,o=[],a=s(()=>{n.trim()&&t.push(n),n=""},"flush");for(;i<e.length;){let c=e[i];if(r){if(c==="\\"&&r==='"'){n+=c+(e[i+1]??""),i+=2;continue}c===r&&(r=null),n+=c,i+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,i+=1;continue}if(c==="<"&&e[i+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(i));if(l){o.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
|
|
800
810
|
`){if(o.length>0){let d=e.slice(i+1).split(`
|
|
801
|
-
`),u=0;for(;o.length>0&&u<d.length;)d[u].trim()===o[0]&&o.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,f)=>p+f.length+1,0),o=[],a();continue}a(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){a(),i+=2;continue}if(c===";"||c==="|"){a(),i+=1;continue}n+=c,i+=1}return a(),t}function
|
|
811
|
+
`),u=0;for(;o.length>0&&u<d.length;)d[u].trim()===o[0]&&o.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,f)=>p+f.length+1,0),o=[],a();continue}a(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){a(),i+=2;continue}if(c===";"||c==="|"){a(),i+=1;continue}n+=c,i+=1}return a(),t}function YF(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(WF.test(a)){n+=1;continue}if(zF.has(a)){n+=1;continue}if(qF.has(a))return null;let c=a.split("/").pop()??a;if(VF.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!lS.test(i))return null;if(!GF.test(i))return vp;if(!JF.has(i))return i;let o=t[n+1];return o&&lS.test(o)?`${i} ${o}`:i}function kp(e){let t=dS(e).filter(n=>n!==vp&&!pS.has(n));return t.length>0?t[t.length-1]:null}var lS,GF,vp,WF,VF,zF,qF,JF,pS,Sp=w(()=>{"use strict";lS=/^[A-Za-z][A-Za-z0-9._-]*$/,GF=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,vp="?",WF=/^[A-Za-z_][A-Za-z0-9_]*=/,VF=new Set(["sudo","env","time","nohup","nice","command","exec"]),zF=new Set(["do","then","else","elif","if","while","until","!","{","("]),qF=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),JF=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(dS,"shellPrograms");s(uS,"commandSegments");s(YF,"programOf");pS=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(kp,"primaryVerb")});function fS(e){let t=e.length>xp?e.slice(-xp):e;return XF.some(n=>n.test(t))}function Ep(e){return e.includes("maind")?ZF.some(t=>e.includes(t)):!1}function mS(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function hS(e,t){if(!mS(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?kp(n):null}function Tp(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=hS(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&fS(e.output)?"fail":"ok",verb:t}}var xp,XF,ZF,gS=w(()=>{"use strict";Sp();xp=8192,XF=[/\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(fS,"outputShowsFailure");ZF=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];s(Ep,"isConsultationTool");s(mS,"isCountedTool");s(hS,"verbOfCall");s(Tp,"observe")});function yS(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 Rp(e,t=-1/0){let n=e.filter(o=>o.k==="fail"&&o.t>t).slice().sort((o,a)=>o.t-a.t),r=[],i=[];for(let o of n)i.length>0&&o.t-i[i.length-1].t>6e5&&(r.push(yS(i)),i=[]),i.push(o);return i.length>0&&r.push(yS(i)),r}function Ap(e,t,n){if(t===null)return null;let r=null;for(let i of e)i.k==="ok"&&i.v===t&&i.t>n&&(r===null||i.t<r)&&(r=i.t);return r}function _S(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function ti(e,t,n){let r=_S(e,t),i=Rp(e,r),o=i.length>0?i[i.length-1]:null,a=o!==null&&n-o.end<=6e5?o:null;if(a===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=Ap(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 Cp(e){return e.open&&!e.nudged}function Ip(e,t){let n=-1/0;for(let o of e)o.k==="prompt"&&o.t>n&&(n=o.t);let r=Math.max(t,n),i=Rp(e,r);for(let o=i.length-1;o>=0;o--){let a=i[o];if(a.failures.length<5||a.end-a.start<3e5)continue;let c=Ap(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function _o(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 Np=w(()=>{"use strict";s(yS,"chainOf");s(Rp,"failureChains");s(Ap,"succeededAfter");s(_S,"resetPoint");s(ti,"difficultyStatus");s(Cp,"shouldNudge");s(Ip,"captureCandidate");s(_o,"verbSummary")});function ej(e){let t=e.id;if(typeof t!="string")return null;let n=e.version,r=typeof n=="number"&&Number.isInteger(n)&&n>=1?n:1,i=e.severity,o=typeof i=="string"&&QF.has(i)?i:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:o,enabled:a}}function Qa(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return wo;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let o=ej(i);o!==null&&(o.id===bo?n=o:o.id===Za&&(r=o))}return{difficulty:n,capture:r}}function ni(e){return e!==null&&e.enabled}function Op(e){return ni(e)&&e.severity==="required"}var bo,Za,wo,QF,Dp=w(()=>{"use strict";bo="conv_consult_on_difficulty",Za="conv_learning_capture_offer",wo={difficulty:null,capture:null},QF=new Set(["required","recommended","info"]);s(ej,"ruleOf");s(Qa,"extractTriggerPolicy");s(ni,"isActive");s(Op,"isDenyCapable")});function tj(e){return Math.max(1,Math.round(e/6e4))}function vo(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${_o(e)}) and no maind consultation since they started (${bo}). 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 Pp(e){return`difficulty episode (${e.failures.length} failed attempts: ${_o(e)}) without a maind consultation since it started (${bo}, required)`}function Mp(e,t="guard"){let n=tj(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${Za}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${_o(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 bS=w(()=>{"use strict";Np();Dp();s(tj,"minutes");s(vo,"nudgeText");s(Pp,"difficultyDenyHead");s(Mp,"captureText")});var ri=w(()=>{"use strict";Sp();gS();Np();Dp();bS()});function nj(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":ne()}}async function vS(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:nj(t),body:JSON.stringify({metrics:n})});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:o.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var ec,$p=w(()=>{"use strict";ie();Cr();ec=process.env.MAIND_ENDPOINT??Ar("mcp-client-metrics-ingest");s(nj,"ingestHeaders");s(vS,"postMetrics")});import{realpathSync as rj}from"node:fs";import{basename as kS,dirname as SS,join as ij}from"node:path";function tr(e){let t=SS(e),n=[kS(e)];for(;;)try{let r=rj(t);return ij(r,...n.reverse())}catch{let r=SS(t);if(r===t)return e;n.push(kS(t)),t=r}}var tc=w(()=>{"use strict";s(tr,"realpathOfUnwritten")});import{existsSync as oj,realpathSync as sj,statSync as aj}from"node:fs";import{dirname as xS,isAbsolute as cj,join as lj}from"node:path";function pj(e,t){let n=e.filter(i=>ES.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let o=i.hint?`
|
|
802
812
|
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
803
813
|
${i.detail}${o}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
804
814
|
|
|
@@ -806,133 +816,133 @@ ${m}`:m}var Ik,ap=v(()=>{"use strict";s(Ak,"prefixConflict");Ik=10*6e4;s(Nk,"par
|
|
|
806
816
|
|
|
807
817
|
`)+`
|
|
808
818
|
|
|
809
|
-
This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function
|
|
819
|
+
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 fj(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function mj(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},o=i[t]??{};o[n]=new Date(r).toISOString(),i[t]=o,e.repo_health_seen=i}function Lp(e){let t=xS(e);for(;;){try{if(aj(t).isDirectory())return t}catch{}let n=xS(t);if(n===t)return t;t=n}}async function hj(e,t,n){let r=await n.load();if(fj(r,e,t))return null;mj(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let o=i.filter(c=>ES.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:dj,metric_value:1},{session_id:e,metric_key:uj,metric_value:o}),await n.save(a),pj(i,t)}async function TS(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=oe(e);if(!_e(n,{kind:"context",event:"PreToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return 0;let i=je(e);if(!i)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=cj(i)?i:lj(o,i),c=oj(a)?sj(a):tr(a),l=We(Lp(c));try{aa()&&yw(l,{memoryPath:jr})}catch{}let d=await hj(r,l,{load:Z,save:lt,check:s(async u=>(await Ai(u,{includeRelease:!1})).findings,"check")});if(d!==null){let u=ce(n,{kind:"context",event:"PreToolUse",text:d});u!==null&&process.stdout.write(u)}return 0}catch{return 0}}var ES,dj,uj,Fp=w(()=>{"use strict";Bt();vt();ca();Ne();ye();tc();Ie();ES=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],dj="repo_health_hook_runs",uj="repo_health_hook_findings";s(pj,"formatRepoHealth");s(fj,"alreadySeen");s(mj,"markSeen");s(Lp,"nearestExistingDir");s(hj,"repoHealthForEdit");s(TS,"runOnRepoHealth")});import{existsSync as gj,readFileSync as yj,realpathSync as _j}from"node:fs";import{isAbsolute as AS,join as CS,posix as bj,relative as wj,sep as vj}from"node:path";function RS(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function Tj(e,t){return{contracts:t.filter(r=>RS(r.spec)===e||RS(r.impl)===e).map(r=>r.id),theme:xj.test(e),acl:Ej.test(e)}}function Rj(e){return e.contracts.length===0&&!e.theme&&!e.acl}function Aj(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},o[t]=a,e.write_health_seen=o}return l}function Cj(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:
|
|
810
820
|
|
|
811
821
|
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
812
822
|
`)+`
|
|
813
823
|
|
|
814
|
-
Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function
|
|
815
|
-
`)}catch{}let r=await
|
|
816
|
-
`);let p
|
|
817
|
-
`)}}catch{}try{let o=
|
|
818
|
-
`)}}catch{}return 0}function
|
|
819
|
-
`)}}}catch{}return 0}function
|
|
824
|
+
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 Ij(e,t){let n=wj(e,t);return!n||n.startsWith("..")||AS(n)?null:n.split(vj).join(bj.sep)}function Nj(e){try{let t=yj(CS(e,ps),"utf8"),{manifest:n}=gs(t);return n?.contracts??[]}catch{return[]}}async function IS(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=oe(e);if(!_e(n,{kind:"context",event:"PostToolUse"}))return 0;let r=typeof e.session_id=="string"?e.session_id:"",i=je(e);if(!r||!i)return 0;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=AS(i)?i:CS(o,i),c=gj(a)?_j(a):tr(a),l=We(Lp(c)),d=Ij(l,c);if(d===null)return 0;let u=Tj(d,Nj(l));if(Rj(u))return 0;let p=[];if(u.contracts.length>0)try{let y=await Rn(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=Cn(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=An(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 Z(),m=Aj(f,r,l,p);f.pending_metrics.push({session_id:r,metric_key:kj,metric_value:1},{session_id:r,metric_key:Sj,metric_value:m.length}),await lt(f);let g=Cj(m,d);if(g!==null){let y=ce(n,{kind:"context",event:"PostToolUse",text:g});y!==null&&process.stdout.write(y)}return 0}catch{return 0}}var kj,Sj,xj,Ej,NS=w(()=>{"use strict";Bt();vt();Ne();ye();Fp();tc();Ie();kj="write_health_hook_runs",Sj="write_health_hook_findings",xj=/\.(tsx?|jsx?|css)$/,Ej=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(RS,"declPath");s(Tj,"routesForPath");s(Rj,"routesAreEmpty");s(Aj,"takeUnreported");s(Cj,"formatWriteHealth");s(Ij,"repoRelative");s(Nj,"readContracts");s(IS,"runOnWriteHealth")});var WS={};X(WS,{agentHostPidCandidates:()=>rn,closeSessionMetrics:()=>oc,closeTrackedSession:()=>jS,effectiveConfig:()=>on,flushSessionMetrics:()=>sc,grandparentPid:()=>US,isCaptureTool:()=>jp,recordGuardSignals:()=>FS,runFlush:()=>Yj,runHookStatus:()=>Xj,runOnFileEdit:()=>Vj,runOnFileWrite:()=>Wj,runOnRepoHealth:()=>TS,runOnSessionStart:()=>Fj,runOnToolUse:()=>Bj,runOnWriteHealth:()=>IS,runSessionEndMetrics:()=>Jj,runSyncConfig:()=>Qj,writeIdentitySideChannel:()=>Hp});import{execFileSync as DS}from"node:child_process";import{existsSync as ic,readFileSync as PS,realpathSync as Oj}from"node:fs";import{writeFile as Dj}from"node:fs/promises";import{homedir as MS}from"node:os";import{isAbsolute as rc,join as ko,relative as $S}from"node:path";function FS(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=Ep(n),o=n.includes("review_changes")||n.includes("review_verdict"),a=jp(n);if(!i&&!o&&!a)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),o&&(l.reviewed_at=d),a&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function jp(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 jS(e,t,n=Date.now()){$j(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function $j(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-i>nc&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o)||0));t-i>nc&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o.at)||0));t-i>nc&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>nc&&delete e.sessions[n]}}function on(e){if(e.config)return e.config;let t=z();return t===null?null:{api_key:t,endpoint:ec}}function HS(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 Lj(e){let t=_e(e,{kind:"text",event:"SessionStart"});if(!tn(e.host))return{speaks:t,line:s(r=>void process.stdout.write(r),"line"),flush:s(async()=>{},"flush")};let n=[];return{speaks:t,line:s(r=>{t&&n.push(r)},"line"),flush:s(async()=>{if(n.length===0)return;let r=ce(e,{kind:"text",event:"SessionStart",text:n.join("")});r!==null&&await Ra(r)},"flush")}}async function Fj(){let e=await G(),t=oe(e),n=Lj(t);try{return await jj(e,t,n)}finally{await n.flush()}}async function jj(e,t,n){if(n.speaks)try{let o=Uk(Ja(go(process.cwd(),{offline:!0})));o!==null&&n.line(o+`
|
|
825
|
+
`)}catch{}let r=await Z();if(on(r)===null)return 0;let i=GS(e);if(i===null)return 0;HS(r,i),await lt(r);try{Hp(e,i)}catch{}try{let o=n.speaks?te():null;if(o!==null){let a=Xr(o),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=ei(a,{hostPids:rn(),cwd:c}),d=aS(l?.snap??null,fo(Vr(e)||null,i)),u=cS(l?.snap??a[0]??null,d.id,Date.now(),void 0,d.announceError);u!==null&&n.line(u+`
|
|
826
|
+
`);let p=$o(Sc(i,BS(l?.snap??null,a,Date.now()),Date.now()));p!==null&&n.line(`[maind] ${p}
|
|
827
|
+
`)}}catch{}try{let o=tn(t.host)?[]:Re(Hj());if(Qd(o)&&qs(o)){let a=s(u=>o.filter(p=>p.remedy==="run-install"&&p.status===u).map(p=>p.subcommand).join(", "),"pick"),c=a("missing"),l=a("superseded"),d=[c?`not yet wired: ${c}`:null,l?`old form to replace: ${l}`:null].filter(u=>u!==null).join("; ");process.stderr.write(`[maind] New bridge capability (${d}) \u2014 run \`maind-mcp-bridge install --hooks-only\` once (asks consent per hook; adds what is missing and rewrites no entry of yours but the reminder's old \`cat\`).
|
|
828
|
+
`)}}catch{}return 0}function Hj(){try{let e=ko(MS(),".claude","settings.json");return ic(e)?PS(e,"utf8"):null}catch{return null}}function Hp(e,t,n,r=Zr()){let i=n??rn();if(i.length===0)return;let o=fo(Vr(e)||null,t);if(o===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=Vr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)Pk({dir:r,agentPid:d,sessionId:t,transcriptStem:o,cwd:a,transcriptPath:c,model:l})}function US(){try{if(process.platform==="win32")return null;let e=DS("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 rn(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=US();return n!==null&&n>1&&n!==t&&e.push(n),e}async function Bj(){let e=await Z();if(on(e)===null)return 0;let t=await G(),n=GS(t)??"unknown",r=HS(e,n);r.tool_call_count+=1;try{let c=rn().filter(l=>Mk(Zr(),l,Uj));n!=="unknown"&&c.length>0&&Hp(t,n,c)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),FS(e,n,i),jp(i)&&n!=="unknown"&&await Q({event:"capture_taken",session_id:n,detail:i});let o=t.transcript_path;if(typeof o=="string"&&o&&!r.transcript_path&&(r.transcript_path=o),r.transcript_path){let c=await lu(r.transcript_path);c&&(r.token_count=c.total_tokens,await qj(e,r))}await lt(e);let a=oe(t);try{let c=Date.now();if(n!=="unknown"&&_e(a,{kind:"context",event:"PreToolUse"})&&!$f(n,c)){let l=te();if(l!==null){let d=Xr(l),u=ei(d,{hostPids:rn(),cwd:typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd()}),p=$o(Sc(n,BS(u?.snap??null,d,c),c)),f=p===null?null:ce(a,{kind:"context",event:"PreToolUse",text:`[maind] ${p}`});f!==null&&process.stdout.write(f+`
|
|
829
|
+
`)}}}catch{}return 0}function BS(e,t,n){return e!==null?e.announce_error?[]:e.assigned_to_you??[]:t.find(i=>!i.announce_error&&n-Date.parse(i.written_at)<Kj)?.assigned_to_you??[]}function Gj(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
820
830
|
`);return`${t.prefix}${e.number} is already taken:
|
|
821
831
|
${n}
|
|
822
832
|
|
|
823
833
|
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
824
834
|
|
|
825
|
-
Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function
|
|
835
|
+
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 Wj(){try{let e=await G();if((e.tool_name??"")!=="Write")return 0;let t=oe(e);if(!_e(t,{kind:"deny"}))return 0;let n=je(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=rc(n)?n:ko(r,n);if(ic(i))return 0;let o=We(r),a=$S(o,tr(i));if(a.length===0||a.startsWith("..")||rc(a))return 0;let c=await Tn(o,a);if(!c.taken||c.namespace===null)return 0;let l=ce(t,{kind:"deny",reason:Gj(c,c.namespace)});return l!==null&&process.stdout.write(l),0}catch{return 0}}async function Vj(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=oe(e);if(!_e(n,{kind:"context",event:"PreToolUse"}))return 0;let r=je(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=rc(r)?r:ko(i,r),a=te();if(a===null)return 0;let c=Xr(a);if(c.length===0)return 0;let l=ei(c,{hostPids:rn(),cwd:i});if(l===null)return 0;let d=We(i),u=ic(o)?Oj(o):tr(o),p=$S(d,u).replace(/\\/g,"/");if(p.length===0||p.startsWith("..")||rc(p))return 0;let f=sS(l.snap,p,{via:l.via,currentBranch:l.via==="cwd"?zj(i):null,nowMs:Date.now()});if(f===null)return 0;let m=ce(n,{kind:"context",event:"PreToolUse",text:f});return m!==null&&process.stdout.write(m),0}catch{return 0}}function zj(e){try{let n=DS("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 qj(e,t){let n=Iu(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,o="ok";if(i>=n.handoff_at_pct/100?o="handoff_recommended":i>=n.warn_at_pct/100&&(o="warn"),t.last_advisory_status===o||(t.last_advisory_status=o,o==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:o,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:o==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await Dj(ko(ve,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
|
|
826
836
|
`)}o==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${a}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
827
837
|
`):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.
|
|
828
|
-
`)}async function
|
|
829
|
-
`)}}async function
|
|
830
|
-
`),n.ok?0:1}async function
|
|
838
|
+
`)}async function Jj(e){await oc(e)&&await sc(LS)}async function oc(e){try{let t=await Z();if(on(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(jS(t,r),await lt(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
839
|
+
`),!1}}async function sc(e=LS){try{let t=await Z(),n=on(t);return n===null?null:await KS(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function Yj(){let e=await Z(),t=on(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 KS(t,Mj);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
840
|
+
`),n.ok?0:1}async function KS(e,t){let n=await Z();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=vS(e.endpoint,e.api_key,r),o=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,o]);if(a.ok){let c=await Z();return c.pending_metrics=c.pending_metrics.slice(r.length),await lt(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function Xj(){let e=await Z(),t=on(e),n=Zj(),r=Qd(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:Iu(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...qs(n.findings)?{remedy:OS}:{}}},null,2)+`
|
|
831
841
|
`),r){process.stderr.write(`
|
|
832
842
|
[maind] Claude Code hook wiring is incomplete:
|
|
833
843
|
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
834
|
-
`);
|
|
835
|
-
`)}return 0}function
|
|
844
|
+
`);qs(n.findings)&&process.stderr.write(` ${OS}
|
|
845
|
+
`)}return 0}function Zj(){let e=ko(MS(),".claude","settings.json"),t=null;try{ic(e)&&(t=PS(e,"utf8"))}catch{}return{settingsPath:e,findings:Re(t)}}async function Qj(){let e=await Z(),t=on(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??Pj,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)}
|
|
836
846
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
837
847
|
`);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
|
|
838
848
|
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
839
849
|
`),1}let o=i;return typeof o.warn_at_pct!="number"||typeof o.handoff_at_pct!="number"||typeof o.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
840
|
-
`),1):(e.thresholds={warn_at_pct:o.warn_at_pct,handoff_at_pct:o.handoff_at_pct,model_token_limit:o.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await
|
|
841
|
-
`),0)}function
|
|
842
|
-
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([o,a])}function Ax(e,t=process.env){let n=Gr(e);return n&&!en(Xi(e,t))?n:""}async function pj(){try{for(let i of ut())Cw(qr(),i)}catch{}let e=J();if(!e)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=Ax(t);if(r)try{let i=oe(),o=oj(no(r,n)),a=Y();await Ex({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:o,repoRoot:sj(),resolveRoot:aj,projectKeyOf:cj,knownCheckouts:s(()=>so(yo),"knownCheckouts"),isDir:lj,rememberCheckouts:s(c=>ao(yo,c),"rememberCheckouts"),fetchContext:s((c,l)=>dj(e,i,c,l),"fetchContext"),post:s((c,l)=>uj(e,i,c,1500,l),"post"),connection:ij})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
843
|
-
`)}
|
|
844
|
-
`),0;let o=
|
|
845
|
-
`),await
|
|
846
|
-
`)}catch{}return 0}}async function
|
|
847
|
-
`,{mode:384}),(await
|
|
848
|
-
`).filter(r=>r.trim().length>0);await
|
|
850
|
+
`),1):(e.thresholds={warn_at_pct:o.warn_at_pct,handoff_at_pct:o.handoff_at_pct,model_token_limit:o.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await lt(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
851
|
+
`),0)}function GS(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var Pj,LS,Mj,nc,Uj,Kj,OS,ac=w(()=>{"use strict";Kn();ri();Bt();vt();Et();ie();ct();Wa();pi();he();$p();wp();za();ye();Ne();tc();Ie();Cr();Ya();bp();Fp();NS();Pj=process.env.MAIND_THRESHOLDS_ENDPOINT??Ar("get-context-thresholds"),LS=1500,Mj=1e4,nc=7*24*60*60*1e3;s(FS,"recordGuardSignals");s(jp,"isCaptureTool");s(jS,"closeTrackedSession");s($j,"gcState");s(on,"effectiveConfig");s(HS,"getOrCreateSession");s(Lj,"sessionStartOut");s(Fj,"runOnSessionStart");s(jj,"sessionStartBody");s(Hj,"readSettingsRaw");s(Hp,"writeIdentitySideChannel");Uj=6e4;s(US,"grandparentPid");s(rn,"agentHostPidCandidates");s(Bj,"runOnToolUse");Kj=5*6e4;s(BS,"assignedFrom");s(Gj,"denyReason");s(Wj,"runOnFileWrite");s(Vj,"runOnFileEdit");s(zj,"currentGitBranch");s(qj,"maybeEmitAdvisory");s(Jj,"runSessionEndMetrics");s(oc,"closeSessionMetrics");s(sc,"flushSessionMetrics");s(Yj,"runFlush");s(KS,"flushPending");s(Xj,"runHookStatus");OS="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(Zj,"readHookWiring");s(Qj,"runSyncConfig");s(GS,"sessionIdOf")});function zS(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!VS.test(n))return null;let r=n.toLowerCase();return t!==null&&VS.test(t)&&r!==t.toLowerCase()?null:r}var VS,qS=w(()=>{"use strict";VS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(zS,"snapshotSessionId")});import{appendFileSync as e1,existsSync as cc,mkdirSync as JS,readFileSync as t1,readdirSync as n1,renameSync as Up,rmdirSync as YS,statSync as Bp,unlinkSync as XS,writeFileSync as r1}from"node:fs";import{join as ii}from"node:path";function Kp(e){return e&&QS.test(e)?e:"no-session"}function So(e,t){return ii(e,`${t}.job.json`)}function Gp(e,t){return ii(e,`${t}.running.json`)}function ex(e,t){return ii(e,`${t}.lock`)}function Wp(e){cc(e)||JS(e,{recursive:!0,mode:448})}function tx(e,t){Wp(e);let n=Kp(t.session_id),r=`${So(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;r1(r,JSON.stringify(t),{mode:384}),Up(r,So(e,n))}function a1(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 nx(e,t){return cc(So(e,t))}function rx(e,t){let n=So(e,t),r=Gp(e,t);try{if(cc(n)&&Up(n,r),!cc(r))return null;let i=a1(t1(r,"utf8"));return i===null?(XS(r),null):i}catch{return null}}function ix(e,t){try{XS(Gp(e,t))}catch{}}function Vp(e,t,n=Date.now()){Wp(e);let r=ex(e,t);try{if(n-Bp(r).mtimeMs<i1)return!1;YS(r)}catch{}try{return JS(r,{recursive:!1}),!0}catch{return!1}}function zp(e,t){try{YS(ex(e,t))}catch{}}function ox(e){try{let t=new Set;for(let n of n1(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&QS.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function sx(e,t){for(let n of[So(e,t),Gp(e,t)])try{return Bp(n).mtimeMs}catch{}return null}function oi(e,t,n=o1){try{Wp(e);let r=ii(e,s1);try{Bp(r).size>n&&Up(r,ii(e,"runs.1.jsonl"))}catch{}e1(r,JSON.stringify(t)+`
|
|
852
|
+
`,{mode:384})}catch{}}var At,i1,ZS,o1,s1,QS,qp=w(()=>{"use strict";Ie();At=ii(ve,"session-end"),i1=10*6e4,ZS=7*24*60*6e4,o1=256*1024,s1="runs.jsonl",QS=/^[A-Za-z0-9_-]{1,80}$/;s(Kp,"jobKey");s(So,"jobPath");s(Gp,"runningPath");s(ex,"lockPath");s(Wp,"ensureDir");s(tx,"writeJob");s(a1,"parseJob");s(nx,"hasJob");s(rx,"takeJob");s(ix,"finishJob");s(Vp,"acquireLock");s(zp,"releaseLock");s(ox,"pendingKeys");s(sx,"pendingSince");s(oi,"appendRunLog")});function ax(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var cx=w(()=>{"use strict";s(ax,"resolveConnection")});function lx(e,t,n,r=Date.now()){let i=t===null?null:Xi(t),o=typeof n=="object"&&n!==null?n:{repoRoot:n},a=bu(e,i,{repoRoot:o.repoRoot,...o.relativize?{relativize:o.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:i!==null}}var dx=w(()=>{"use strict";Kn();s(lx,"buildCostPayload")});function l1(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();c1.test(r)&&!t.includes(r)&&t.push(r)}return t}async function ux(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:i}=await Yi(e.transcriptPath),o=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?ku({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:d1(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,c=a?Su(r,a):null,l=c??e.projectKey,d=l1([e.coordSessionId,e.sessionId,...i]),u=performance.now(),[p,f,m]=await Promise.all([uu(e.transcriptPath,{turns:r}),Tu(e.transcriptPath),e.fetchContext(l,d)]),g={collect_ms:o,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?xu(c,a):null,_=lx(r,m,{repoRoot:e.repoRoot,relativize:y},t()),b=m===null?null:Xi(m)?.canonical_session_id??null,v=e.coordSessionId??b,x=mu(p,f,{client_session_id:v,client:"claude-code",coordination_session_ids:d},"live_bridge",_);return await e.post(x,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:g}}function d1(e,t){try{return e()}catch{return t}}var c1,px=w(()=>{"use strict";Kn();dx();c1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(l1,"sessionIdsFor");s(ux,"ingestSessionEnd");s(d1,"safe")});var kx={};X(kx,{FLUSH_LOCK_KEY:()=>Zp,INLINE_BUDGET:()=>ef,SESSION_END_WORKER:()=>Qp,SWEEP_MAX_KEYS:()=>gx,SWEEP_MIN_AGE_MS:()=>hx,WORKER_BUDGET:()=>mx,WORKER_DEADLINE_MS:()=>Yp,drainSession:()=>tf,fetchCostContext:()=>yx,flushUnderLock:()=>vx,gitResolvers:()=>bx,liveJobDeps:()=>dc,postIngest:()=>_x,postIngestOnce:()=>Xp,processJob:()=>lc,runSessionEndWorker:()=>f1,sweepPending:()=>wx});import{execFileSync as u1}from"node:child_process";import{existsSync as fx,statSync as p1}from"node:fs";async function yx(e,t,n,r,i){if(n===null)return null;let[o,...a]=r;try{return await kt("get_session_cost_context",{project_key:n,...o?{session_id:o}:{},...a.length>0?{also_session_ids:a}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:U,timeoutMs:i})}catch{return null}}async function Xp(e,t,n,r,i,o=fetch){let a=new AbortController,c=setTimeout(()=>a.abort(),r);try{let l=await o(ec,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":U},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=fu(pu(d),i);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 _x(e,t,n,r,i,o={}){let a=o.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=await Xp(e,t,n,i.postMs,r,o.fetchImpl),l=1;return(c.outcome==="post_timeout"||c.outcome==="post_error"||c.outcome==="post_failed"&&(c.status??0)>=500)&&i.postRetryDelayMs>0&&(await a(i.postRetryDelayMs),c=await Xp(e,t,n,i.postMs,r,o.fetchImpl),l=2),{...c,attempts:l}}function Jp(e,t){try{let n=u1("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function bx(){let e=new Map,t=new Map;return{repoRootOf:s(n=>fx(n)?Jp(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let i=Jp(["-C",n,"rev-parse","--show-toplevel"]);return e.set(n,i),i},"gitRootOf"),projectKeyOfRoot:s(n=>{let r=t.get(n);if(r!==void 0)return r;let i=Jp(["-C",n,"config","--get","remote.origin.url"]),o=i?Nr(i):null;return t.set(n,o),o},"projectKeyOfRoot"),isDir:s(n=>{try{return p1(n).isDirectory()}catch{return!1}},"isDir")}}async function lc(e,t){let n=t.now??Date.now,r=n(),i=Date.parse(e.queued_at),o={queued:Number.isFinite(i)?Math.max(0,r-i):0},a={ts:new Date(r).toISOString(),bridge:U,session_id:e.session_id,outcome:"no_transcript",ms:o};try{if(e.transcript_path)if(!fx(e.transcript_path))a.outcome="transcript_gone";else{let l=bx(),d=t.memoryPath??jr,u=null,p=await ux({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(()=>Zi(d),"knownCheckouts"),rememberCheckouts:s(m=>Qi(d,m),"rememberCheckouts")}:{},fetchContext:s(async(m,g)=>{let y=n();try{return await t.fetchContext(m,g)}finally{o.context=n()-y}},"fetchContext"),post:s(async(m,g)=>{let y=n();u=await t.post(m,g),o.post=n()-y},"post"),connection:s(m=>ax({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&&(o.collect=p.timings.collect_ms,o.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 o.flush=n()-c,o.total=n()-r,a}async function tf(e,t,n,r={}){let i=r.now??Date.now,o=r.maxRounds??20,a=0;for(;a<o&&Vp(e,t,i());){try{let c=rx(e,t);if(c===null)break;let l=Date.parse(c.queued_at),d=Number.isFinite(l)&&i()-l>ZS?{ts:new Date(i()).toISOString(),bridge:U,session_id:c.session_id,outcome:"expired",ms:{queued:i()-l}}:await n(c);oi(e,d),ix(e,t),a++}finally{zp(e,t)}if(!nx(e,t))break}return a}async function wx(e,t,n,r={}){let i=r.now??Date.now,o=0;for(let a of ox(e)){if(o>=gx)break;if(a===t)continue;let c=sx(e,a);c===null||i()-c<hx||await tf(e,a,n,{...r,maxRounds:1})>0&&o++}return o}async function vx(e,t,n=Date.now){if(!Vp(e,Zp,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{zp(e,Zp)}}function dc(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,i)=>yx(e,t,r,i,n.contextMs),"fetchContext"),post:s((r,i)=>_x(e,t,r,i,n),"post"),flush:s(()=>vx(At,()=>sc(n.flushMs)),"flush"),memoryAllowed:aa()}}async function f1(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{oi(At,{ts:new Date().toISOString(),bridge:U,session_id:t,outcome:"deadline",ms:{total:Yp}}),process.exit(0)},Yp);n.unref();try{let r=z();if(!r)return 0;let i=ne(),o=s(a=>lc(a,dc(r,i,mx)),"run");await tf(At,t,o),await wx(At,t,o)}catch(r){oi(At,{ts:new Date().toISOString(),bridge:U,session_id:t,outcome:"error",ms:{},error:(r instanceof Error?r.message:String(r)).slice(0,200)})}finally{clearTimeout(n)}return 0}var Qp,mx,ef,Yp,hx,gx,Zp,nf=w(()=>{"use strict";Kn();ie();en();$p();ac();he();ze();ca();cx();px();qp();Qp="session-end-run",mx={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},ef={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},Yp=3*6e4,hx=2*6e4,gx=3;s(yx,"fetchCostContext");s(Xp,"postIngestOnce");s(_x,"postIngest");s(Jp,"git");s(bx,"gitResolvers");s(lc,"processJob");s(tf,"drainSession");s(wx,"sweepPending");Zp="metrics-flush";s(vx,"flushUnderLock");s(dc,"liveJobDeps");s(f1,"runSessionEndWorker")});var Rx={};X(Rx,{buildJob:()=>Ex,enqueueAndSpawn:()=>Tx,presenceLookup:()=>Sx,runOnSessionEnd:()=>w1,transcriptToIngest:()=>xx});import{spawn as m1}from"node:child_process";import{existsSync as h1,unlinkSync as g1}from"node:fs";import{join as y1}from"node:path";function Sx(e,t,n,r){let i=null,o={own_snapshot_age_ms:null,presence_usable:!1};try{if(o.presence_usable=e!==null&&!sp(process.env,ee()),e!==null){let a=ei(Xr(e),{hostPids:r,cwd:process.cwd()});if(a){let c=Date.parse(a.snap.written_at);o={...o,own_snapshot_age_ms:Number.isFinite(c)?Math.max(0,n-c):null}}i=zS(a?.snap,t)}}catch{o={own_snapshot_age_ms:null,presence_usable:!1},i=null}if(i===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)&&(i=a)}return{coordSessionId:i,evidence:o}}function xx(e,t=process.env){let n=Vr(e);return n&&!tn(ao(e,t))?n:""}function Ex(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 i=t.projectKey(),o=t.presence(i,fo(t.transcriptPath,n),t.nowMs);return{...r,project_key:i,coord_session_id:o.coordSessionId,presence:o.evidence}}function Tx(e,t={}){let n=t.dir??At,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let i=Kp(e.session_id);try{tx(n,e)}catch{return!1}try{return(t.spawnWorker??_1)(r,i,e.cwd),!0}catch{try{g1(y1(n,`${i}.job.json`))}catch{}return!1}}function _1(e,t,n){m1(process.execPath,[e,Qp,t],{detached:!0,stdio:"ignore",cwd:h1(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function b1(e,t){try{let n=await lc(e,dc(t,ne(),ef));oi(At,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
|
|
853
|
+
`)}}async function w1(){let e=[];try{e=rn()}catch{e=[]}try{for(let o of e)$k(Zr(),o)}catch{}let t=z();if(!t)return 0;let n=await G(),r=typeof n.session_id=="string"&&n.session_id?n.session_id:null;await oc(r);let i;try{i=Ex(n,{transcriptPath:xx(n),cwd:process.cwd(),nowMs:Date.now(),projectKey:te,presence:s((o,a,c)=>Sx(o,a,c,e),"presence")})}catch{return 0}return Tx(i)||await b1(i,t),0}var Ax=w(()=>{"use strict";Ce();ie();wp();ye();Ne();ac();ap();Wa();he();za();qS();qp();nf();s(Sx,"presenceLookup");s(xx,"transcriptToIngest");s(Ex,"buildJob");s(Tx,"enqueueAndSpawn");s(_1,"spawnDetachedWorker");s(b1,"runInline");s(w1,"runOnSessionEnd")});var Cx={};X(Cx,{runOnSessionBriefing:()=>v1});async function v1(){try{return await Ma("core",await G())}catch{return 0}}var Ix=w(()=>{"use strict";Xn();ye();s(v1,"runOnSessionBriefing")});var Ox={};X(Ox,{deliverSessionReminder:()=>Nx,runOnSessionReminder:()=>E1});import{readFile as k1}from"node:fs/promises";import{homedir as S1}from"node:os";import{join as x1}from"node:path";async function Nx(e,t={}){let n=t.target??oe(e);if(!_e(n,{kind:"text",event:"SessionStart"}))return 0;let r;try{r=await k1(x1(t.homeDir??S1(),Zd),"utf8")}catch{return 0}if(r.length===0)return 0;let i=ce(n,{kind:"text",event:"SessionStart",text:r});return i!==null&&await(t.write??Ra)(i),0}async function E1(){try{return await Nx(await G())}catch{return 0}}var Dx=w(()=>{"use strict";ct();ye();Ne();s(Nx,"deliverSessionReminder");s(E1,"runOnSessionReminder")});var Ux={};X(Ux,{CURSOR_BRIEFING_MARKER:()=>rf,CURSOR_DELIVERY_LOG:()=>Px,CURSOR_UNAVAILABLE_TEXT:()=>$x,appendDelivery:()=>jx,cursorProjectDir:()=>Mx,deliverCursorSessionStart:()=>Fx,formatCursorBriefing:()=>Lx,runOnCursorSessionStart:()=>M1});import{appendFile as T1,mkdir as R1,readFile as A1,stat as C1,writeFile as I1}from"node:fs/promises";import{dirname as N1,join as O1}from"node:path";function Mx(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let i=r.find(o=>typeof o=="string"&&o.length>0);if(i)return i}return null}function Lx(e,t,n){let i=`${rf}${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 Da(i,n,e)}async function Fx(e,t={}){let n=t.write??Hx,r=t.env??process.env,i=(t.apiKey??z)();if(i===null)return await n(`{}
|
|
854
|
+
`),0;let o=Mx(e,r),a=o===null?null:(t.projectKeyFor??Le)(o),c=await qr(a,i,{fetcher:s(p=>Wr({...p,clientFamily:"cursor"}),"fetcher"),...t.inject}),l,d,u=!0;if(c.text===null)l=$x,d="none";else{let p=Lx(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})+`
|
|
855
|
+
`),await jx(t.logFile??Px,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:si(e.conversation_id)??si(e.session_id),transcript_path:si(e.transcript_path)??si(r.CURSOR_TRANSCRIPT_PATH),cursor_version:si(e.cursor_version)??si(r.CURSOR_VERSION),chars:c.text===null?0:l.length,via:d,complete:u}),0}async function M1(){try{return await Fx(await G())}catch{try{await Hx(`{}
|
|
856
|
+
`)}catch{}return 0}}async function jx(e,t){try{if(await R1(N1(e),{recursive:!0,mode:448}),await T1(e,JSON.stringify(t)+`
|
|
857
|
+
`,{mode:384}),(await C1(e)).size>D1){let n=(await A1(e,"utf8")).split(`
|
|
858
|
+
`).filter(r=>r.trim().length>0);await I1(e,n.slice(-P1).join(`
|
|
849
859
|
`)+`
|
|
850
|
-
`,{mode:384})}}catch{}}function
|
|
851
|
-
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of $r)o.push(await
|
|
860
|
+
`,{mode:384})}}catch{}}function Hx(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var rf,Px,D1,P1,si,$x,Bx=w(()=>{"use strict";ie();Xn();en();Pa();he();ye();Ie();rf="[maind] Cursor session briefing",Px=O1(ve,"cursor","deliveries.jsonl"),D1=512*1024,P1=2e3,si=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Mx,"cursorProjectDir");$x=`${rf} 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(Lx,"formatCursorBriefing");s(Fx,"deliverCursorSessionStart");s(M1,"runOnCursorSessionStart");s(jx,"appendDelivery");s(Hx,"writeStdout")});function $1(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function Kx(e,t,n=process.stdout){let r=$1(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
861
|
+
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of $r)o.push(await iu(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
852
862
|
`);let a=o.some(l=>l.detail==="user declined"),c=o.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
853
863
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
854
|
-
`),0):(await
|
|
864
|
+
`),0):(await Jn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
855
865
|
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
856
866
|
flip: maind-mcp-bridge guard mode <warn|block>
|
|
857
867
|
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
858
868
|
check: maind-mcp-bridge guard status
|
|
859
869
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
860
870
|
`),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
861
|
-
`),c?1:0)}var
|
|
862
|
-
`,{mode:384})}catch{}}async function nr(e,t=
|
|
863
|
-
`))if(i.trim())try{let o=JSON.parse(i),a=o.t,c=o.k,l=o.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!
|
|
864
|
-
`),1):(await
|
|
865
|
-
`),0)}case"off":return await
|
|
871
|
+
`),c?1:0)}var Gx=w(()=>{"use strict";ct();su();dt();s($1,"parseGuardInstallFlags");s(Kx,"runGuardInstall")});import{existsSync as Wx}from"node:fs";import{appendFile as L1,mkdir as F1,readFile as j1}from"node:fs/promises";import{join as H1}from"node:path";function of(e,t=uc){return H1(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function ai(e,t=uc){return Wx(of(e,t))}async function sn(e,t,n=uc){try{await F1(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await L1(of(e,n),r+`
|
|
872
|
+
`,{mode:384})}catch{}}async function nr(e,t=uc){try{let n=of(e,t);if(!Wx(n))return[];let r=[];for(let i of(await j1(n,"utf8")).split(`
|
|
873
|
+
`))if(i.trim())try{let o=JSON.parse(i),a=o.t,c=o.k,l=o.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!U1.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var uc,U1,xo=w(()=>{"use strict";xt();uc=Yu,U1=new Set(["fail","ok","nudge","skip","prompt"]);s(of,"triggerLogPath");s(ai,"hasTriggerLog");s(sn,"appendTriggerEvent");s(nr,"loadTriggerEvents")});import{existsSync as B1}from"node:fs";import{mkdir as K1,readFile as G1,rename as W1,writeFile as V1}from"node:fs/promises";import{dirname as z1,join as q1}from"node:path";function Eo(e=process.env){let t=z();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??io,keyFp:Tr(t)}}async function sf(e,t=Date.now(),n=pc){try{if(!B1(n))return null;let r=JSON.parse(await G1(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let i=Date.parse(r.fetched_at);if(Number.isNaN(i))return null;let o=r.policy;return{policy:Qa([o?.difficulty,o?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<J1}}catch{return null}}async function X1(e,t,n,r){try{await K1(z1(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},o=`${r}.tmp`;await V1(o,JSON.stringify(i,null,2),{mode:384}),await W1(o,r)}catch{}}async function Z1(){let e=z();if(e===null)return null;let t=null;try{t=te()}catch{t=null}let n=await kt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:Q1(),projectKey:t,bridgeVersion:U,timeoutMs:Y1});if(n===null)return null;try{return Qa(JSON.parse(n))}catch{return null}}async function ci(e,t={}){let n=t.nowMs??Date.now(),r=t.file??pc,i=t.identity===void 0?Eo():t.identity;if(i===null)return wo;let o=await sf(i,n,r);if(o?.fresh)return o.policy;if(e){let a=await(t.fetcher??Z1)();if(a!==null)return await X1(i,a,n,r),a}return o?.policy??wo}function Q1(){try{return ne()}catch{return null}}var pc,J1,Y1,li=w(()=>{"use strict";ri();vt();ie();he();ze();en();xt();pc=q1(Je,"trigger-policy.json"),J1=12*60*60*1e3,Y1=3e3;s(Eo,"currentIdentity");s(sf,"readCachedPolicy");s(X1,"writeCachedPolicy");s(Z1,"fetchTriggerPolicy");s(ci,"resolveTriggerPolicy");s(Q1,"safeDeviceId")});var zx={};X(zx,{runGuard:()=>iH});import{existsSync as eH,readFileSync as tH}from"node:fs";import{homedir as Vx}from"node:os";import{join as nH}from"node:path";async function iH(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Kx(n,Vx());case"status":return sH();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
874
|
+
`),1):(await Jn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
875
|
+
`),0)}case"off":return await Jn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
866
876
|
`),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>
|
|
867
|
-
`),1):(await
|
|
877
|
+
`),1):(await Jn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
868
878
|
`),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>
|
|
869
|
-
`),1):(await
|
|
879
|
+
`),1):(await Jn(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.
|
|
870
880
|
`:`${t} trigger disabled on this machine (your convention prefs are unchanged).
|
|
871
|
-
`),0)}case"skip":return
|
|
872
|
-
`),1;let i=n.trim().slice(0,500);if(r!=="consult")return await
|
|
873
|
-
logged (auditable) in ${
|
|
874
|
-
`),0;let o=await St(t);return await
|
|
875
|
-
logged (auditable) in ${
|
|
876
|
-
`),0}async function
|
|
881
|
+
`),0)}case"skip":return oH(n);default:return process.stdout.write(rH),t===void 0||t==="--help"||t==="-h"?0:1}}async function oH(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]
|
|
882
|
+
`),1;let i=n.trim().slice(0,500);if(r!=="consult")return await sn(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await Q({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
|
|
883
|
+
logged (auditable) in ${Yn}
|
|
884
|
+
`),0;let o=await St(t);return await Te(t,{...o,override_reason:i}),await Q({event:"override",session_id:t,reason:i,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
|
|
885
|
+
logged (auditable) in ${Yn}
|
|
886
|
+
`),0}async function sH(){let e=le(),t=nH(Vx(),".claude","settings.json"),n=null;try{eH(t)&&(n=tH(t,"utf8"))}catch{}let r=Re(n,{},$r),i=await Nv(),o=Eo(),a=o?await sf(o):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",briefing_channel:Ca(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:pc},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:Yn},null,2)+`
|
|
877
887
|
`);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(`
|
|
878
888
|
[maind] guard hook wiring is incomplete:
|
|
879
889
|
`);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
|
|
880
|
-
`);c.some(l=>l.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var
|
|
881
|
-
`);s(
|
|
882
|
-
`):null,interrupted:t.interrupted===!0}}function
|
|
890
|
+
`);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 rH,qx=w(()=>{"use strict";Ia();ct();dt();Gx();Et();xt();xo();li();rH=["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(`
|
|
891
|
+
`);s(iH,"runGuard");s(oH,"runGuardSkip");s(sH,"runGuardStatus")});var Xx={};X(Xx,{bashOutputOf:()=>Jx,consultedAtOf:()=>fc,outcomeFromHook:()=>Yx,runGuardDifficulty:()=>cH});function Jx(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(`
|
|
892
|
+
`):null,interrupted:t.interrupted===!0}}function Yx(e){let t=e.hook_event_name;if(t!=="PostToolUse"&&t!=="PostToolUseFailure")return null;let n=typeof e.tool_name=="string"?e.tool_name:"",r=t==="PostToolUseFailure",i=!r&&n==="Bash"?Jx(e.tool_response):{output:null,interrupted:!1},o=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:i.output,isInterrupt:e.is_interrupt===!0||i.interrupted,isSubagent:typeof o=="string"&&o.length>0}}}function fc(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 aH(e,t,n){if(!ai(e))return;let r=await nr(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let i=ti(r,null,n);await sn(e,{t:n,k:"ok",v:t});let o=i.chain;o!==null&&o.failures.length>=4&&!i.resolved&&o.lastVerb===t&&await Q({event:"difficulty_resolved",session_id:e,detail:String(o.failures.length)})}async function cH(){try{let e=le();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await G();if(qe(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=Yx(t);if(r===null)return 0;let i=Tp(r.outcome);if(i===null)return 0;let o=Date.now();if(i.kind==="ok")return await aH(n,i.verb,o),0;await sn(n,{t:o,k:"fail",v:i.verb});let a=await nr(n),c=ti(a,fc(await Z(),n),o);if(!Cp(c)||c.chain===null)return 0;let l=await ci(!0);if(!e.difficulty||!ni(l.difficulty))return 0;await sn(n,{t:o,k:"nudge"});let d=vo(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?Ta(d):oo(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await Q({event:"difficulty_nudge",session_id:n,cwd:u,project_key:te()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var af=w(()=>{"use strict";ri();ye();Ne();so();Ie();he();dt();Et();xo();li();s(Jx,"bashOutputOf");s(Yx,"outcomeFromHook");s(fc,"consultedAtOf");s(aH,"recordSuccess");s(cH,"runGuardDifficulty")});var tE={};X(tE,{decideDifficultyGate:()=>eE,decideGate:()=>Qx,runGuardGate:()=>uH});function Qx(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:Zx(n)}:(n.deny_count??0)>=mc?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. "+Zx(n)}:{kind:"deny",reason:lH(e.sessionId,n)}}function Zx(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 lH(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:
|
|
883
893
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
884
894
|
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
885
|
-
After ${
|
|
895
|
+
After ${mc} denies this gate downgrades itself to warn.`}function eE(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)>=mc?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. "+vo(n.chain)}:{kind:"deny",reason:dH(n,e.sessionId)}}function dH(e,t){return`[maind guard | block] Edit denied \u2014 ${Pp(e.chain)}. Two exits:
|
|
886
896
|
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.
|
|
887
897
|
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
|
|
888
|
-
After ${
|
|
889
|
-
`,{mode:384}),await
|
|
890
|
-
`).filter(r=>r.trim());if(t.length<=
|
|
898
|
+
After ${mc} denies this gate downgrades itself to warn.`}async function uH(){try{let e=le();if(e.mode==="off")return 0;let t=await G();if(qe(t))return 0;let n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await St(r),o=fc(await Z(),r),a=o!==null,c=Qx({mode:e.mode,session:i,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=te()??void 0;if(c.kind==="deny")return process.stdout.write(Vn(c.reason)),await Te(r,{...i,deny_count:(i.deny_count??0)+1}),await Q({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(zn(c.context)),await Te(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await Q({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&ai(r)){let u=ti(await nr(r),o,Date.now()),p=u.open?eE({mode:e.mode,enabled:e.difficulty,denyCapable:Op((await ci(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(Vn(p.reason)),await Te(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await Q({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(zn(p.context)),await Te(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await Te(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var mc,nE=w(()=>{"use strict";ri();ye();Ne();so();Ie();he();dt();af();Et();xt();xo();li();mc=3;s(Qx,"decideGate");s(Zx,"warnText");s(lH,"denyText");s(eE,"decideDifficultyGate");s(dH,"difficultyDenyText");s(uH,"runGuardGate")});var iE={};X(iE,{decideStopGate:()=>rE,runGuardStop:()=>fH});function rE(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function fH(){try{let e=le();if(e.mode==="off"||!e.stopGate)return 0;let t=await G();if(qe(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 St(n),i=(await Z()).guard_signals?.[n]?.reviewed_at!==void 0;return rE({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:pH})),await Te(n,{...r,stop_blocked:!0}),await Q({event:"stop_block",session_id:n})),0}catch{return 0}}var pH,oE=w(()=>{"use strict";ye();Ne();Ie();dt();Et();xt();s(rE,"decideStopGate");pH="[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(fH,"runGuardStop")});var cE={};X(cE,{capturedAtOf:()=>sE,decideCapture:()=>aE,runGuardCapture:()=>mH});function sE(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 aE(e){if(e.stopHookActive||!ni(e.policy.capture))return null;let t=Ip(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Mp(t)}}async function mH(){try{let e=le();if(e.mode==="off"||!e.capture)return 0;let t=await G();if(qe(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!ai(n))return 0;let r=aE({events:await nr(n),capturedAtMs:sE(await Z(),n),policy:await ci(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await sn(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await Q({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var lE=w(()=>{"use strict";ri();ye();Ne();Ie();dt();Et();xo();li();s(sE,"capturedAtOf");s(aE,"decideCapture");s(mH,"runGuardCapture")});import{appendFile as hH,mkdir as gH,readFile as uE,rename as pE,writeFile as fE}from"node:fs/promises";import{homedir as mE}from"node:os";import{join as hE}from"node:path";function gE(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=new Map,a=1/0,c=-1/0;for(let d of e){d.at<a&&(a=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=o.get(d.convention_id);(p===void 0||d.convention_version>p)&&o.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function rr(){return hE(mE(),".maind","gateway","attest-spool.jsonl")}async function cf(e){let t=z();if(t===null)return!1;let n=await kt("gateway_attest",{...e},{apiKey:t,deviceId:ne(),projectKey:e.project_key??null,bridgeVersion:U,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function yE(e){try{await gH(hE(mE(),".maind","gateway"),{recursive:!0}),await hH(rr(),JSON.stringify(e)+`
|
|
899
|
+
`,{mode:384}),await yH()}catch{}}async function yH(){try{let t=(await uE(rr(),"utf8")).split(`
|
|
900
|
+
`).filter(r=>r.trim());if(t.length<=dE)return;let n=`${rr()}.${process.pid}.tmp`;await fE(n,t.slice(-dE).join(`
|
|
891
901
|
`)+`
|
|
892
|
-
`,{mode:384}),await
|
|
893
|
-
`).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await
|
|
902
|
+
`,{mode:384}),await pE(n,rr())}catch{}}async function _E(){let e;try{e=(await uE(rr(),"utf8")).split(`
|
|
903
|
+
`).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await cf(i)||(n=!0,t.push(r))}try{let r=`${rr()}.${process.pid}.tmp`;await fE(r,t.length>0?t.join(`
|
|
894
904
|
`)+`
|
|
895
|
-
`:"",{mode:384}),await
|
|
896
|
-
`,384)}async function
|
|
897
|
-
`),2;let n=
|
|
898
|
-
`);continue}let a=
|
|
899
|
-
`);continue}if(!(t.yes||await
|
|
905
|
+
`:"",{mode:384}),await pE(r,rr())}catch{}}var dE,bE=w(()=>{"use strict";ie();en();ze();dE=256;s(gE,"aggregateWindow");s(rr,"attestSpoolPath");s(cf,"postAttestation");s(yE,"spoolAttestation");s(yH,"capSpool");s(_E,"flushAttestSpool")});function To(e=process.env,t=ee()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function hc(e=process.env,t=ee()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function wE(e,t=Ae()){let n={};try{let i=await Y(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await V(t,JSON.stringify(r,null,2)+`
|
|
906
|
+
`,384)}async function vE(e,t=Ae()){await wE({gateway_mode:e},t)}async function kE(e,t=Ae()){await wE({gateway_attest:e},t)}function SE(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 lf=w(()=>{"use strict";Ce();we();s(To,"resolveGatewayMode");s(hc,"resolveGatewayAttest");s(wE,"writeGatewayConfigPatch");s(vE,"writeGatewayMode");s(kE,"writeGatewayAttest");s(SE,"resolveShaProofMode")});function EE(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,o=i.gateway_gate;if(typeof o!="object"||o===null)continue;let a=o;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let d=typeof i.severity=="string"&&_H.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function bH(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function TE(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)bH(o,e,t)&&(i===null||xE[o.severity]>xE[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function RE(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 _H,xE,df=w(()=>{"use strict";_H=new Set(["required","recommended","info"]);s(EE,"extractGatewayRules");xE={required:2,recommended:1,info:0};s(bH,"ruleMatches");s(TE,"decideToolCall");s(RE,"policyDenyText")});import{mkdirSync as wH,readFileSync as vH,renameSync as kH,writeFileSync as SH}from"node:fs";import{homedir as xH}from"node:os";import{dirname as EH,join as TH}from"node:path";function AE(){return TH(xH(),".maind","gateway","policy-cache.json")}function gc(e,t,n=new Date().toISOString()){try{let r={version:uf,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=AE();wH(EH(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;SH(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),kH(o,i)}catch{}}function yc(e){try{let t=vH(AE(),"utf8"),n=JSON.parse(t);return n.version!==uf||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:uf,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var uf,pf=w(()=>{"use strict";uf=1;s(AE,"policyCachePath");s(gc,"writePolicyCache");s(yc,"readPolicyCache")});function Ro(e=process.env){let t=e.MAIND_MCP_URL??io,n=z();return{mcpUrl:t,keyFp:n?Tr(n):"anon"}}async function _c(e=6e3){let t=z();if(t===null)return null;let n=null;try{n=te()}catch{n=null}let r=await kt("get_conventions",{},{apiKey:t,deviceId:ne(),projectKey:n,bridgeVersion:U,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return EE(i)}var ff=w(()=>{"use strict";vt();ie();en();he();ze();df();s(Ro,"policyIdentity");s(_c,"fetchGatewayRules")});function Ao(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 RH(e){if(Ao(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 AH(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Ao(e)?{action:"skip",reason:"already-wrapped"}:RH(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function CE(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],o=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=o||t.env?{...o??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function IE(e){if(!Ao(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 NE(e){return Object.entries(e).map(([t,n])=>{let r=AH(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var OE=w(()=>{"use strict";s(Ao,"isGatewayWrapped");s(RH,"isMaindProxyEntry");s(AH,"classifyServer");s(CE,"wrapServerEntry");s(IE,"unwrapServerEntry");s(NE,"planRewrites")});var FE={};X(FE,{runGatewayInstall:()=>PH,runGatewayUninstall:()=>MH});import{existsSync as CH,readFileSync as IH}from"node:fs";import{homedir as NH}from"node:os";import{join as DE}from"node:path";import{createInterface as OH}from"node:readline";function PE(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 ME(){return[{label:"Claude Code (project .mcp.json)",path:DE(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:DE(NH(),".claude.json")}]}async function $E(e){let t=OH({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 LE(e){let t=DH(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function DH(e){try{return CH(e)?IH(e,"utf8"):null}catch{return null}}async function PH(e){let t=PE(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
907
|
+
`),2;let n=xe({entryPath:ge(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of ME()){let o=LE(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
908
|
+
`);continue}let a=NE(o.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
909
|
+
`);continue}if(!(t.yes||await $E(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
900
910
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
901
911
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
902
|
-
`);continue}o.servers[c.key]=
|
|
903
|
-
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await
|
|
912
|
+
`);continue}o.servers[c.key]=CE(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
913
|
+
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await V(i.path,JSON.stringify(o.raw,null,2)+`
|
|
904
914
|
`,384)}return process.stderr.write(r>0?`
|
|
905
915
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
906
916
|
`:`
|
|
907
917
|
Nothing to wrap.
|
|
908
|
-
`),0}async function
|
|
909
|
-
`),2;let n=0;for(let r of
|
|
918
|
+
`),0}async function MH(e){let t=PE(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
919
|
+
`),2;let n=0;for(let r of ME()){let i=LE(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!Ao(c)||!(t.yes||await $E(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=IE(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
|
|
910
920
|
`);continue}i.servers[a]=d,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
|
|
911
|
-
`)}!t.dryRun&&o&&await
|
|
921
|
+
`)}!t.dryRun&&o&&await V(r.path,JSON.stringify(i.raw,null,2)+`
|
|
912
922
|
`,384)}return process.stderr.write(n>0?`
|
|
913
923
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
914
924
|
`:`
|
|
915
925
|
Nothing wrapped \u2014 nothing to restore.
|
|
916
|
-
`),0}var
|
|
926
|
+
`),0}var jE=w(()=>{"use strict";we();Kt();OE();s(PE,"parseFlags");s(ME,"targets");s($E,"confirm");s(LE,"loadConfig");s(DH,"readFileSafeSync");s(PH,"runGatewayInstall");s(MH,"runGatewayUninstall")});var HE={};X(HE,{runGatewayAttest:()=>LH,runGatewayMode:()=>$H,runGatewayPolicy:()=>HH});async function $H(e){let t=e[0];if(t===void 0){let n=To(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
917
927
|
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
918
|
-
`),2):(await
|
|
928
|
+
`),2):(await vE(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
919
929
|
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
920
930
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
921
|
-
`)),0)}async function
|
|
931
|
+
`)),0)}async function LH(e){let t=e[0];if(t===void 0){let n=hc(),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)":""}.
|
|
922
932
|
`+(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.
|
|
923
933
|
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
924
|
-
`),2):(await
|
|
934
|
+
`),2):(await kE(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.
|
|
925
935
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
926
|
-
`),0)}function
|
|
936
|
+
`),0)}function FH(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
927
937
|
`;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
|
|
928
|
-
`}return t}function
|
|
929
|
-
`):(
|
|
930
|
-
`))}let i=
|
|
938
|
+
`}return t}function jH(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function HH(e){let t=e.includes("--refresh"),n=To(),r=Ro();if(t){let o=await _c();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
939
|
+
`):(gc(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
|
|
940
|
+
`))}let i=yc(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
931
941
|
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
932
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
933
|
-
`),process.stdout.write(
|
|
934
|
-
`),0)}var
|
|
935
|
-
`,{mode:384})}catch{}}function
|
|
942
|
+
`),0):(process.stdout.write(`maind: policy from cache (${jH(i)}, ${r.mcpUrl}):
|
|
943
|
+
`),process.stdout.write(FH(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
|
|
944
|
+
`),0)}var UE=w(()=>{"use strict";lf();pf();ff();s($H,"runGatewayMode");s(LH,"runGatewayAttest");s(FH,"renderRules");s(jH,"cacheAge");s(HH,"runGatewayPolicy")});var VE={};X(VE,{gatewayEventsFile:()=>GE,parseGatewayArgs:()=>WE,runGateway:()=>qH});import{spawn as UH}from"node:child_process";import{appendFile as BH,mkdir as KH}from"node:fs/promises";import{homedir as BE}from"node:os";import{basename as GH,join as KE}from"node:path";import{createInterface as WH}from"node:readline";function GE(){return KE(BE(),".maind","gateway","events.jsonl")}async function zH(e){try{let t=GE();await KH(KE(BE(),".maind","gateway"),{recursive:!0}),await BH(t,JSON.stringify(e)+`
|
|
945
|
+
`,{mode:384})}catch{}}function WE(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let o=e[r+1];if(!o)return null;t.add(o),r+=2;continue}if(i==="--label"){let o=e[r+1];if(!o)return null;n=o,r+=2;continue}if(i==="--"){let o=e[r+1];return o?{denyTools:t,label:n,command:o,args:e.slice(r+2)}:null}return null}return null}async function qH(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:E}=await Promise.resolve().then(()=>(jE(),FE));return e[0]==="install"?k(e.slice(1)):E(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:k,runGatewayMode:E,runGatewayPolicy:P}=await Promise.resolve().then(()=>(UE(),HE));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?k(e.slice(1)):P(e.slice(1))}let t=WE(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
936
946
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
937
947
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
938
948
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -942,59 +952,59 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
942
952
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
943
953
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
944
954
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
945
|
-
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r
|
|
946
|
-
`),process.exitCode=1});let
|
|
947
|
-
`),y(
|
|
948
|
-
`),y(
|
|
949
|
-
`),y(
|
|
950
|
-
`),y(
|
|
951
|
-
`)}),
|
|
952
|
-
`),await
|
|
953
|
-
`),a.warned[o]=c.current,await
|
|
954
|
-
`)){let r=
|
|
955
|
-
(trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:o,symbolNames:a}}function
|
|
956
|
-
(trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var
|
|
957
|
-
`)}},uE=90;s(pE,"renderPromptContext");mH=2e3;s(hH,"isPartialRead");s(gH,"commonDir");s(yH,"callerLabel");s(fE,"renderReadContext")});import{createHash as _H}from"node:crypto";import{existsSync as hE,mkdirSync as bH,readdirSync as vH,rmSync as wH,statSync as kH,writeFileSync as xH}from"node:fs";import{join as lc}from"node:path";function ef(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function TH(e,t,n=null,r=EH){try{for(let i of vH(e)){let o=lc(e,i);if(o!==n)try{t-kH(o).mtimeMs>r&&wH(o,{recursive:!0,force:!0})}catch{}}}catch{}}var SH,EH,So,gE=v(()=>{"use strict";Le();SH=lc(Ce,"context"),EH=7*24*60*60*1e3;s(ef,"safe");So=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=SH){let i=n?`${ef(t)}__${ef(n)}`:ef(t);return new e(r,lc(r,i))}fileFor(t){return lc(this.dir,_H("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return hE(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{hE(this.dir)||(bH(this.dir,{recursive:!0,mode:448}),TH(this.root,n,this.dir));for(let r of t)try{xH(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(TH,"sweepStaleScopes")});var rf={};Q(rf,{INDEX_RELPATH:()=>zt,SOFT_BUDGET_MS:()=>bE,findRepoRoot:()=>qt,isMachinePrompt:()=>xE,loadCachedConventions:()=>wE,promptContextFor:()=>EE,promptTextOf:()=>kE,readContextFor:()=>TE,runOnPromptContext:()=>MH,runOnReadContext:()=>LH});import{existsSync as yE,readFileSync as RH,realpathSync as CH,statSync as AH}from"node:fs";import{dirname as IH,isAbsolute as _E,join as Eo,relative as NH,sep as OH}from"node:path";function DH(e,t){let n=NH(e,t);return!n||n.startsWith("..")||_E(n)?null:n.split(OH).join("/")}function nf(e){try{let t=AH(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function vE(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(ia(),au));return t(e)}function wE(e,t={}){try{let n=t.identity===void 0?vo():t.identity;if(e!==null&&n!==null){let r=Ss(e,n),i=fa(r?.result.instructions??null),o=Qp(i);if(o.length>0)return o}}catch{}try{let n=JSON.parse(RH(t.briefingCacheFile??Kr,"utf8"));if(typeof n.conventions=="string")return Qp(n.conventions)}catch{}return[]}function kE(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function xE(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 SE(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 PH(e,t,n,r){let i;try{i=await r(n)}catch{return[]}try{if(!i.meta().schemaCurrent)return[];let o=i.symbolsNamed(e.map(d=>d.name)),a=i.files([...o.values()].flat().map(d=>d.filePath).slice(0,tf)),c=new Set;for(let[d,u]of a){let p=nf(Eo(t,d));p!==null&&Mi(u,p)&&c.add(d)}let l=[];for(let d of e){let u=o.get(d.name)??[],p=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),f=p.length>0?p:u,m=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));m.length>0&&l.push({candidate:d,locations:m,total:f.length})}return l}catch{return[]}finally{try{i.close()}catch{}}}async function EE(e,t={}){let n=t.now??Date.now,r=n(),i=t.env??process.env,o=re(e,i,t.readConfig??te);if(!ye(o,{kind:"context",event:"UserPromptSubmit"}))return null;let a=kE(e);if(a.trim().length===0||xE(e,a))return null;let c=SE(e);if(c===null)return null;let l=So.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:la(o,i)??process.cwd(),u=qt(d),p=lE(a,(t.loadConventions??wE)(u),6,cE(u)).filter(b=>!l.has(`conv:${b.convention.id}@${b.convention.version}`)).slice(0,3),f=dE(a).filter(b=>!l.has(`sym:${u??""}:${b.name}`)),m=u===null?null:Eo(u,zt),g=f.length>0&&m!==null&&u!==null&&yE(m)&&n()-r<bE?await PH(f,u,m,t.openReader??vE):[],y=pE({repoRoot:u,conventions:p,symbols:g});if(y===null)return null;let _=new Map(p.map(b=>[b.convention.id,b.convention.version]));return l.mark([...y.conventionIds.map(b=>`conv:${b}@${_.get(b)??0}`),...y.symbolNames.map(b=>`sym:${u??""}:${b}`)],n()),y.text}async function MH(){try{let e=await G(),t=await EE(e);if(t!==null){let n=ce(re(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function $H(e){let t=e.tool_input;if(t===null||typeof t!="object")return null;let n=t,r=typeof n.offset=="number"&&Number.isFinite(n.offset)?n.offset:void 0,i=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0;return r===void 0&&i===void 0?null:{offset:r,limit:i}}async function TE(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=re(e,t.env??process.env,t.readConfig??te);if(!ye(r,{kind:"context",event:"PreToolUse"}))return null;let i=$e(e);if(!i||yr(i)===null||_i(i))return null;let o=SE(e);if(o===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=_E(i)?i:Eo(a,i),l;try{l=CH(c)}catch{return null}let d=qt(IH(l));if(d===null)return null;let u=Eo(d,zt);if(!yE(u))return null;let p=DH(d,l);if(p===null)return null;let f=await(t.openReader??vE)(u);try{let m=f.meta();if(!m.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=nf(l);if(y===null||!Mi(g,y))return null;let _=So.forScope(o.sessionId,o.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let w=f.symbolsInFile(p),S=m.edgesDirty?[]:f.callersOfFile(p),A=m.edgesDirty?[]:f.importersOf(p),k=[...new Set([...S.map(q=>q.caller.filePath),...A])],E=k.slice(0,tf),P=new Set(k.slice(tf)),x=f.files(E),N=new Set;for(let q of E){let Fe=x.get(q),Ro=Fe===void 0?null:nf(Eo(d,q));Fe!==void 0&&Ro!==null&&Mi(Fe,Ro)&&N.add(q)}let D=s(q=>S.filter(Fe=>q.has(Fe.caller.filePath)).length+A.filter(Fe=>q.has(Fe)).length,"countIn"),j=S.filter(q=>N.has(q.caller.filePath)).map(q=>({calleeKey:q.calleeKey,kind:q.kind,caller:{nodeKey:q.caller.nodeKey,kind:q.caller.kind,qualifiedName:q.caller.qualifiedName,filePath:q.caller.filePath,startLine:q.caller.startLine}})),W=A.filter(q=>N.has(q)),pt=D(P),To=S.length-j.length+(A.length-W.length)-pt,oi=fE({relPath:p,symbols:w,callers:j,importers:W,hidden:To,unchecked:pt,range:$H(e)});return oi===null?null:(_.mark([b],n()),oi)}finally{f.close()}}async function LH(){try{let e=await G(),t=await TE(e);if(t!==null){let n=ce(re(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var bE,tf,of=v(()=>{"use strict";Bt();ze();ha();Vn();ii();kt();mE();gE();Ks();ge();Re();bE=200,tf=200;s(DH,"repoRelative");s(nf,"diskStat");s(vE,"openReader");s(wE,"loadCachedConventions");s(kE,"promptTextOf");s(xE,"isMachinePrompt");s(SE,"scopeOf");s(PH,"locateSymbols");s(EE,"promptContextFor");s(MH,"runOnPromptContext");s($H,"readRangeOf");s(TE,"readContextFor");s(LH,"runOnReadContext")});import{randomUUID as FH}from"node:crypto";ai();import{createInterface as gI}from"node:readline";var UE=[["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 BE(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of UE)if(t.includes(n))return r;return null}s(BE,"mapClientInfoNameToFamily");function mf(e){let t;try{t=JSON.parse(e)}catch{return null}if(!uc(t)||t.method!=="initialize")return null;let n=t.params;if(!uc(n))return null;let r=n.clientInfo;if(!uc(r))return null;let i=r.name,o=BE(typeof i=="string"?i:null);if(o===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:o,version:c}}s(mf,"tryExtractInitializeClient");function uc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(uc,"isRecord");import{fileURLToPath as GE}from"node:url";var pc="maind-bridge-",KE=8,hf=8e3;function At(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(At,"isRecord");function WE(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!At(t)||t.method!=="initialize"||!At(t.params))return!1;let n=t.params.capabilities;return At(n)&&At(n.roots)}catch{return!1}}s(WE,"clientDeclaresRoots");function VE(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(VE,"isInitializedNotification");function zE(e){if(!At(e)||!At(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!At(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let i;try{i=GE(r.uri)}catch{continue}if(n.includes(i)||n.push(i),n.length>=KE)break}return n}s(zE,"rootPathsFrom");var Oo=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(pc)){let n;try{n=JSON.parse(t)}catch{n=null}if(At(n)&&typeof n.id=="string"&&n.id.startsWith(pc)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&VE(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=hf){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(c=>{let l=s(u=>{clearTimeout(d),this.waiters=this.waiters.filter(p=>p!==l),c(u)},"done"),d=setTimeout(()=>l(!1),n);this.waiters.push(l)})||this.closed))return null;let i=`${pc}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,o=new Promise(a=>{let c=s(d=>{clearTimeout(l),this.pending.delete(i),a(d)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(i,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:i,method:t})),o}};async function gf(e,t,n=hf){return WE(e)?zE(await t.request("roots/list",n)):null}s(gf,"listClientRoots");gc();yc();function _c(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let o=JSON.parse(t);return Array.isArray(o)?o:[o]}catch{return[]}let n=[],r=[],i=s(()=>{if(r.length===0)return;let o=r.join(`
|
|
955
|
+
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??GH(i),c=To(),l=SE(),d=l==="off"?null:Fo(),u=c==="off"?[]:yc(Ro())?.rules??[];c!=="off"&&_c().then(k=>{k!==null&&(u=k,gc(Ro(),k))}).catch(()=>{});let p=[],f=hc()&&z()!==null&&c!=="off",m=null;try{m=te()}catch{m=null}let g=Promise.resolve(),y=s(k=>{g=g.then(()=>zH(k)),f&&p.push(k)},"record"),_=s(async()=>{if(!f)return;let k=gE(p.splice(0),c,a,m);k!==null&&(await cf(k)||await yE(k))},"attestAndReset");f&&_E().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let v=UH(i,o,{stdio:["pipe","pipe","inherit"]});v.stdout.pipe(process.stdout),v.on("error",k=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(k)}
|
|
956
|
+
`),process.exitCode=1});let x=WH({input:process.stdin,terminal:!1});x.on("line",k=>{let E=Bf(k);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(ir(E.id,E.toolName)+`
|
|
957
|
+
`),y(Tc("deny",a,E.toolName,Date.now()));return}let P=TE(E.toolName,a,u,c);if(P.kind==="deny"&&E.id!==void 0){process.stdout.write(ir(E.id,E.toolName,RE(E.toolName,P.rule))+`
|
|
958
|
+
`),y(Rc("policy_deny",a,E.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));return}(P.kind==="warn"||P.kind==="deny")&&y(Rc("policy_warn",a,E.toolName,Date.now(),P.rule.conventionId,P.rule.conventionVersion));let S=jo(k,d);if(S.length>0){let N=S.find(W=>W.verdict==="fabricated");if(N!==void 0&&l==="enforce"&&c==="enforce"&&E.id!==void 0&&N!==void 0&&E.id!==void 0){process.stdout.write(ir(E.id,E.toolName,or(N,!0))+`
|
|
959
|
+
`),y(Ac("sha_deny",a,E.toolName,Date.now()));return}let j=N??S[0];process.stderr.write(`[maind gateway] ${or(j,!1)}
|
|
960
|
+
`),y(Ac("sha_warn",a,E.toolName,Date.now()))}y(Tc("tool_call",a,E.toolName,Date.now()))}v.stdin.write(k+`
|
|
961
|
+
`)}),x.on("close",()=>{v.stdin.end()});let C=await new Promise(k=>{v.on("exit",(E,P)=>{k(E??(P?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(k=>setTimeout(k,VH).unref())]),await _(),C}var VH,zE=w(()=>{"use strict";Cc();bE();lf();df();Ic();pf();ff();ie();he();s(GE,"gatewayEventsFile");VH=5e3;s(zH,"logEvent");s(WE,"parseGatewayArgs");s(qH,"runGateway")});var wf={};X(wf,{MAX_ENTRIES:()=>mf,TTL_MS:()=>yf,crossSessionDir:()=>_f,decideCrossSession:()=>YE,parseSessionDb:()=>JE,pruneDb:()=>bf,runGuardCrossCheck:()=>rU,runGuardCrossObserve:()=>nU,staleReason:()=>hf});import{mkdir as JH,readFile as YH,readdir as XH,stat as qE,unlink as ZH,writeFile as QH}from"node:fs/promises";import{homedir as eU}from"node:os";import{join as gf}from"node:path";function _f(){return gf(eU(),".maind","cross-session")}function JE(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[o,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[o]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[o,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[o]=a);return{files:r,warned:i}}function bf(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=yf);return n.length>mf&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-mf)),{files:Object.fromEntries(n),warned:e.warned}}function YE(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function hf(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 XE(e){let t=_f();return await JH(t,{recursive:!0}),gf(t,`${e}.json`)}async function ZE(e,t){try{let n=await YH(await XE(e),"utf8");return bf(JE(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function QE(e,t){try{await QH(await XE(e),JSON.stringify(t),{mode:384})}catch{}}async function tU(e){try{let t=_f();for(let n of await XH(t)){if(!n.endsWith(".json"))continue;let r=gf(t,n),i=await qE(r).catch(()=>null);i&&e-i.mtimeMs>yf&&await ZH(r).catch(()=>{})}}catch{}}async function e0(e){try{return(await qE(e)).mtimeMs}catch{return}}async function nU(e,t=Date.now()){try{if(le().mode==="off")return 0;let r=e??await G();if(qe(r))return 0;let i=typeof r.session_id=="string"?r.session_id:"",o=je(r);if(!i||!o)return 0;let a=await e0(o);if(a===void 0)return 0;let c=await ZE(i,t);return c.files[o]={m:a,t},delete c.warned[o],await QE(i,bf(c,t)),await tU(t),0}catch{return 0}}async function rU(e,t=Date.now()){try{let n=le();if(n.mode==="off")return 0;let r=e??await G();if(qe(r))return 0;let i=typeof r.session_id=="string"?r.session_id:"",o=je(r);if(!i||!o)return 0;let a=await ZE(i,t),c=YE(a.files[o]?.m,await e0(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Vn(hf(o,c))+`
|
|
962
|
+
`),await Q({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o}),0):(a.warned[o]===c.current||(process.stdout.write(zn(hf(o,c))+`
|
|
963
|
+
`),a.warned[o]=c.current,await QE(i,a),await Q({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var yf,mf,vf=w(()=>{"use strict";ye();Ne();so();dt();Et();yf=48*3600*1e3,mf=500;s(_f,"crossSessionDir");s(JE,"parseSessionDb");s(bf,"pruneDb");s(YE,"decideCrossSession");s(hf,"staleReason");s(XE,"dbPath");s(ZE,"loadDb");s(QE,"saveDb");s(tU,"sweepStaleSessionFiles");s(e0,"fileMtime");s(nU,"runGuardCrossObserve");s(rU,"runGuardCrossCheck")});var kf={};X(kf,{INDEX_REFRESH_WORKER:()=>t0,acquireLock:()=>Ha,releaseLock:()=>lo,runIndexRefreshWorker:()=>lU,runOnIndexRefresh:()=>cU});import{spawn as iU}from"node:child_process";import{existsSync as oU}from"node:fs";import{join as sU}from"node:path";function aU(e){return sU(e,".maind","code-index.sqlite")}async function cU(){try{let e=await G(),t=Ee(typeof e.cwd=="string"?e.cwd:process.cwd());if(!oU(aU(t))||!Ha(t))return 0;let n=process.argv[1];if(n===void 0)return lo(t),0;iU(process.execPath,[n,t0,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function lU(){let e=process.argv[3]??Ee();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Sa(),Wu)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{lo(e)}return 0}var t0,Sf=w(()=>{"use strict";ye();Qt();Qu();t0="index-refresh-run";s(aU,"indexDbPath");s(cU,"runOnIndexRefresh");s(lU,"runIndexRefreshWorker")});function vc(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 bc(e){return e.length<3||/^\d+$/.test(e)||n0.has(e)||n0.has(vc(e))}function pU(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function fU(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function i0(e){let t=new Set,n=new Set,r=[];for(let i of e.matchAll(mU)){let o=i[0],a=o.toLowerCase();if(r.push(a),/[._-]/.test(o)){let c=fU(a);c.length>=4&&!r0.has(c)&&n.add(c)}for(let c of pU(o)){let l=c.toLowerCase();bc(l)||t.add(vc(l))}}for(let i=0;i+1<r.length;i++){if(/[._-]/.test(r[i])||/[._-]/.test(r[i+1]))continue;let o=`${r[i]}-${r[i+1]}`;r0.has(o)||n.add(o)}return{words:t,compounds:n}}function hU(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 o0(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function Ef(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
964
|
+
`)){let r=gU.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 yU(e){let t=e.shortId.split("-"),n=new Set;for(let o of t)bc(o)||n.add(vc(o));let r=new Set;for(let o=0;o+1<t.length;o++)!bc(t[o])&&!bc(t[o+1])&&r.add(`${t[o]}-${t[o+1]}`);let i=i0(e.summary);for(let o of i.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(o)&&r.add(o);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:i.words}}function s0(e,t,n=3,r=[]){if(t.length===0)return[];let i=new Set([...r].map(f=>vc(f.toLowerCase()))),o=t.map(yU),a=new Map,c=new Map;for(let f of o){let m=new Set([...f.keyWords,...f.keyCompounds]);for(let g of m)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...m,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=o.length,d=s(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=i0(hU(e));for(let f of i)u.words.delete(f);let p=[];for(let f of o){let m=new Set;for(let v of u.words)f.keyWords.has(v)&&m.add(v);for(let v of u.compounds)f.keyCompounds.has(v)&&m.add(v);let g=new Set;for(let v of u.words)!m.has(v)&&f.summaryWords.has(v)&&g.add(v);if(m.size===0&&g.size===0)continue;let y=0;for(let v of m)y+=2*d(v);for(let v of g)y+=d(v);let _=[...m].some(v=>(a.get(v)??0)!==1?!1:/[.-]/.test(v)?v.length>=5:v.length>=6),b=m.size>=1&&m.size+g.size>=2&&y>=_U;!_&&!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 vU(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function a0(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],i=new Set,o=s((c,l)=>{if(r.length>=t)return;let d=c.endsWith("()"),u=d?c.slice(0,-2):c;if(u.includes("/")||bU.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!vU(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||wU.has(f.toLowerCase())||i.has(f)||(i.add(f),r.push({name:f,qualifier:p.length>1?p[p.length-2]:null}))},"consider");for(let c of n.matchAll(/`([^`\n]{1,120})`/g))o(c[1].trim(),!0);let a=n.replace(/`[^`\n]{1,120}`/g," ");for(let c of a.matchAll(/(?<![\w$./\\-])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)(?![\w$/\\-])/g))o(c[1],!1);return r}function xf(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function l0(e,t=2e3){let n=e.conventions,r=e.symbols.filter(d=>d.locations.length>0);if(n.length===0&&r.length===0)return null;let i=new wc(t-c0);if(!i.tryAdd(`${dU} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let o=[],a=[],c=!1;if(n.length>0&&i.tryAdd("Project conventions whose terms appear in this prompt (full text: get_conventions({id})):"))for(let d of n){let u=`- ${d.convention.id} (v${d.convention.version}): ${xf(d.convention.summary,320)}`;if(!i.tryAdd(u)){c=!0;break}o.push(d.convention.id)}if(r.length>0&&!c){let d=e.repoRoot?` in ${e.repoRoot}`:"";if(i.tryAdd(`Symbols this prompt names, as the local code index places them${d} (files unchanged since indexing):`))for(let u of r){let p=u.locations.slice(0,3),f=p.map(y=>{let _=y.qualifiedName===u.candidate.name?y.kind:`${y.kind} ${y.qualifiedName}`;return`${y.filePath}:${y.startLine} (${_})${y.signature?` '${xf(y.signature,70)}'`:""}`}).join("; "),m=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${m>0?` (+${m} more \u2014 codebase_search)`:""}`;if(!i.tryAdd(g)){c=!0;break}a.push(u.candidate.name)}}if(o.length===0&&a.length===0)return null;let l=i.toString();return c&&(l+=`
|
|
965
|
+
(trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:o,symbolNames:a}}function SU(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>kU}function xU(e){if(e.length===0)return"";let t=e.map(i=>i.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(i=>i[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function EU(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function d0(e,t=1500){let n=new Map;for(let g of e.callers){let y=n.get(g.calleeKey)??[];y.some(_=>_.caller.nodeKey===g.caller.nodeKey)||y.push(g),n.set(g.calleeKey,y)}let r=s(g=>new Set((n.get(g)??[]).map(y=>y.caller.filePath)).size,"fileCount"),i=e.symbols.filter(g=>n.has(g.nodeKey)).sort((g,y)=>r(y.nodeKey)-r(g.nodeKey)||g.startLine-y.startLine),o=e.symbols.reduce((g,y)=>Math.max(g,y.endLine),0),a=e.symbols.filter(g=>!g.qualifiedName.includes(".")&&g.kind!=="module"),c=SU(e.range,o)&&a.length>0;if(i.length===0&&e.importers.length===0&&!c)return null;let l=xU([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new wc(t-c0),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${uU} ${e.relPath} as the local code index knows it (the index matches this file on disk).${u}`))return null;let p=!1;if(c&&d.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let g="",y=0;for(let b of a){let v=`${b.qualifiedName} L${b.startLine}`,x=g.length===0?v:`${g} \xB7 ${v}`;if(x.length>500)break;g=x,y++}let _=a.length-y;d.tryAdd(_>0?`${g} \xB7 +${_} more`:g)||(p=!0)}if(i.length>0&&!p&&d.tryAdd("Called from other files (import-resolved call graph):"))for(let g of i){let y=n.get(g.nodeKey)??[],_=y.slice(0,3).map(C=>`${EU(C.caller,l)}${C.kind==="calls"?"":` [${C.kind}]`}`),b=y.length-_.length,v=g.signature?` '${xf(g.signature,80)}'`:"",x=`- ${g.qualifiedName} L${g.startLine}${v} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!d.tryAdd(x)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(v=>v.slice(l.length)),y=e.importers.length-g.length,_=e.importers.length,b=`Imported by ${_} file${_===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(b)||(p=!0)}e.hidden>0&&!p&&d.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let f=e.unchecked??0;if(f>0&&!p&&d.tryAdd(`(+${f} more reference${f===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),d.size<=1)return null;let m=d.toString();return p&&(m+=`
|
|
966
|
+
(trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var dU,uU,n0,r0,mU,gU,_U,bU,wU,wc,c0,kU,u0=w(()=>{"use strict";dU="[maind context \xB7 prompt]",uU="[maind context \xB7 read]",n0=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+/)),r0=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(vc,"stem");s(bc,"isNoise");s(pU,"splitParts");s(fU,"normalizeCompound");mU=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(i0,"termsOf");s(hU,"promptForMatching");s(o0,"repoNameWords");gU=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(Ef,"parseConventionLines");s(yU,"profileOf");_U=4.5;s(s0,"matchConventions");bU=/\.(?: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,wU=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(vU,"looksLikeCode");s(a0,"extractSymbolCandidates");s(xf,"clip");wc=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(`
|
|
967
|
+
`)}},c0=90;s(l0,"renderPromptContext");kU=2e3;s(SU,"isPartialRead");s(xU,"commonDir");s(EU,"callerLabel");s(d0,"renderReadContext")});import{createHash as TU}from"node:crypto";import{existsSync as p0,mkdirSync as RU,readdirSync as AU,rmSync as CU,statSync as IU,writeFileSync as NU}from"node:fs";import{join as kc}from"node:path";function Tf(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function PU(e,t,n=null,r=DU){try{for(let i of AU(e)){let o=kc(e,i);if(o!==n)try{t-IU(o).mtimeMs>r&&CU(o,{recursive:!0,force:!0})}catch{}}}catch{}}var OU,DU,Co,f0=w(()=>{"use strict";Ie();OU=kc(ve,"context"),DU=7*24*60*60*1e3;s(Tf,"safe");Co=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=OU){let i=n?`${Tf(t)}__${Tf(n)}`:Tf(t);return new e(r,kc(r,i))}fileFor(t){return kc(this.dir,TU("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return p0(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{p0(this.dir)||(RU(this.dir,{recursive:!0,mode:448}),PU(this.root,n,this.dir));for(let r of t)try{NU(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(PU,"sweepStaleScopes")});var Cf={};X(Cf,{INDEX_RELPATH:()=>qt,SOFT_BUDGET_MS:()=>g0,findRepoRoot:()=>Jt,isMachinePrompt:()=>w0,loadCachedConventions:()=>_0,promptContextFor:()=>k0,promptTextOf:()=>b0,readContextFor:()=>S0,runOnPromptContext:()=>KU,runOnReadContext:()=>WU});import{existsSync as m0,readFileSync as MU,realpathSync as $U,statSync as LU}from"node:fs";import{dirname as FU,isAbsolute as h0,join as Io,relative as jU,sep as HU}from"node:path";function UU(e,t){let n=jU(e,t);return!n||n.startsWith("..")||h0(n)?null:n.split(HU).join("/")}function Af(e){try{let t=LU(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function y0(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Sa(),Wu));return t(e)}function _0(e,t={}){try{let n=t.identity===void 0?Eo():t.identity;if(e!==null&&n!==null){let r=Cs(e,n),i=Oa(r?.result.instructions??null),o=Ef(i);if(o.length>0)return o}}catch{}try{let n=JSON.parse(MU(t.briefingCacheFile??zr,"utf8"));if(typeof n.conventions=="string")return Ef(n.conventions)}catch{}return[]}function b0(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function w0(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 v0(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 BU(e,t,n,r){let i;try{i=await r(n)}catch{return[]}try{if(!i.meta().schemaCurrent)return[];let o=i.symbolsNamed(e.map(d=>d.name)),a=i.files([...o.values()].flat().map(d=>d.filePath).slice(0,Rf)),c=new Set;for(let[d,u]of a){let p=Af(Io(t,d));p!==null&&Hi(u,p)&&c.add(d)}let l=[];for(let d of e){let u=o.get(d.name)??[],p=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),f=p.length>0?p:u,m=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));m.length>0&&l.push({candidate:d,locations:m,total:f.length})}return l}catch{return[]}finally{try{i.close()}catch{}}}async function k0(e,t={}){let n=t.now??Date.now,r=n(),i=t.env??process.env,o=oe(e,i,t.readConfig??ee);if(!_e(o,{kind:"context",event:"UserPromptSubmit"}))return null;let a=b0(e);if(a.trim().length===0||w0(e,a))return null;let c=v0(e);if(c===null)return null;let l=Co.forScope(c.sessionId,c.agentId,t.seenRoot),d=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:Aa(o,i)??process.cwd(),u=Jt(d),p=s0(a,(t.loadConventions??_0)(u),6,o0(u)).filter(b=>!l.has(`conv:${b.convention.id}@${b.convention.version}`)).slice(0,3),f=a0(a).filter(b=>!l.has(`sym:${u??""}:${b.name}`)),m=u===null?null:Io(u,qt),g=f.length>0&&m!==null&&u!==null&&m0(m)&&n()-r<g0?await BU(f,u,m,t.openReader??y0):[],y=l0({repoRoot:u,conventions:p,symbols:g});if(y===null)return null;let _=new Map(p.map(b=>[b.convention.id,b.convention.version]));return l.mark([...y.conventionIds.map(b=>`conv:${b}@${_.get(b)??0}`),...y.symbolNames.map(b=>`sym:${u??""}:${b}`)],n()),y.text}async function KU(){try{let e=await G(),t=await k0(e);if(t!==null){let n=ce(oe(e),{kind:"context",event:"UserPromptSubmit",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}function GU(e){let t=e.tool_input;if(t===null||typeof t!="object")return null;let n=t,r=typeof n.offset=="number"&&Number.isFinite(n.offset)?n.offset:void 0,i=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0;return r===void 0&&i===void 0?null:{offset:r,limit:i}}async function S0(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read")return null;let r=oe(e,t.env??process.env,t.readConfig??ee);if(!_e(r,{kind:"context",event:"PreToolUse"}))return null;let i=je(e);if(!i||yr(i)===null||Si(i))return null;let o=v0(e);if(o===null)return null;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=h0(i)?i:Io(a,i),l;try{l=$U(c)}catch{return null}let d=Jt(FU(l));if(d===null)return null;let u=Io(d,qt);if(!m0(u))return null;let p=UU(d,l);if(p===null)return null;let f=await(t.openReader??y0)(u);try{let m=f.meta();if(!m.schemaCurrent)return null;let g=f.file(p);if(g===null)return null;let y=Af(l);if(y===null||!Hi(g,y))return null;let _=Co.forScope(o.sessionId,o.agentId,t.seenRoot),b=`read:${d}:${p}@${g.contentHash}`;if(_.has(b))return null;let v=f.symbolsInFile(p),x=m.edgesDirty?[]:f.callersOfFile(p),C=m.edgesDirty?[]:f.importersOf(p),k=[...new Set([...x.map(J=>J.caller.filePath),...C])],E=k.slice(0,Rf),P=new Set(k.slice(Rf)),S=f.files(E),N=new Set;for(let J of E){let He=S.get(J),Oo=He===void 0?null:Af(Io(d,J));He!==void 0&&Oo!==null&&Hi(He,Oo)&&N.add(J)}let D=s(J=>x.filter(He=>J.has(He.caller.filePath)).length+C.filter(He=>J.has(He)).length,"countIn"),j=x.filter(J=>N.has(J.caller.filePath)).map(J=>({calleeKey:J.calleeKey,kind:J.kind,caller:{nodeKey:J.caller.nodeKey,kind:J.caller.kind,qualifiedName:J.caller.qualifiedName,filePath:J.caller.filePath,startLine:J.caller.startLine}})),W=C.filter(J=>N.has(J)),ut=D(P),No=x.length-j.length+(C.length-W.length)-ut,di=d0({relPath:p,symbols:v,callers:j,importers:W,hidden:No,unchecked:ut,range:GU(e)});return di===null?null:(_.mark([b],n()),di)}finally{f.close()}}async function WU(){try{let e=await G(),t=await S0(e);if(t!==null){let n=ce(oe(e),{kind:"context",event:"PreToolUse",text:t});n!==null&&process.stdout.write(n)}}catch{}return 0}var g0,Rf,If=w(()=>{"use strict";Bt();Ce();Pa();Xn();li();vt();u0();f0();la();ye();Ne();g0=200,Rf=200;s(UU,"repoRelative");s(Af,"diskStat");s(y0,"openReader");s(_0,"loadCachedConventions");s(b0,"promptTextOf");s(w0,"isMachinePrompt");s(v0,"scopeOf");s(BU,"locateSymbols");s(k0,"promptContextFor");s(KU,"runOnPromptContext");s(GU,"readRangeOf");s(S0,"readContextFor");s(WU,"runOnReadContext")});import{randomUUID as VU}from"node:crypto";pi();import{createInterface as fN}from"node:readline";var F0=[["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 j0(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of F0)if(t.includes(n))return r;return null}s(j0,"mapClientInfoNameToFamily");function jf(e){let t;try{t=JSON.parse(e)}catch{return null}if(!xc(t)||t.method!=="initialize")return null;let n=t.params;if(!xc(n))return null;let r=n.clientInfo;if(!xc(r))return null;let i=r.name,o=j0(typeof i=="string"?i:null);if(o===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:o,version:c}}s(jf,"tryExtractInitializeClient");function xc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(xc,"isRecord");import{fileURLToPath as H0}from"node:url";var Ec="maind-bridge-",U0=8,Hf=8e3;function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ct,"isRecord");function B0(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Ct(t)||t.method!=="initialize"||!Ct(t.params))return!1;let n=t.params.capabilities;return Ct(n)&&Ct(n.roots)}catch{return!1}}s(B0,"clientDeclaresRoots");function K0(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(K0,"isInitializedNotification");function G0(e){if(!Ct(e)||!Ct(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Ct(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let i;try{i=H0(r.uri)}catch{continue}if(n.includes(i)||n.push(i),n.length>=U0)break}return n}s(G0,"rootPathsFrom");var Lo=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(Ec)){let n;try{n=JSON.parse(t)}catch{n=null}if(Ct(n)&&typeof n.id=="string"&&n.id.startsWith(Ec)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&K0(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=Hf){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(c=>{let l=s(u=>{clearTimeout(d),this.waiters=this.waiters.filter(p=>p!==l),c(u)},"done"),d=setTimeout(()=>l(!1),n);this.waiters.push(l)})||this.closed))return null;let i=`${Ec}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,o=new Promise(a=>{let c=s(d=>{clearTimeout(l),this.pending.delete(i),a(d)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(i,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:i,method:t})),o}};async function Uf(e,t,n=Hf){return B0(e)?G0(await t.request("roots/list",n)):null}s(Uf,"listClientRoots");Cc();Ic();function Nc(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let o=JSON.parse(t);return Array.isArray(o)?o:[o]}catch{return[]}let n=[],r=[],i=s(()=>{if(r.length===0)return;let o=r.join(`
|
|
958
968
|
`).trim();if(r=[],o.length!==0)try{n.push(JSON.parse(o))}catch{}},"flush");for(let o of t.split(`
|
|
959
|
-
`)){let a=o.endsWith("\r")?o.slice(0,-1):o;if(a===""){i();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return i(),n}s(
|
|
960
|
-
`),o!==null&&o.initFrame!==null&&(o.pendingFrame===null||!Rr(o.pendingFrame))),this.shaRepoRoot=
|
|
969
|
+
`)){let a=o.endsWith("\r")?o.slice(0,-1):o;if(a===""){i();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return i(),n}s(Nc,"rpcMessagesOf");function qf(e,t){for(let n of Nc(e)){if(typeof n!="object"||n===null)continue;let r=n;if(r.id!==t)continue;if(typeof r.error=="object"&&r.error!==null){let c=r.error;return{kind:"rpc_error",code:typeof c.code=="number"?c.code:-32603,message:typeof c.message=="string"?c.message:""}}let i=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(i.content)?i.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:i.isError===!0,text:a?.text??""}}return null}s(qf,"parseCloudToolResponse");vt();var mN="https://mcp.maind.dev/mcp",Ui=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},Os=class{static{s(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;onSessionReady;assignedInbox;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;pendingFrame=null;clientChannel;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=Tr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=hN(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=gN(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.onConnectionOutcome=t.onConnectionOutcome??null,this.onSessionReady=t.onSessionReady??null,this.assignedInbox=t.assignedInbox??null;let o=t.carry??null;o!==null&&(this.initFrame=o.initFrame,this.clientFamily===null&&(this.clientFamily=o.clientFamily),this.clientVersion===null&&(this.clientVersion=o.clientVersion),this.replayFrame=o.pendingFrame),this.clientChannel=new Lo(a=>process.stdout.write(a+`
|
|
970
|
+
`),o!==null&&o.initFrame!==null&&(o.pendingFrame===null||!Rr(o.pendingFrame))),this.shaRepoRoot=Fo(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??mN}async run(t=Fd()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r){this.clientChannel.close();return}let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}listClientRoots(t){return Uf(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=jf(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Rr(t)&&(this.initFrame=t);let r=bN(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=jo(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&Vf(p)&&r.id!==null){let m=or(p,!0);process.stderr.write(`[maind] ${m}
|
|
961
971
|
`);let g=r.params?.name;process.stdout.write(ir(r.id,typeof g=="string"?g:"unknown",m)+`
|
|
962
972
|
`);return}i=or(f,!1),process.stderr.write(`[maind] ${i}
|
|
963
|
-
`)}if(this.assignedInbox&&!
|
|
973
|
+
`)}if(this.assignedInbox&&!Ff(this.clientFamily)){let p=this.assignedInbox.takeNote();p!==null&&(i=i===null?p:`${i}
|
|
964
974
|
[maind] ${p}`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let u=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(u+`
|
|
965
|
-
`);return}let o=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Rr(t)&&await this.recoverSession();let a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(u){let p=
|
|
966
|
-
`);return}if(Rr(t)){let u=d.startsWith("text/event-stream")?await
|
|
967
|
-
`);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await
|
|
968
|
-
`);return}if(d.startsWith("text/event-stream"))await
|
|
969
|
-
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new
|
|
970
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
975
|
+
`);return}let o=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Rr(t)&&await this.recoverSession();let a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(u){let p=Is(t);if(this.serveInitializeFromCache(t,p))return;Ns(p,-32603,`bridge network error: ${M_(u)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.ok&&!this.connectionOkRecorded&&(this.connectionOkRecorded=!0,this.recordOutcome("ok",null)),c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!Rr(t)){let u=await c.text().catch(()=>"");if(P_(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=Is(t);Ns(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Is(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;Ns(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(o&&this.localRouter){let u=d.startsWith("text/event-stream")?await $d(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
976
|
+
`);return}if(Rr(t)){let u=d.startsWith("text/event-stream")?await $d(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
977
|
+
`);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await $d(c):await c.text(),p=_N(u,i);p.trim().length>0&&process.stdout.write(p+`
|
|
978
|
+
`);return}if(d.startsWith("text/event-stream"))await yN(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
979
|
+
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new Ui(vN(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=Is(n);Ns(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(t,n){try{this.onConnectionOutcome?.(t,n)}catch{}}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),o=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return kN(o)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,o=await this.postCloudToolCall(t,n,i);if(o.kind!=="session_lost")return o;if(!await this.recoverSession())return{kind:"http_error",status:404,body:o.body.slice(0,500)};let a=await this.postCloudToolCall(t,n,i);return a.kind==="session_lost"?{kind:"http_error",status:404,body:a.body.slice(0,500)}:a}async postCloudToolCall(t,n,r){this.cloudFrameId+=1;let i=`maind-bridge-${this.cloudFrameId}`,o=JSON.stringify({jsonrpc:"2.0",id:i,method:"tools/call",params:{name:t,arguments:n}});try{let a=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:o,signal:AbortSignal.timeout(r)}),c=a.headers.get("mcp-session-id");c&&c!==this.sessionId&&(this.sessionId=c);let l=await a.text();return a.status===404&&P_(l)?{kind:"session_lost",body:l}:a.ok?qf(l,i)??{kind:"transport_error",message:`the response carried no answer to ${i}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:a.status,body:l.slice(0,500)}}catch(a){return{kind:"transport_error",message:M_(a),timedOut:wN(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=We()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&O_(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Rr(t))return!1;let r=Cs(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(D_(n,r)+`
|
|
980
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${As(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Fd(){return fN({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}s(Fd,"stdinLines");function hN(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(hN,"normalizeClientFamily");function gN(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(gN,"normalizeClientVersion");async function yN(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=s(()=>{if(i.length===0)return;let a=i.join(`
|
|
971
981
|
`).trim();i=[],a.length>0&&process.stdout.write(a+`
|
|
972
982
|
`)},"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(`
|
|
973
|
-
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){o();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{o()}}s(
|
|
983
|
+
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){o();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{o()}}s(yN,"pipeSseToStdout");function _N(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(_N,"appendNoteToToolResult");function bN(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(bN,"parseRpc");async function $d(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],a=s(()=>{if(o.length===0)return;let c=o.join(`
|
|
974
984
|
`).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
975
985
|
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
|
|
976
|
-
`)}s(
|
|
977
|
-
`)}s(
|
|
978
|
-
`),null));if(p){if(p.status==="approved")return
|
|
986
|
+
`)}s($d,"collectSseText");function Is(e){try{return JSON.parse(e).id??null}catch{return null}}s(Is,"tryExtractId");function Rr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Rr,"isInitializeRequest");function P_(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(P_,"isSessionLossBody");function M_(e){return e instanceof Error?e.message:String(e)}s(M_,"stringifyErr");function wN(e){return e?.name==="TimeoutError"}s(wN,"isTimeoutError");function Ns(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
987
|
+
`)}s(Ns,"emitJsonRpcError");function vN(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(vN,"extractHint");function kN(e){try{let t=Nc(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(kN,"parsePresenceToolResult");ie();ie();Cr();import{spawn as DN}from"node:child_process";import{platform as PN}from"node:os";async function Ir(e,t=process.stderr){let n=Ki(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=Ps(e),a=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:o})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await FN(l.verification_uri_complete).catch(()=>{}),LN(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await $N(u);let p=await MN(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
|
|
988
|
+
`),null));if(p){if(p.status==="approved")return On(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
979
989
|
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
980
990
|
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
981
991
|
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
982
|
-
`),null}s(Ir,"runDeviceFlow");async function
|
|
992
|
+
`),null}s(Ir,"runDeviceFlow");async function MN(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}s(MN,"pollOnce");function $N(e){return new Promise(t=>setTimeout(t,e))}s($N,"sleep");function LN(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: ${H_(e.verification_uri,56)} \u2502`,` \u2502 Code: ${H_(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(`
|
|
983
993
|
`)+`
|
|
984
|
-
`)}s(
|
|
985
|
-
`)}s(
|
|
994
|
+
`)}s(LN,"printAuthInstructions");function H_(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(H_,"pad");async function FN(e){let t,n;switch(PN()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let o=DN(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(FN,"openExternalBrowser");Bd();ze();he();ze();import*as qv from"node:os";Mn();var Hs={devin:"windsurf"};function Gd(){return Kd.map(e=>{let t=Object.keys(Hs).filter(n=>Hs[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}s(Gd,"familyChoices");function sb(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,hooksOnly:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--hooks-only":t.hooksOnly=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Fe("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Fe("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Fe("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Fe("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Fe(`--client requires a family argument (${Gd()})`);let o=i.trim().toLowerCase(),a=Object.hasOwn(Hs,o)?Hs[o]:o;if(!Kd.includes(a))throw new Fe(`--client "${i}" is not a known client family. Known: ${Gd()}`);t.client=a,n++;break}default:throw new Fe(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}if(t.full&&(t.nonInteractive=!0),t.hooksOnly){let n=[t.noHook&&"--no-hook",t.projectRoot!==null&&"--project-root",t.noPreamble&&"--no-preamble",t.token!==null&&"--token",t.oneClickToken!==null&&"--one-click-token",t.oneClickExchangeUrl!==null&&"--one-click-exchange-url",t.client!==null&&"--client",t.skipCodex&&"--skip-codex",t.telemetry&&"--telemetry",t.autoWorkingPaths&&"--auto-working-paths"].filter(r=>typeof r=="string");if(n.length>0)throw new Fe(`--hooks-only wires the Claude Code hooks and nothing else \u2014 drop ${n.join(", ")}`)}return t}s(sb,"parseInstallFlags");var Fe=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function ab(){process.stdout.write(bO())}s(ab,"printInstallHelp");function bO(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Devin Desktop (formerly Windsurf) / Copilot files. Idempotent \u2014","re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${Gd()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --skip-codex Skip Codex's config.toml even where Codex is installed",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only wire the hooks: Claude Code's in ~/.claude/settings.json and,"," where Cursor is installed, Cursor's in ~/.cursor/hooks.json"," (no pairing, no MCP configs, no preamble files) \u2014 adds what"," an existing install is missing; with --full, without prompts"," --telemetry Opt-in: post anonymous install_completed event"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
|
|
995
|
+
`)}s(bO,"installHelpText");var zi=class{static{s(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
|
|
986
996
|
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),o=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),a=s((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),l.push(c);for(let d of this.results)l.push(`| ${a(d.target,n)} | ${a(d.action,r)} | ${a(d.status,i)} | ${a(d.detail??"",o)} |`);return l.join(`
|
|
987
997
|
`)+`
|
|
988
998
|
`}print(t){let n=this.summary();t.write(`
|
|
989
999
|
`),t.write(this.toMarkdownTable()),t.write(`
|
|
990
1000
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
991
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};
|
|
992
|
-
`;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await
|
|
993
|
-
`}}),i=
|
|
1001
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};Wd();Mn();Kt();we();Ks();we();Mn();import{applyEdits as AO,modify as CO,parse as IO,printParseErrorCode as NO}from"jsonc-parser";var $n="maind";async function wb(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=ob(e),i=r.serversKey==="servers",o;try{o=await Y(e.path)}catch(m){return zd(e,"read",m)}let a,c="create";if(o===null||o.trim().length===0)a={};else{c="merge";try{a=i?OO(o):JSON.parse(o)}catch(m){return e.refreshOnly!==void 0?bb(e,`not valid JSON: ${m instanceof Error?m.message:String(m)}`):zd(e,"parse",m)}}if(!Vt(a))return e.refreshOnly!==void 0?bb(e,"not a JSON object at root"):{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};if(e.refreshOnly!==void 0){let m=a[r.serversKey];if(o===null||!Vt(m)||!($n in m))return{target:e.key,action:"merge",status:"skipped",detail:e.refreshOnly.skipDetail}}let l=e.key==="claude-code-user"&&PO(a),d,u,p=!1;if(l){let m=a[$n];p=_b(m,t,r),u=yb(m,t,r),d={...a,[$n]:u}}else{let m=a[r.serversKey],g=Vt(m)?m:{},y=g[$n];p=_b(y,t,r),u=yb(y,t,r),d={...a,[r.serversKey]:{...g,[$n]:u}}}if(p&&o!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=i&&!l?DO(o??"",[r.serversKey,$n],u):JSON.stringify(d,null,2)+`
|
|
1002
|
+
`;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await V(e.path,f)}catch(m){return zd(e,"write",m)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}s(wb,"mergeJsonConfig");function yb(e,t,n){let r=Vt(e)&&Vt(e.env)?e.env:{},i={...t.env};for(let[p,f]of Object.entries(r))!(p in i)&&typeof f=="string"&&(i[p]=f);let o={command:t.command,args:[...t.args],env:i},a=n.entryType===void 0?o:{type:n.entryType,...o};if(n.clientKeys===void 0)return a;let{defaults:c,drop:l}=n.clientKeys,d={};if(Vt(e))for(let[p,f]of Object.entries(e))p in a||l.includes(p)||(d[p]=f);let u=Object.entries(c).filter(([p])=>!(p in d));return{...a,...d,...Object.fromEntries(u)}}s(yb,"mergeEntry");function OO(e){let t=[],n=IO(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${NO(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}s(OO,"parseJsoncStrict");function DO(e,t,n){let r=CO(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
|
|
1003
|
+
`}}),i=AO(e,r);return i.endsWith(`
|
|
994
1004
|
`)?i:i+`
|
|
995
|
-
`}s(
|
|
1005
|
+
`}s(DO,"editInPlace");function PO(e){return!("mcpServers"in e||!($n in e))}s(PO,"hasRootShape");function _b(e,t,n){if(!Vt(e)||n.entryType!==void 0&&e.type!==n.entryType||n.clientKeys!==void 0&&n.clientKeys.drop.some(r=>r in e)||e.command!==t.command||!MO(e.args,t.args)||!Vt(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}s(_b,"serverEntriesEqual");function MO(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}s(MO,"arrayEquals");function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Vt,"isObject");function bb(e,t){return{target:e.key,action:"merge",status:"skipped",detail:`left alone \u2014 ${t}`}}s(bb,"leftAlone");function zd(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(zd,"failed");we();import{parse as $O,stringify as LO}from"smol-toml";async function vb(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 Y(e.path)}catch(g){return Gs(e,"read",g)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let g=$O(r);if(!Ln(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return Gs(e,"parse",g)}}let a=Ln(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Ln(c)&&FO(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Ln(c)&&Ln(c.env)?c.env:{},d={...t.env};for(let[g,y]of Object.entries(l))!(g in d)&&typeof y=="string"&&(d[g]=y);let u={command:t.command,args:[...t.args],env:d},p={...i,mcp_servers:{...a,maind:u}},f;try{f=LO(p),f.endsWith(`
|
|
996
1006
|
`)||(f+=`
|
|
997
|
-
`)}catch(g){return
|
|
1007
|
+
`)}catch(g){return Gs(e,"write",g)}let m=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await V(e.path,f)}catch(g){return Gs(e,"write",g)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(vb,"mergeTomlConfig");function FO(e,t){if(!Ln(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!Ln(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(FO,"tomlServerEntryEqual");function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ln,"isObject");function Gs(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Gs,"failed");Yd();su();nu();ct();Ce();we();import*as Ob from"node:readline";var Un="config:auto_working_paths",gD=`
|
|
998
1008
|
Enable presence enrichment (auto working_paths)?
|
|
999
1009
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
1000
1010
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -1003,46 +1013,58 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
1003
1013
|
absolute paths. Server-side these paths are account-private (org members never
|
|
1004
1014
|
see them) and revocable any time on the dashboard consent page or via
|
|
1005
1015
|
{"auto_working_paths": false} in the bridge config.
|
|
1006
|
-
[y/N]: `;async function
|
|
1007
|
-
`;if(e.dryRun)return{target:
|
|
1016
|
+
[y/N]: `;async function Db(e){let t=e.configPath??Ae(),n={};try{let a=await Y(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:Un,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:Un,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??yD)(e.out,gD)}else return{target:Un,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Un,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},o=JSON.stringify(i,null,2)+`
|
|
1017
|
+
`;if(e.dryRun)return{target:Un,action:"merge",status:"would-merge",detail:t};try{await V(t,o,384)}catch(a){return{target:Un,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Un,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(Db,"applyWorkingPathsConsent");async function yD(e,t){e.write(t);let n=Ob.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}s(yD,"promptYesNoDefaultNo");Ce();ca();we();import{rmSync as FP}from"node:fs";import*as _w from"node:readline";var zt="config:checkout_memory",jP=`
|
|
1018
|
+
Remember the repositories you edit in (checkout memory)?
|
|
1019
|
+
With this ON, the repo-health hook (before an edit) and the Stop hook (after a
|
|
1020
|
+
turn) record the ROOT directory of each git checkout you edit in, plus its
|
|
1021
|
+
project key (a hash of the git remote), in ~/.maind/checkout-roots.json. That is
|
|
1022
|
+
what lets a feature worktree deleted before the session's last turn keep its
|
|
1023
|
+
token cost on the right repository (ADR-329). Checkout roots and hashes only \u2014
|
|
1024
|
+
never file names, never contents. The file never leaves this machine; entries
|
|
1025
|
+
not seen for 90 days are pruned. Without it, a deleted worktree is still
|
|
1026
|
+
recognised when it follows the \`maind feature start\` naming (<repo>-<name>).
|
|
1027
|
+
Off later: {"checkout_memory": false} in the bridge config.
|
|
1028
|
+
[Y/n]: `;async function Nu(e){let t=e.configPath??Ae(),n=e.memoryPath??jr;if(e.skip)return{target:zt,action:"skip",status:"skipped",detail:"--no-hook"};let r={};try{let a=await Y(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:zt,action:"skip",status:"skipped",detail:`already decided (${r.checkout_memory?"on":"off"}) in ${t}`};let i;if(e.full)i=!0;else if(e.isInteractive){if(e.dryRun)return{target:zt,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};i=await(e.promptFn??HP)(e.out,jP)}else return{target:zt,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:zt,action:"merge",status:"would-merge",detail:t};let o={...r,checkout_memory:i};try{await V(t,JSON.stringify(o,null,2)+`
|
|
1029
|
+
`,384)}catch(a){return{target:zt,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}if(!i){let a=!1;try{FP(n,{force:!0}),a=!0}catch{a=!1}return{target:zt,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory off${a?`; ${n} removed if it existed`:`; could not remove ${n}`}`}}return{target:zt,action:"merge",status:"merged",detail:`${t} \u2014 checkout memory on (${n}, local only; off: checkout_memory=false)`}}s(Nu,"applyCheckoutMemoryConsent");async function HP(e,t){e.write(t);let n=_w.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}s(HP,"promptYesNoDefaultYes");la();import{existsSync as KP}from"node:fs";import{join as GP}from"node:path";function WP(e){let t=e.find(n=>n.target.startsWith("hook(on-read-context)"));return t===void 0?!1:t.status==="skipped"?/already runs maind on-read-context/.test(t.detail??""):t.status!=="failed"}s(WP,"readHookWired");function ww(e,t,n=KP){if(!WP(t))return null;let r=Jt(e,n)??e;return n(GP(r,qt))?null:{target:"context-moment",action:"probe",status:"skipped",detail:`on-read-context is wired, but ${r} has no code index yet \u2014 it stays silent there until one exists. Ask your agent to run codebase_index once (or run \`maind index\` in the repo); the Stop hook keeps it fresh after that.`}}s(ww,"contextIndexRow");we();Kt();Mn();Ks();import*as Pu from"node:path";import*as kw from"node:readline";var VP=Pu.join(".cursor","hooks.json"),Ou=1,zP="on-cursor-session-start",vw=[{event:"sessionStart",subcommand:zP,label:"Cursor sessionStart hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-cursor-session-start' when a Cursor agent conversation starts and returns your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 as `additional_context` for the conversation's initial system context, kept under 10,000 characters. Delivery, not enforcement: it never blocks anything. It talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, the project key (a hash of the repository's git remote) and the client family 'cursor' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most starts add no network call. It records the conversation id, Cursor's transcript path and the size of what it returned in a local log (~/.maind/cursor/deliveries.jsonl), so `maind sessions scan-conventions --client cursor` can tell delivered from arrived; that log never leaves the machine. Cursor documents that it can drop sessionStart context in a race \u2014 the AGENTS.md block stays the reliable channel there."}];function Sw(e){return`hook(${e.subcommand}):~/.cursor/hooks.json`}s(Sw,"targetKeyFor");function Gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Gn,"isObject");function qP(e,t,n){if(!Gn(e)||!Gn(e.hooks))return null;let r=e.hooks[t];if(!Array.isArray(r))return null;for(let i of r)if(Gn(i)&&typeof i.command=="string"&&i.command.includes(n))return i.command;return null}s(qP,"findCursorHookCommand");async function JP(e,t){let n=Pu.join(e.homeDir,VP),r=Sw(t),i=s((g,y,_="merge")=>({target:r,action:_,status:g,detail:y}),"row");if(e.skip)return i("skipped","--no-hook","skip");let o;try{o=await Y(n)}catch(g){return i("failed",`read: ${Du(g)}`)}let a={},c=o===null||o.trim().length===0;if(!c){let g;try{g=JSON.parse(o)}catch(_){return i("failed",`parse: ${Du(_)} \u2014 ${n} left untouched`)}if(!Gn(g))return i("failed",`${n} is not a JSON object \u2014 left untouched`);if(a=g,a.version!==void 0&&a.version!==Ou)return i("skipped",`hooks.json version ${JSON.stringify(a.version)} is not one this bridge knows (expects ${Ou}) \u2014 left untouched`,"skip");if(a.hooks!==void 0&&!Gn(a.hooks))return i("failed",`"hooks" in ${n} is not an object \u2014 left untouched`);let y=Gn(a.hooks)?a.hooks[t.event]:void 0;if(y!==void 0&&!Array.isArray(y))return i("failed",`"hooks.${t.event}" in ${n} is not an array \u2014 left untouched`)}let l=e.launch??xe({entryPath:ge(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),d=it(l),u=qP(a,t.event,t.subcommand);if(u!==null){let g=`${t.label} already runs maind ${t.subcommand}`;return i("skipped",Or(u)?`${g}, but via \`npx\` \u2014 PATH decides which bridge that is. Replace its command with: ${d}`:g,"skip")}if(!e.full){if(!e.isInteractive)return i("skipped","consent-required: pass --full to write the hook non-interactively","skip");if(e.dryRun)return i(c?"would-create":"would-merge",`${n} (would prompt for consent in real run)`);if(!await(e.prompt??YP)(e.out,`
|
|
1008
1030
|
Add a ${t.event} hook to ${n}?
|
|
1009
1031
|
${t.consentDescription}
|
|
1010
|
-
[Y/n]: `))return i("skipped","user declined","skip")}let p=
|
|
1011
|
-
`)}catch(g){return i("failed",`write: ${
|
|
1012
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=
|
|
1013
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return
|
|
1014
|
-
`),2;if(n.hooksOnly)return
|
|
1032
|
+
[Y/n]: `))return i("skipped","user declined","skip")}let p=Gn(a.hooks)?a.hooks:{},f=Array.isArray(p[t.event])?p[t.event]:[],m={...a,version:a.version??Ou,hooks:{...p,[t.event]:[...f,{command:d,timeout:t.timeout}]}};if(e.dryRun)return i(c?"would-create":"would-merge",n,c?"write":"merge");try{await V(n,JSON.stringify(m,null,2)+`
|
|
1033
|
+
`)}catch(g){return i("failed",`write: ${Du(g)}`)}return i(c?"created":"merged",n,c?"write":"merge")}s(JP,"mergeCursorHook");async function Mu(e){if(!e.explicit&&!e.skip&&!hb(e.presence.ctx,e.presence.probe)){let n=Pn(e.presence.ctx).skipDetail;return vw.map(r=>({target:Sw(r),action:"skip",status:"skipped",detail:n}))}let t=[];for(let n of vw)t.push(await JP(e,n));return t}s(Mu,"mergeCursorHooks");async function YP(e,t){e.write(t);let n=kw.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}s(YP,"promptYesNo");function Du(e){return e instanceof Error?e.message:String(e)}s(Du,"errMessage");ie();async function xw(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),o={};try{o=await i.json()}catch{}return i.ok?o.status!=="exchanged"||typeof o.api_key!="string"||!o.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:o.api_key,plan:o.plan??"unknown"}:{ok:!1,reason:o.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}s(xw,"exchangeOneClickToken");async function Rw(e){let t="browser-pair";if(e.token!==null)try{let o=XP(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(Bi(),On(o),{apiKey:o,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(o){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:Ew(o)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let o=Ps(e.bridgeVersion),a=await xw({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:j_(),clientMeta:{...o}});if(a.ok)return Bi(),On(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,Tw(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
|
|
1034
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=z();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let o=await Ir(e.bridgeVersion,Tw(e));return o===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:o.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${o.plan})${r}`}}}catch(o){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:Ew(o)}}}}s(Rw,"pairOrUseToken");function XP(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}s(XP,"validateTokenShape");function Ew(e){return e instanceof Error?e.message:String(e)}s(Ew,"errMessage");function Tw(e){return e.out??process.stdout}s(Tw,"out");Cr();var ZP="install-completed",QP=3e3;async function Aw(e){if(!e.enabled||e.apiKey===null)return;let t=Ar(ZP),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:tM(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:eM(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),QP);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(i)}}s(Aw,"postInstallTelemetry");function eM(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}s(eM,"countStatuses");function tM(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(tM,"parseNodeMajor");Qt();La();he();var L$="https://mcp.maind.dev/mcp";async function Jv(e){let t=Date.now(),n;try{n=sb(e)}catch(k){if(k instanceof Fe)return process.stderr.write(`error: ${k.message}
|
|
1035
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return ab(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=qv.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
1036
|
+
`),2;if(n.hooksOnly)return F$({homeDir:o,isInteractive:i,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:Vi({projectRoot:o,homeDir:o,platform:process.platform,env:process.env}),probe:Wt});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let k=await Us(process.cwd());if(k.length===0)a=await db(process.cwd());else if(k.length===1)a=k[0];else{let E=await pb(k,i);if(E===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
|
|
1015
1037
|
`);for(let P of k)process.stderr.write(` candidate: ${P}
|
|
1016
|
-
`);return 2}a=E}}let c=new
|
|
1038
|
+
`);return 2}a=E}}let c=new zi,l=(process.env.MAIND_MCP_URL??"").trim()||L$;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
1017
1039
|
`),process.stdout.write(`maind install \u2014 project root: ${a}
|
|
1018
1040
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
1019
1041
|
|
|
1020
|
-
`);let d=
|
|
1042
|
+
`);let d=Vi({projectRoot:a,homeDir:o,platform:process.platform,env:process.env,bridgeEntry:ge()}),u=Wi(d);if(u=ib(u,n.client),n.skipCodex&&(u=u.filter(k=>k.key!=="codex-cli")),u.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
|
|
1021
1043
|
`:`error: no client targets selected (did you skip all of them?)
|
|
1022
|
-
`),c.print(process.stdout),2;let p=await
|
|
1044
|
+
`),c.print(process.stdout),2;let p=await Rw({bridgeVersion:U,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(p.result),p.result.status==="failed")return process.stderr.write(`
|
|
1023
1045
|
pairing failed: ${p.result.detail??"unknown"}
|
|
1024
1046
|
Skipping remaining steps.
|
|
1025
|
-
`),c.print(process.stdout),2;let f=new Set;for(let k of u){let E=
|
|
1026
|
-
DRY RUN finished in ${
|
|
1047
|
+
`),c.print(process.stdout),2;let f=new Set;for(let k of u){let E=gb({target:k,explicitFamily:n.client,probe:Wt});if(E!==null){c.add(E);continue}f.add(k.clientFamilyEnv);let P=q_({mcpUrl:l,clientFamily:k.clientFamilyEnv}),S;k.kind==="json"?S=await wb(k,P,n.dryRun):S=await vb(k,P,n.dryRun),c.add(S)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let k=[...f].find(P=>Jr(P))??null,E=await Rb({projectRoot:a,homeDir:o,...k!==null?{conventions:s(()=>$a(p.apiKey,Le(a),{allowFetch:!n.dryRun,clientFamily:k}),"conventions")}:{}},n.dryRun);for(let P of E)c.add(P);k===null&&c.add({target:Mr,action:"upsert",status:"skipped",detail:"conventions block: skipped (no selected client uses the AGENTS.md block \u2014 Codex, Cursor, Devin Desktop, Copilot)"})}let m={homeDir:o,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},g=await ou(m);for(let k of g)c.add(k);n.dryRun||await tu(at,g);let y=ww(a,g);if(y!==null&&c.add(y),c.add(await Nu({isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout})),c.add(await Db({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout})),u.some(k=>k.clientFamilyEnv==="cursor")){let k=await Mu({...m,explicit:n.client==="cursor",presence:{ctx:d,probe:Wt}});for(let E of k)c.add(E)}let _=Ea();_.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${_.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await Aw({enabled:n.telemetry||n.full,installerVersion:U,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let b=c.exitCode(),v=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
1048
|
+
DRY RUN finished in ${v}s. No files were modified. Re-run without --dry-run to apply.
|
|
1027
1049
|
`):process.stdout.write(`
|
|
1028
|
-
Finished in ${
|
|
1029
|
-
`);let
|
|
1050
|
+
Finished in ${v}s. Restart your MCP client so it picks up the new server entry.
|
|
1051
|
+
`);let x=xe({entryPath:ge(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),C=x.fallbackReason===null?`${it(x)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${C}
|
|
1030
1052
|
`),b===1&&process.stdout.write(`Note: some steps were skipped or failed \u2014 review the table above. The MCP setup is usable as long as 'browser-pair' and at least one JSON/TOML target succeeded.
|
|
1031
|
-
`),b}s(
|
|
1053
|
+
`),b}s(Jv,"runInstall");async function F$(e,t){let n=new zi;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
1032
1054
|
`),e.out.write(`maind install --hooks-only \u2014 Claude Code hooks in ~/.claude/settings.json, and Cursor's in ~/.cursor/hooks.json where Cursor is installed
|
|
1033
|
-
`);let r=await
|
|
1055
|
+
`);let r=await ou(e);for(let i of r)n.add(i);e.dryRun||await tu(at,r),n.add(await Nu({isInteractive:e.isInteractive,full:e.full,skip:e.skip,dryRun:e.dryRun,out:e.out}));for(let i of await Mu({...e,explicit:!1,presence:t}))n.add(i);return n.print(e.out),e.out.write(e.dryRun?`
|
|
1034
1056
|
DRY RUN finished. No files were modified.
|
|
1035
1057
|
`:`
|
|
1036
1058
|
Claude Code reads hooks when a session starts; Cursor reloads ~/.cursor/hooks.json by itself.
|
|
1037
|
-
`),n.exitCode()}s(
|
|
1038
|
-
`,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(
|
|
1039
|
-
${JSON.stringify(t)}`).digest("hex")}s(UP,"payloadKey");function Ye(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(Ye,"fail");var zn="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function tw(e){let t=vd(e);if(t!==null&&wd(t))return Ye("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 Ye("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 Ye("cloud_unavailable",`review_verdict failed: ${xa(t?.detail??e)||"no detail"}`,zn)}s(tw,"fromProtocolText");function BP(e,t,n){switch(e.kind){case"no_session":return Ye("cloud_unavailable","no MCP session with the MAIND server \u2014 the client never completed its handshake through this bridge.",`Retry once the MAIND cloud tools respond. ${zn}`);case"transport_error":return e.timedOut?Ye("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."):Ye("cloud_unavailable",`network error: ${e.message}`,zn);case"http_error":return e.status===401?Ye("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${xa(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?Ye("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."):Ye("cloud_unavailable",`HTTP ${e.status}: ${xa(e.body)}`,zn);case"rpc_error":return tw(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return tw(e.text);let r;try{r=JSON.parse(e.text)}catch{return Ye("cloud_unavailable",`review_verdict returned non-JSON text: ${xa(e.text)}`,zn)}return typeof r!="object"||r===null?Ye("cloud_unavailable","review_verdict returned no object",zn):{kind:"verdict",body:r}}}}s(BP,"interpretOutcome");var GP="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).",KP={dirty:"commit (or stash) your changes \u2014 a dirty worktree cannot be recomputed",base_kind_not_ref:"pass `since` \u2014 only a committed range is replayable",base_sha_missing:"pass `since` \u2014 only a committed range is replayable",stale_files:"the index was stale for changed files \u2014 run codebase_index, then call again",truncated:"more than 1000 changed symbols, or labels beyond the schema \u2014 split the change",hunk_coverage_not_full:"some changes could not be line-graded (binary or unusual diffs)",detector_coverage_not_full:"a repo-health detector could not run \u2014 see local.detectors",merge_base_missing:"no merge-base with `since` (shallow clone?) \u2014 fetch the full history",private_citation:"a finding cites a private convention \u2014 not verifiable by others"},nw=s(e=>e.map(t=>KP[t]??t).join("; "),"adviceFor");function WP(e,t){switch(e){case"no_report":return"persist: false \u2014 verdict only, nothing recorded.";case"no_head":return"no HEAD commit \u2014 there is nothing a record could be anchored to.";case"no_project_key":return"no origin remote, so no project_key to file a record under \u2014 the verdict is computed but not recorded.";case"no_merge_base":return"no merge-base between HEAD and `since` (shallow clone?) \u2014 the verdict is computed but not recorded; fetch the full history.";case"no_base":return"uncommitted work is judged but never recorded. Commit and push, then call again with `since` = the branch's base (e.g. origin/master).";case"dirty_tree":return"the worktree has uncommitted or untracked changes \u2014 a record attests a commit, and a dirty tree cannot be recomputed. Commit (or stash) them, then call again.";case"not_grade_eligible":return`this run could not be attestation-grade (${(t??[]).join(", ")}), and only replayable runs are recorded. To fix: ${nw(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,i]=t??[];return`the reviewed range starts at ${Qv(n)}, but this branch forks off ${i??"the default branch"} at ${Qv(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${i??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}s(WP,"skipText");function VP(e,t,n,r){if(e.persisted){if(t===!0)return`Recorded as attestation-grade run ${e.run_id} (format 3). Recompute it: \`maind verify ${e.run_id}\``+(r?` \u2014 a teammate: \`maind verify --commit ${r}\`.`:".");let c=nw(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",o=WP(i,e.detail),a=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return o!==null?`Not recorded: ${o}${a}`:`Not recorded (${i||"the server gave no reason"}).${a}`}s(VP,"recordHint");async function rw(e,t,n){let r=n.repoRoot??Se(),i=r,o=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let ne=Ur(c,r);if(ne===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(c)} could not be located \u2014 no repository was reviewed, nothing was sent.`,hint:"Pass a path that exists relative to the workspace (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};if(!OP(ne.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};i=ne.repoRoot,o=n.engineFor(i),a=n.projectKeyFor?.(i)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,d=l!==void 0&&t.include_uncommitted===!0,u=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??PP,m=[],g=await MP(o,i,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await o.reviewChanges(gd(l,d)),_={repo_root:i,since:l??null,include_uncommitted:l===void 0?!0:d,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if($P(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:_,warnings:m};let b;try{b=await o.reviewDetectorScopes({baseRef:l})}catch(ne){let sf=Oe(vt(`reviewDetectorScopes failed: ${_u(ne)}`));b={commit:sf,local:sf},m.push(`repo-health detectors unavailable (${_u(ne)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:w,dropped:S}=yd(y,b.commit);S>0&&m.push(`${S} symbol(s) exceed the server schema (name > ${ws} or qualified name > ${ks} chars) and were left out \u2014 this run is not attestation-grade.`);let A=UP(a,w),k=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",E=jP({persistWanted:u,since:l,projectKey:a,result:y,payload:w,git:k?(n.persistFacts??HP)(i,y.headSha):null,recordedRunId:f.get(A)??null}),P={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:w.changed_symbols.length,symbols_dropped:S,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,Zv),local_only:LP(b).slice(0,Zv)}},x=await n.callCloudTool("review_verdict",{attest:w,persist:E.persist,...a?{project_key:a}:{}},{timeoutMs:p}),N=BP(x,p,E.persist);if(N.kind==="error")return{ok:!1,error:N.error,message:N.message,hint:N.hint,base:_,local:P,warnings:m};let D=N.body;if(D.ok!==!0){let ne=D.error==="requires_team"||D.error==="requires_enterprise";return{ok:!1,error:D.error??"unknown_error",message:D.message??"review_verdict returned no message",hint:ne?GP:D.hint??zn,base:_,local:P,warnings:m}}if(D.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 j=D.attest,W=D.run??null,pt=W&&typeof W.id=="string"?{persisted:!0,run_id:W.id,commit_sha:W.commit_sha??null,attestation_format:W.attestation_format??null}:{persisted:!1,reason:E.skipped??D.run_note??"not_persisted",...E.detail?{detail:E.detail}:{}};pt.persisted&&f.set(A,W.id);let To=typeof j?.attestation_grade=="boolean"?j.attestation_grade:null,oi=Array.isArray(j?.grade_blockers)?j.grade_blockers:[],q=D.counts??{},Fe=Array.isArray(D.findings)?D.findings:[],Ro=`Verdict ${D.verdict??"?"}: ${q.block??0} block, ${q.warn??0} warn, ${q.note??0} note`+(D.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:D.verdict??null,counts:q,record:pt,attest:j?{attestation_grade:To,grade_blockers:oi,attestation_format:j.attestation_format??null,input_hash:j.input_hash??null,policy_hash:j.policy_hash??null,evaluated_convention_count:j.evaluated_convention_count??null,detector_coverage:j.detector_coverage??null}:null,hint:`${Ro} ${VP(pt,To,oi,y.headSha)}`,findings:Fe.slice(0,yu).map(ne=>({convention_id:ne.convention_id,convention_version:ne.convention_version,severity:ne.severity,action:ne.action,...ne.downgrade_reason?{downgrade_reason:ne.downgrade_reason}:{},summary:ne.summary,matched_changed_symbols:(ne.matched_changed_symbols??[]).slice(0,DP),matched_symbol_count:ne.matched_symbols?.length??0})),...Fe.length>yu?{findings_not_shown:Fe.length-yu}:{},detector_findings:D.detector_findings??[],policy_source:D.policy_source??null,coverage_note:bd(y,j?.evaluated_convention_count,S),base:_,local:P,warnings:m}}s(rw,"runAttestReview");var iw=(()=>{let e=Object.keys(Ti),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Sa(e){return zP("sha256").update(e,"utf8").digest("hex")}s(Sa,"nodeKeyHash");var qP=["module","class","interface","function","method","type_alias","enum","variable"],bu=[{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:qP,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. For TS/JS, CALLS follow the caller's imports (relative paths, tsconfig aliases, workspace packages, barrels) and include `new`, JSX and module-level code; a method call is linked only when the receiver's declared type or an importable class identifies it. Not modelled: non-call references (type annotations, a function passed as a value) and types inferred through other types \u2014 an empty 'in' is strong evidence, not proof. Python stays name-based.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the "+iw+" \u2014 ADR-324 \u2014 and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full counts as a complete check. This two-step gives an ADVISORY verdict and writes no record: diff_stats carries no commit anchors (MAIND-581). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located. For a gate verdict \u2014 and, for a clean pushed commit, a replayable attestation record \u2014 use attest_review_changes instead: one call, and the bridge sends the payload itself.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"attest_review_changes",description:"Gate verdict for your change in ONE call, computed by the MAIND server (ADR-357) \u2014 and, for a clean pushed commit, recorded as a replayable attestation. The bridge refreshes the local index, enumerates the diff (merge-base of `since` \u2192 HEAD), runs the "+iw+", builds the attest payload exactly like `maind review --gate`, and sends it to review_verdict itself \u2014 you copy no symbols and no commit hashes. The server matches ALL changed symbols (up to 1000) against its full visible code_review convention set and answers pass|warn|block with cited findings. A RECORD is written only when anyone with the commit can recompute it (`maind verify <run_id>`): `since` given, a clean worktree, HEAD pushed, the range starting where the branch forks off the default branch (so `since` = e.g. 'origin/master'), and nothing that keeps the run from being attestation-grade. Otherwise you still get the verdict, and `record.reason` names the step that leads to a record. THIS TOOL UPLOADS, unlike the codebase_* tools: symbol names and qualified names, kinds, languages, change grades and changed-line counts; closed-enum risk flags; detector ids, rule ids, levels and evidence HASHES; file counts; commit hashes; this repo's project_key hash. Never paths, source, detector titles or reasons. Call this WHEN: (a) your work is committed and pushed and you are about to open or update a PR \u2014 pass `since` = the branch's base (e.g. 'origin/master'); (b) a reviewer or CI needs a verdict with provenance, not an advisory list; (c) you want to see how uncommitted work fares against the gate \u2014 omit `since` (judged, never recorded). To iterate on local edits, codebase_review_changes is cheaper and uploads nothing. review_verdict is a Team-plan feature. Read `verdict` and `record` first; `ok: false` always carries an `error` code and a `hint`.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref the change is based on (e.g. 'origin/master', a SHA). Reviewed range: merge-base(since, HEAD) \u2192 HEAD. A record is written only when this range starts where the branch forks off the default branch. Omit to judge your uncommitted work against HEAD (never recorded)."},include_uncommitted:{type:"boolean",description:"With `since`: also include uncommitted changes \u2014 judged, never recorded (a dirty worktree cannot be recomputed). Default false; ignored without `since`."},persist:{type:"boolean",description:"Record the run when it is replayable (default true). false = verdict only, nothing written."},dir:{type:"string",description:`A path inside the repository to review (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 e.g. "Asgard/Maind". The record is filed under THAT repository's origin remote. Omit for the workspace repo. A path that cannot be located answers dir_not_found \u2014 nothing is sent.`}}},annotations:{title:"Attested review verdict",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],vu=new Map([["codebase_review_verdict","attest_review_changes"]]),aw=new Set([...bu.map(e=>e.name),...vu.keys()]),wu=new Set(["attest_review_changes",...[...vu].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function cw(e,t,n,r){if(!wu.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let i=await rw(e,n,r),o=vu.get(t);return o?{...i,renamed:{from:t,to:o,note:`${t} is ${o} since bridge 0.79.0 \u2014 call ${o}; the old name goes in a later minor.`}}:i}s(cw,"dispatchCloudBackedTool");function de(e){return typeof e=="string"&&e.length>0?e:void 0}s(de,"str");function qn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(qn,"num");function ow(e){if(e===void 0)return{repoRoot:Se(),scanDirs:void 0};let t=Ur(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(ow,"anchorRepo");function sw(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(sw,"dirNotFound");async function lw(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=de(n.for_path);if(i!==void 0){let u=iv(i);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await xn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,m=s(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(o!==void 0&&o.length>0){let u=new Map,p=[];for(let S of o){let A=Ur(S);if(A===null){p.push(S);continue}let k=u.get(A.repoRoot)??new Set;k.add(A.repoRelDir),u.set(A.repoRoot,k)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],m=[],g=[],y=[];for(let[S,A]of u){let k=[...A],E=k.includes(""),P=await kn(S,{dirs:E?void 0:k,minFiles:r});f.push({repo_root:S,dirs:E?null:k}),m.push(...P.findings),g.push(...P.facts.namespaces.map(x=>({repo_root:S,dir:x.dir,prefix:x.prefix,file_count:x.fileCount}))),y.push(...P.facts.skipped)}let _=m.filter(S=>S.status==="open"),b=m.filter(S=>S.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=Se(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:de(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=de(n.dir),i,o;if(r!==void 0){let u=Ur(r);if(u===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=u.repoRoot,o=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=Se(),o=void 0;let a=Tn(i,{dirs:o,baseRef:de(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=ow(de(n.dir));if(r===null)return sw("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=En(r.repoRoot,{dirs:r.scanDirs,baseRef:de(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=ow(de(n.dir));if(r===null)return sw("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=dd(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:de(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=de(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:de(n.kind),limit:qn(n.limit)})).map(o=>({...o,nodeKeyHash:Sa(o.nodeKey)}))}case"codebase_trace":{let r=de(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:qn(n.max_depth),limit:qn(n.limit)})}case"codebase_snippet":{let r=de(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:Sa(r)}}case"codebase_map":return e.getArchitecture({topN:qn(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:de(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:qn(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:Sa(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:de(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:qn(n.limit)}),i;if(n.include_history!==!1)try{i=Jc(await e.fileHistory({since:de(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:de(n.since)})}catch(l){o=Oe(vt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Sa(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:de(n.since),limit:qn(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(lw,"dispatchLocalTool");var Ea=class{constructor(t=sv,n=null,r=Se,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return bu}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&aw.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=wu.has(i)?await cw(this.getEngine(),i,o,this.ctx??void 0):await lw(this.getEngine(),i,o),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=nv(a)?`${rv} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Wv(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Ar();var JP="/mcp-client-metrics-ingest",YP=4e3,XP="codebase_search_tokens_saved";async function dw(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Fi()}${JP}`,n=new AbortController,r=setTimeout(()=>n.abort(),YP);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:XP,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
|
|
1040
|
-
`),!1}finally{clearTimeout(r)}}s(
|
|
1041
|
-
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,
|
|
1042
|
-
`),process.exit(1)),
|
|
1043
|
-
`),process.exit(1)),
|
|
1044
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
1045
|
-
`),process.exit(0));let t=
|
|
1046
|
-
`),n=await
|
|
1047
|
-
`))}s(
|
|
1048
|
-
`),process.exit(1)});function
|
|
1059
|
+
`),n.exitCode()}s(F$,"runHooksOnly");Qt();Qt();import{readFileSync as j$}from"node:fs";import{join as Yv}from"node:path";function Fa(e){return e?Math.ceil(e.length/4):0}s(Fa,"estimateTokens");var Xv=1e6,ja=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 Zv(e){try{let t=j$(e,"utf8");return t.length>Xv?t.slice(0,Xv):t}catch{return""}}s(Zv,"readFileCapped");function H$(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(H$,"distinctFilePaths");function Qv(e,t,n,r){try{let i=Fa(n);if(e==="codebase_search"){let o=H$(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=Fa(Zv(Yv(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let a=Fa(Zv(Yv(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Qv,"measureLocalToolSaved");Bt();Qt();import{createHash as aL}from"node:crypto";Bt();import{execFileSync as G$}from"node:child_process";import{createHash as W$}from"node:crypto";Qt();Qu();import{realpathSync as ok}from"node:fs";function V$(e,t){try{return ok(e)===ok(t)}catch{return e===t}}s(V$,"samePath");var ep=30,z$=10,sk=20,q$=new Map;function tp(e){return e instanceof Error?e.message:String(e)}s(tp,"msg");function Ua(e){let t=e.split(`
|
|
1060
|
+
`,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Ua,"firstLine");var ak=s(e=>e?e.slice(0,12):"?","short");async function J$(e,t,n,r){let i=await e.status(),o=!i.indexed||i.fileCount===0,a=await ik(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:tp(c)}}},n);return a.locked?a.value.ok?o?(r.push(`no local index found \u2014 built it now (${a.value.stats.filesParsed} file(s), ${Math.round(a.value.stats.durationMs/1e3)} s).`),{action:"built",files_parsed:a.value.stats.filesParsed,missing:!1}):{action:"refreshed",files_parsed:a.value.stats.filesParsed,missing:!1}:(o||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:o}):(o||r.push("another process holds the index lock (the Stop hook's refresh?) \u2014 reviewing with the existing index; stale files degrade to co_located and keep the run from being attestation-grade."),{action:"kept",note:"lock_busy",missing:o})}s(J$,"refreshIndex");function Y$(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(Y$,"isEmptyRange");function X$(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(X$,"localOnly");function Z$(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(Z$,"localGradeBlockers");function Q$(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=Nd(!1,e.projectKey,e.result);if(!t.persist)return t;let n=Z$(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(Q$,"bridgePersistDecision");function ck(e,t){try{return G$("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(ck,"git");function eL(e,t){let n=Ti(e),r=n&&ck(e,["merge-base",t,`origin/${n}`])||null,i=ck(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}s(eL,"gitPersistFacts");function tL(e,t){return W$("sha256").update(`${e??""}
|
|
1061
|
+
${JSON.stringify(t)}`).digest("hex")}s(tL,"payloadKey");function Ye(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(Ye,"fail");var Zn="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function lk(e){let t=Dd(e);if(t!==null&&Pd(t))return Ye("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 Ye("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 Ye("cloud_unavailable",`review_verdict failed: ${Ua(t?.detail??e)||"no detail"}`,Zn)}s(lk,"fromProtocolText");function nL(e,t,n){switch(e.kind){case"no_session":return Ye("cloud_unavailable","no MCP session with the MAIND server \u2014 the client never completed its handshake through this bridge.",`Retry once the MAIND cloud tools respond. ${Zn}`);case"transport_error":return e.timedOut?Ye("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."):Ye("cloud_unavailable",`network error: ${e.message}`,Zn);case"http_error":return e.status===401?Ye("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Ua(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?Ye("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."):Ye("cloud_unavailable",`HTTP ${e.status}: ${Ua(e.body)}`,Zn);case"rpc_error":return lk(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return lk(e.text);let r;try{r=JSON.parse(e.text)}catch{return Ye("cloud_unavailable",`review_verdict returned non-JSON text: ${Ua(e.text)}`,Zn)}return typeof r!="object"||r===null?Ye("cloud_unavailable","review_verdict returned no object",Zn):{kind:"verdict",body:r}}}}s(nL,"interpretOutcome");var rL="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).",iL={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"},dk=s(e=>e.map(t=>iL[t]??t).join("; "),"adviceFor");function oL(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: ${dk(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,i]=t??[];return`the reviewed range starts at ${ak(n)}, but this branch forks off ${i??"the default branch"} at ${ak(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${i??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}s(oL,"skipText");function sL(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=dk(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",o=oL(i,e.detail),a=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return o!==null?`Not recorded: ${o}${a}`:`Not recorded (${i||"the server gave no reason"}).${a}`}s(sL,"recordHint");async function uk(e,t,n){let r=n.repoRoot??Ee(),i=r,o=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let re=Gr(c,r);if(re===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(!V$(re.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};i=re.repoRoot,o=n.engineFor(i),a=n.projectKeyFor?.(i)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,d=l!==void 0&&t.include_uncommitted===!0,u=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??q$,m=[],g=await J$(o,i,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await o.reviewChanges(Cd(l,d)),_={repo_root:i,since:l??null,include_uncommitted:l===void 0?!0:d,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(Y$(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:_,warnings:m};let b;try{b=await o.reviewDetectorScopes({baseRef:l})}catch(re){let Nf=Me(bt(`reviewDetectorScopes failed: ${tp(re)}`));b={commit:Nf,local:Nf},m.push(`repo-health detectors unavailable (${tp(re)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:v,dropped:x}=Id(y,b.commit);x>0&&m.push(`${x} symbol(s) exceed the server schema (name > ${Ts} or qualified name > ${Rs} chars) and were left out \u2014 this run is not attestation-grade.`);let C=tL(a,v),k=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",E=Q$({persistWanted:u,since:l,projectKey:a,result:y,payload:v,git:k?(n.persistFacts??eL)(i,y.headSha):null,recordedRunId:f.get(C)??null}),P={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:v.changed_symbols.length,symbols_dropped:x,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,sk),local_only:X$(b).slice(0,sk)}},S=await n.callCloudTool("review_verdict",{attest:v,persist:E.persist,...a?{project_key:a}:{}},{timeoutMs:p}),N=nL(S,p,E.persist);if(N.kind==="error")return{ok:!1,error:N.error,message:N.message,hint:N.hint,base:_,local:P,warnings:m};let D=N.body;if(D.ok!==!0){let re=D.error==="requires_team"||D.error==="requires_enterprise";return{ok:!1,error:D.error??"unknown_error",message:D.message??"review_verdict returned no message",hint:re?rL:D.hint??Zn,base:_,local:P,warnings:m}}if(D.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 j=D.attest,W=D.run??null,ut=W&&typeof W.id=="string"?{persisted:!0,run_id:W.id,commit_sha:W.commit_sha??null,attestation_format:W.attestation_format??null}:{persisted:!1,reason:E.skipped??D.run_note??"not_persisted",...E.detail?{detail:E.detail}:{}};ut.persisted&&f.set(C,W.id);let No=typeof j?.attestation_grade=="boolean"?j.attestation_grade:null,di=Array.isArray(j?.grade_blockers)?j.grade_blockers:[],J=D.counts??{},He=Array.isArray(D.findings)?D.findings:[],Oo=`Verdict ${D.verdict??"?"}: ${J.block??0} block, ${J.warn??0} warn, ${J.note??0} note`+(D.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:D.verdict??null,counts:J,record:ut,attest:j?{attestation_grade:No,grade_blockers:di,attestation_format:j.attestation_format??null,input_hash:j.input_hash??null,policy_hash:j.policy_hash??null,evaluated_convention_count:j.evaluated_convention_count??null,detector_coverage:j.detector_coverage??null}:null,hint:`${Oo} ${sL(ut,No,di,y.headSha)}`,findings:He.slice(0,ep).map(re=>({convention_id:re.convention_id,convention_version:re.convention_version,severity:re.severity,action:re.action,...re.downgrade_reason?{downgrade_reason:re.downgrade_reason}:{},summary:re.summary,matched_changed_symbols:(re.matched_changed_symbols??[]).slice(0,z$),matched_symbol_count:re.matched_symbols?.length??0})),...He.length>ep?{findings_not_shown:He.length-ep}:{},detector_findings:D.detector_findings??[],policy_source:D.policy_source??null,coverage_note:Od(y,j?.evaluated_convention_count,x),base:_,local:P,warnings:m}}s(uk,"runAttestReview");var pk=(()=>{let e=Object.keys(Ni),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Ba(e){return aL("sha256").update(e,"utf8").digest("hex")}s(Ba,"nodeKeyHash");var cL=["module","class","interface","function","method","type_alias","enum","variable"],np=[{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:cL,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 "+pk+" \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 "+pk+", 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."}}}}],rp=new Map([["codebase_review_verdict","attest_review_changes"]]),hk=new Set([...np.map(e=>e.name),...rp.keys()]),ip=new Set(["attest_review_changes",...[...rp].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function gk(e,t,n,r){if(!ip.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let i=await uk(e,n,r),o=rp.get(t);return o?{...i,renamed:{from:t,to:o,note:`${t} is ${o} since bridge 0.79.0 \u2014 call ${o}; the old name goes in a later minor.`}}:i}s(gk,"dispatchCloudBackedTool");function de(e){return typeof e=="string"&&e.length>0?e:void 0}s(de,"str");function Qn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Qn,"num");function fk(e){if(e===void 0)return{repoRoot:Ee(),scanDirs:void 0};let t=Gr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(fk,"anchorRepo");function mk(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(mk,"dirNotFound");async function yk(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=de(n.for_path);if(i!==void 0){let u=hv(i);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Tn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,m=s(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(o!==void 0&&o.length>0){let u=new Map,p=[];for(let x of o){let C=Gr(x);if(C===null){p.push(x);continue}let k=u.get(C.repoRoot)??new Set;k.add(C.repoRelDir),u.set(C.repoRoot,k)}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[x,C]of u){let k=[...C],E=k.includes(""),P=await En(x,{dirs:E?void 0:k,minFiles:r});f.push({repo_root:x,dirs:E?null:k}),m.push(...P.findings),g.push(...P.facts.namespaces.map(S=>({repo_root:x,dir:S.dir,prefix:S.prefix,file_count:S.fileCount}))),y.push(...P.facts.skipped)}let _=m.filter(x=>x.status==="open"),b=m.filter(x=>x.status==="info"),v=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(x=>`${x.namespace.prefix}${x.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+v}}let a=Ee(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:de(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=de(n.dir),i,o;if(r!==void 0){let u=Gr(r);if(u===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=u.repoRoot,o=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=Ee(),o=void 0;let a=Cn(i,{dirs:o,baseRef:de(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=fk(de(n.dir));if(r===null)return mk("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=An(r.repoRoot,{dirs:r.scanDirs,baseRef:de(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=fk(de(n.dir));if(r===null)return mk("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Sd(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:de(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=de(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:de(n.kind),limit:Qn(n.limit)})).map(o=>({...o,nodeKeyHash:Ba(o.nodeKey)}))}case"codebase_trace":{let r=de(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Qn(n.max_depth),limit:Qn(n.limit)})}case"codebase_snippet":{let r=de(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:Ba(r)}}case"codebase_map":return e.getArchitecture({topN:Qn(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:de(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Qn(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:Ba(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:de(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Qn(n.limit)}),i;if(n.include_history!==!1)try{i=cl(await e.fileHistory({since:de(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:de(n.since)})}catch(l){o=Me(bt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Ba(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:de(n.since),limit:Qn(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(yk,"dispatchLocalTool");var Ka=class{constructor(t=yv,n=null,r=Ee,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return np}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&hk.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=ip.has(i)?await gk(this.getEngine(),i,o,this.ctx??void 0):await yk(this.getEngine(),i,o),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=fv(a)?`${mv} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Qv(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Cr();var lL="/mcp-client-metrics-ingest",dL=4e3,uL="codebase_search_tokens_saved";async function _k(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Ki()}${lL}`,n=new AbortController,r=setTimeout(()=>n.abort(),dL);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:uL,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
|
|
1062
|
+
`),!1}finally{clearTimeout(r)}}s(_k,"postSavingsMetric");ap();Wa();pi();he();import{existsSync as IL,readFileSync as NL,readdirSync as OL,statSync as DL}from"node:fs";import{dirname as PL,join as uo,resolve as lp}from"node:path";var ML=8,$L=128;function LL(e){return OL(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>t.name).sort()}s(LL,"defaultListDirs");function FL(e){let t=uo(e,".git");if(!IL(t))return null;if(DL(t).isDirectory())return{isDir:!0,gitdir:null};let n=/^gitdir:\s*(.+)\s*$/m.exec(NL(t,"utf8"));return{isDir:!1,gitdir:n?lp(e,n[1].trim()):null}}s(FL,"defaultGitKind");function jL(e){let t=`${uo(".git","worktrees")}`,n=e.lastIndexOf(t);return n>0?PL(uo(e.slice(0,n),".git")):null}s(jL,"mainCheckoutOf");function Ik(e,t,n={}){try{let r=n.listDirs??LL,i=n.gitKind??FL,o=n.keyOf??Le,a=r(e).slice(0,$L),c=new Set,l=new Map;for(let u of a)try{let p=i(uo(e,u));if(p===null)continue;l.set(u,p),p.isDir&&c.add(lp(e,u))}catch{}let d=new Map;for(let[u,p]of l){if(!p.isDir&&p.gitdir!==null){let g=jL(p.gitdir);if(g!==null&&c.has(lp(g)))continue}let f=null;try{f=o(uo(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,ML)}catch{return[]}}s(Ik,"discoverNestedRepos");vt();za();Kn();import{join as sF}from"node:path";var aF="<synthetic>";function Fk(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:sF(Au,Cu(e.cwd),`${e.transcript_stem}.jsonl`)}s(Fk,"transcriptPathFromSideChannel");var qa=class{constructor(t){this.deps=t}static{s(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??Ru)(n,{start:this.offset});for(let o of i.events)if(o.kind==="title"){let a=o.title.trim();a.length>0&&(this.title=a)}else o.kind==="assistant"&&!o.isSidechain&&typeof o.model=="string"&&o.model.length>0&&o.model!==aF&&(this.model=o.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as cF}from"node:child_process";var lF=8,dF=32;function uF(e){return e.split(`
|
|
1063
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,dF)}s(uF,"parsePorcelain");function pF(e,t=lF){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let o=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(o.length===0||n.includes(o))&&(n.push(o),n.length>=t))break}return n}s(pF,"condenseToDirs");async function jk(e=fF){let t=await e();if(t===null)return null;let n=pF(uF(t));return n.length>0?n:null}s(jk,"deriveWorkingPaths");async function fF(){return await new Promise(e=>{cF("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(fF,"defaultGitStatus");La();var zU=1,qU=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function JU(e){return qU.includes(e)}s(JU,"isHookSubcommand");var YU=6e4;async function XU(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==z()&&On(e),e;let t=z();if(t!==null)return t;let n=await Ir(U);return n===null&&(Dn("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:U}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
1064
|
+
`),process.exit(1)),Dn("paired",null,{version:U}),n.apiKey}s(XU,"ensureApiKey");async function ZU(e){let t=await Ir(U);return t===null&&(Dn("auth_failed",`${e}; re-authorization did not complete`,{version:U}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
1065
|
+
`),process.exit(1)),Dn("paired",null,{version:U}),t.apiKey}s(ZU,"reauth");async function QU(){let e=process.argv.slice(2).find(S=>!S.startsWith("-"));if(e==="install"){let S=process.argv.indexOf("install"),N=process.argv.slice(S+1),D=await Jv(N);process.exit(D)}if(e==="doctor"){let{runDoctor:S}=await Promise.resolve().then(()=>(bp(),nS));process.exit(await S(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:S}=await Promise.resolve().then(()=>(Ax(),Rx));process.exit(await S())}if(e==="session-end-run"){let{runSessionEndWorker:S}=await Promise.resolve().then(()=>(nf(),kx));process.exit(await S())}if(e==="on-session-briefing"){let{runOnSessionBriefing:S}=await Promise.resolve().then(()=>(Ix(),Cx));process.exit(await S())}if(e==="on-session-reminder"){let{runOnSessionReminder:S}=await Promise.resolve().then(()=>(Dx(),Ox));process.exit(await S())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:S}=await Promise.resolve().then(()=>(Bx(),Ux));process.exit(await S())}if(e==="guard"){let S=process.argv.indexOf("guard"),{runGuard:N}=await Promise.resolve().then(()=>(qx(),zx));process.exit(await N(process.argv.slice(S+1)))}if(e==="guard-inject"){let{runGuardInject:S}=await Promise.resolve().then(()=>(Xn(),$v));process.exit(await S())}if(e==="guard-gate"){let{runGuardGate:S}=await Promise.resolve().then(()=>(nE(),tE));process.exit(await S())}if(e==="guard-stop"){let{runGuardStop:S}=await Promise.resolve().then(()=>(oE(),iE));process.exit(await S())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:S}=await Promise.resolve().then(()=>(af(),Xx));process.exit(await S())}if(e==="guard-capture"){let{runGuardCapture:S}=await Promise.resolve().then(()=>(lE(),cE));process.exit(await S())}if(e==="gateway"){let S=process.argv.indexOf("gateway"),{runGateway:N}=await Promise.resolve().then(()=>(zE(),VE));process.exit(await N(process.argv.slice(S+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:S}=await Promise.resolve().then(()=>(vf(),wf));process.exit(await S())}if(e==="guard-cross-check"){let{runGuardCrossCheck:S}=await Promise.resolve().then(()=>(vf(),wf));process.exit(await S())}if(e==="on-index-refresh"){let{runOnIndexRefresh:S}=await Promise.resolve().then(()=>(Sf(),kf));process.exit(await S())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:S}=await Promise.resolve().then(()=>(Sf(),kf));process.exit(await S())}if(e==="on-prompt-context"){let{runOnPromptContext:S}=await Promise.resolve().then(()=>(If(),Cf));process.exit(await S())}if(e==="on-read-context"){let{runOnReadContext:S}=await Promise.resolve().then(()=>(If(),Cf));process.exit(await S())}if(e!==void 0&&JU(e)){let S=await Promise.resolve().then(()=>(ac(),WS)),N={"on-session-start":S.runOnSessionStart,"on-tool-use":S.runOnToolUse,"on-file-write":S.runOnFileWrite,"on-file-edit":S.runOnFileEdit,"on-repo-health":S.runOnRepoHealth,"on-write-health":S.runOnWriteHealth,"sync-config":S.runSyncConfig,flush:S.runFlush,status:S.runHookStatus}[e];process.exit(await N())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(U+`
|
|
1066
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(eB(),process.exit(0)),process.argv.includes("--reauth")&&(Bi(),await Ir(U,process.stdout)===null&&process.exit(1),Dn("paired",null,{version:U}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
1067
|
+
`),process.exit(0));let t=ne(),n=await XU(),r=te(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new ja:null,a=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Ka(void 0,o,void 0,{callCloudTool:s((S,N,D)=>a===null?Promise.resolve({kind:"no_session"}):a.callCloudTool(S,N,D),"callCloudTool"),projectKey:r,engineFor:s(S=>{let N=c.get(S);return N===void 0&&(N=_v(S),c.set(S,N)),N},"engineFor"),projectKeyFor:Le}),d=`bridge-${VU()}`,u=s(async()=>{if(!o)return;let S=o.takePending();S.tokens<=0||await _k({apiKey:n,deviceId:t,sessionId:d,tokensSaved:S.tokens,bridgeVersion:U})},"flushSavings"),p=o?setInterval(()=>{u()},YU):null;p?.unref();let f=new Va({projectKey:r}),m=new qa({resolvePath:s(()=>Fk(f.sideChannel()),"resolvePath"),fallbackModel:s(()=>f.sideChannel()?.model??null,"fallbackModel")}),g=new Do,y=null,_=s(()=>(y===null&&(y=r!==null?Ik(We(),r):[]),y),"nestedRepos"),b=s(S=>_().find(N=>N.projectKey===S)?.dir??null,"nestedDirOf"),v=new Ga({projectKey:r,identity:f,sessionMeta:s(()=>m.read(),"sessionMeta"),postToolCall:s((S,N)=>a===null?Promise.reject(new Error("presence: no active forwarder")):a.postPresenceToolCall(S,N),"postToolCall"),deriveWorkingPaths:s(()=>jk(),"deriveWorkingPaths"),snapshot:r!==null?tB(Ck({projectKey:r}),g,b):void 0,nestedProjectKeys:s(()=>_().map(S=>S.projectKey),"nestedProjectKeys")}),x=v.isEnabled?setInterval(()=>{v.pollActivity()},vk):null;if(x?.unref(),v.isEnabled){let S=s(N=>{v.end().finally(()=>process.exit(N))},"endAndExit");process.on("SIGTERM",()=>S(143)),process.on("SIGINT",()=>S(130))}let C=!1,k=s(S=>{if(C||!Jr(S))return;C=!0,setTimeout(()=>{Promise.resolve().then(()=>(La(),zv)).then(({refreshAgentsMdForSession:D})=>D(S,{apiKey:n,projectKey:r,listRoots:s(()=>a?.listClientRoots()??Promise.resolve(null),"listRoots")})).catch(()=>{})},0).unref()},"scheduleAgentsMdRefresh"),E=0,P=Fd();try{for(;;){let S=a?.carryOver()??null,N=new Os({apiKey:n,deviceId:t,bridgeVersion:U,projectKey:r,localRouter:l,presence:v,onConnectionOutcome:s((D,j)=>Dn(D,j,{version:U}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:D})=>k(D),"onSessionReady"),assignedInbox:g,carry:S});a=N;try{await N.run(P);return}catch(D){if(D instanceof Ui&&E<zU){E+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${D.message}; re-authorizing\u2026
|
|
1068
|
+
`),n=await ZU(D.reason);continue}throw D}}}finally{p&&clearInterval(p),x&&clearInterval(x),await v.end(),await u()}}s(QU,"main");function eB(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge doctor # offline self-diagnosis with fix commands (--json)"," npx -y @maind-dev/mcp-bridge doctor --remove-phantoms [--yes]"," # list (then remove) maind entries of clients that are not installed"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-reminder add ~/.claude/maind-session-start-reminder.md at session start (replaces `cat`; MAIND-630)"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-session-briefing add the session briefing + project conventions at session start (MAIND-620, never blocks)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end 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)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_NO_AGENTS_MD_REFRESH Set to 1 to stop refreshing the conventions block in AGENTS.md (Codex, Cursor, Windsurf, Copilot; ADR-359 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," MAIND_DEVIN_HOOK_OUTPUT 'off' keeps every hook silent when Devin Local runs it (default on; or",' "devin_hook_output": false in config.json \u2014 MAIND-630, unmeasured there)'," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
|
|
1069
|
+
`))}s(eB,"printHelp");QU().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
1070
|
+
`),process.exit(1)});function tB(e,t,n){return{...e,write(r,i){let o=r;try{o=Lf(r,n)}catch{o=r}try{t.update(o)}catch{}e.write(o,i)}}}s(tB,"withAssignedCapture");
|