@maind-dev/mcp-bridge 0.83.0 → 0.85.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 +73 -0
- package/build/index.js +404 -391
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,43 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var qd=Object.defineProperty;var a=(e,t)=>qd(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var ne=(e,t)=>{for(var n in t)qd(e,n,{get:t[n],enumerable:!0})};function Jd(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let o=n.params;if(typeof o=="object"&&o!==null){let c=o.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function bn(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function Io(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function No(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Co(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Oo=_(()=>{"use strict";a(Jd,"parseFrame");a(bn,"denyResult");a(Io,"toolEvent");a(No,"policyEvent");a(Co,"shaEvent")});import{execFileSync as Qd}from"node:child_process";function eu(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=Mv}function Lv(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let s of Ov){let o=r[s];typeof o=="string"&&Xd.test(o)&&i.push({field:s,sha:o})}for(let[s,o]of Dv){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[o];typeof l=="string"&&Xd.test(l)&&i.push({field:`${s}.${o}`,sha:l})}return i}function $v(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,Zd);for(let i=Zd;i>=Pv;i--){let s=r.slice(0,i),o=t(s);if(o!==null&&o.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:o,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function wn(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 tu(){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 ki(e=process.cwd()){try{let n=Qd("git",["rev-parse","--show-toplevel"],{cwd:e,env:tu(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function Fv(e){return t=>{try{let r=Qd("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:tu(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function xi(e,t){if(t===null)return[];let n=Lv(e);if(n.length===0)return[];let r=Fv(t),i=[];for(let{field:s,sha:o}of n){let c=$v(o,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var Ov,Dv,Xd,Pv,Zd,Mv,Do=_(()=>{"use strict";Ov=["commit_sha","base_sha","head_sha"],Dv=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Xd=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,Pv=7,Zd=12,Mv=10;a(eu,"isDenyGrade");a(Lv,"extractShaArgs");a($v,"classifySha");a(wn,"shaFindingText");a(tu,"cleanGitEnv");a(ki,"resolveRepoRootForSha");a(Fv,"gitShaResolver");a(xi,"inspectLineForShas")});var ru=_(()=>{"use strict"});var L,Mo,T,Re,yr=_(()=>{(function(e){e.assertEqual=i=>{};function t(i){}a(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}a(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),o={};for(let c of s)o[c]=i[c];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}a(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Mo||(Mo={}));T=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=a(e=>{switch(typeof e){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(e)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(e)?T.array:e===null?T.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?T.promise:typeof Map<"u"&&e instanceof Map?T.map:typeof Set<"u"&&e instanceof Set?T.set:typeof Date<"u"&&e instanceof Date?T.date:T.object;default:return T.unknown}},"getParsedType")});var x,jv,ue,Si=_(()=>{yr();x=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),jv=a(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ue=class e extends Error{static{a(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},i=a(s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let c=r,l=0;for(;l<o.path.length;){let d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ue.create=e=>new ue(e)});var Uv,He,Lo=_(()=>{Si();yr();Uv=a((e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===T.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,L.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.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 x.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 x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},"errorMap"),He=Uv});function Hv(e){iu=e}function vn(){return iu}var iu,Ei=_(()=>{Lo();iu=He;a(Hv,"setErrorMap");a(vn,"getErrorMap")});function E(e,t){let n=vn(),r=_r({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===He?void 0:He].filter(i=>!!i)});e.common.issues.push(r)}var _r,Gv,X,C,Et,re,Ti,Ai,ct,kn,$o=_(()=>{Ei();Lo();_r=a(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(o,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),Gv=[];a(E,"addIssueToContext");X=class e{static{a(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 C;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let s=await i.key,o=await i.value;r.push({key:s,value:o})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return C;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:t.value,value:r}}},C=Object.freeze({status:"aborted"}),Et=a(e=>({status:"dirty",value:e}),"DIRTY"),re=a(e=>({status:"valid",value:e}),"OK"),Ti=a(e=>e.status==="aborted","isAborted"),Ai=a(e=>e.status==="dirty","isDirty"),ct=a(e=>e.status==="valid","isValid"),kn=a(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var su=_(()=>{});var I,ou=_(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}))});function P(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:a((o,c)=>{let{message:l}=e;return o.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function du(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 sk(e){return new RegExp(`^${du(e)}$`)}function uu(e){let t=`${lu}T${du(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 ok(e,t){return!!((t==="v4"||!t)&&Zv.test(e)||(t==="v6"||!t)&&ek.test(e))}function ak(e,t){if(!qv.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 ck(e,t){return!!((t==="v4"||!t)&&Qv.test(e)||(t==="v6"||!t)&&tk.test(e))}function lk(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function xn(e){if(e instanceof pe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ge.create(xn(r))}return new pe({...e._def,shape:a(()=>t,"shape")})}else return e instanceof We?new We({...e._def,type:xn(e.element)}):e instanceof ge?ge.create(xn(e.unwrap())):e instanceof Ne?Ne.create(xn(e.unwrap())):e instanceof Ie?Ie.create(e.items.map(t=>xn(t))):e}function jo(e,t){let n=Re(e),r=Re(t);if(e===t)return{valid:!0,data:e};if(n===T.object&&r===T.object){let i=L.objectKeys(t),s=L.objectKeys(e).filter(c=>i.indexOf(c)!==-1),o={...e,...t};for(let c of s){let l=jo(e[c],t[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(n===T.array&&r===T.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],c=t[s],l=jo(o,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===T.date&&r===T.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function pu(e,t){return new Lt({values:e,typeName:O.ZodEnum,...P(t)})}function cu(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function fu(e,t={},n){return e?dt.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(o=>{if(!o){let c=cu(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let o=cu(t,r),c=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:c})}}):dt.create()}var ye,au,M,Bv,Wv,Kv,Vv,zv,qv,Yv,Jv,Xv,Fo,Zv,Qv,ek,tk,nk,rk,lu,ik,lt,Tt,At,Rt,It,Sn,Nt,Ct,dt,Be,ve,En,We,pe,Ot,Ge,Ri,Dt,Ie,Ii,Tn,An,Ni,Pt,Mt,Lt,$t,ut,_e,ge,Ne,Ft,jt,Rn,dk,br,wr,Ut,uk,O,pk,mu,hu,fk,mk,gu,hk,gk,yk,_k,bk,wk,vk,kk,xk,Sk,Ek,Tk,Ak,Rk,Ik,Nk,Ck,Ok,Dk,Pk,Mk,Lk,$k,Fk,jk,Uk,Hk,Gk,Bk,Wk,Kk,Vk,zk,qk,yu=_(()=>{Si();Ei();ou();$o();yr();ye=class{static{a(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}},au=a((e,t)=>{if(ct(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 ue(e.common.issues);return this._error=n,this._error}}},"handleResult");a(P,"processCreateParams");M=class{static{a(this,"ZodType")}get description(){return this._def.description}_getType(t){return Re(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Re(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new X,ctx:{common:t.parent.common,data:t.data,parsedType:Re(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(kn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Re(t)},i=this._parseSync({data:t,path:r.path,parent:r});return au(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Re(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ct(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=>ct(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:Re(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(kn(i)?i:Promise.resolve(i));return au(r,s)}refine(t,n){let r=a(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let o=t(i),c=a(()=>s.addIssue({code:x.custom,...r(i)}),"setError");return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!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 _e({schema:this,typeName:O.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:a(n=>this["~validate"](n),"validate")}}optional(){return ge.create(this,this._def)}nullable(){return Ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return We.create(this)}promise(){return ut.create(this,this._def)}or(t){return Ot.create([this,t],this._def)}and(t){return Dt.create(this,t,this._def)}transform(t){return new _e({...P(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Ft({...P(this._def),innerType:this,defaultValue:n,typeName:O.ZodDefault})}brand(){return new br({typeName:O.ZodBranded,type:this,...P(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new jt({...P(this._def),innerType:this,catchValue:n,typeName:O.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return wr.create(this,t)}readonly(){return Ut.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Bv=/^c[^\s-]{8,}$/i,Wv=/^[0-9a-z]+$/,Kv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vv=/^[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,zv=/^[a-z0-9_-]{21}$/i,qv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yv=/^[-+]?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)?)??$/,Jv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zv=/^(?:(?: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])$/,Qv=/^(?:(?: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])$/,ek=/^(([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]))$/,tk=/^(([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])$/,nk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lu="((\\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])))",ik=new RegExp(`^${lu}$`);a(du,"timeRegexSource");a(sk,"timeRegex");a(uu,"datetimeRegex");a(ok,"isValidIP");a(ak,"isValidJWT");a(ck,"isValidCidr");lt=class e extends M{static{a(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==T.string){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:T.string,received:s.parsedType}),C}let r=new X,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let o=t.data.length>s.value,c=t.data.length<s.value;(o||c)&&(i=this._getOrReturnCtx(t,i),o?E(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&E(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Jv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"email",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Fo||(Fo=new RegExp(Xv,"u")),Fo.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"emoji",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Vv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"uuid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")zv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"nanoid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Bv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Wv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid2",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Kv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ulid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),E(i,{validation:"url",code:x.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"regex",code:x.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?uu(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ik.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?sk(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Yv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"duration",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?ok(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ip",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?ak(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"jwt",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?ck(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cidr",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?nk.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?rk.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64url",code:x.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:x.invalid_string,...I.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...I.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...I.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...I.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...I.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...I.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...I.errToObj(n)})}nonempty(t){return this.min(1,I.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};lt.create=e=>new lt({checks:[],typeName:O.ZodString,coerce:e?.coerce??!1,...P(e)});a(lk,"floatSafeRemainder");Tt=class e extends M{static{a(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)!==T.number){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:T.number,received:s.parsedType}),C}let r,i=new X;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:x.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?lk(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:x.not_finite,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Tt.create=e=>new Tt({checks:[],typeName:O.ZodNumber,coerce:e?.coerce||!1,...P(e)});At=class e extends M{static{a(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)!==T.bigint)return this._getInvalidInput(t);let r,i=new X;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:T.bigint,received:n.parsedType}),C}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};At.create=e=>new At({checks:[],typeName:O.ZodBigInt,coerce:e?.coerce??!1,...P(e)});Rt=class extends M{static{a(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==T.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.boolean,received:r.parsedType}),C}return re(t.data)}};Rt.create=e=>new Rt({typeName:O.ZodBoolean,coerce:e?.coerce||!1,...P(e)});It=class e extends M{static{a(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==T.date){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:T.date,received:s.parsedType}),C}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_date}),C}let r=new X,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:I.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:I.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};It.create=e=>new It({checks:[],coerce:e?.coerce||!1,typeName:O.ZodDate,...P(e)});Sn=class extends M{static{a(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==T.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.symbol,received:r.parsedType}),C}return re(t.data)}};Sn.create=e=>new Sn({typeName:O.ZodSymbol,...P(e)});Nt=class extends M{static{a(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.undefined,received:r.parsedType}),C}return re(t.data)}};Nt.create=e=>new Nt({typeName:O.ZodUndefined,...P(e)});Ct=class extends M{static{a(this,"ZodNull")}_parse(t){if(this._getType(t)!==T.null){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.null,received:r.parsedType}),C}return re(t.data)}};Ct.create=e=>new Ct({typeName:O.ZodNull,...P(e)});dt=class extends M{static{a(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return re(t.data)}};dt.create=e=>new dt({typeName:O.ZodAny,...P(e)});Be=class extends M{static{a(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return re(t.data)}};Be.create=e=>new Be({typeName:O.ZodUnknown,...P(e)});ve=class extends M{static{a(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:T.never,received:n.parsedType}),C}};ve.create=e=>new ve({typeName:O.ZodNever,...P(e)});En=class extends M{static{a(this,"ZodVoid")}_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.void,received:r.parsedType}),C}return re(t.data)}};En.create=e=>new En({typeName:O.ZodVoid,...P(e)});We=class e extends M{static{a(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==T.array)return E(n,{code:x.invalid_type,expected:T.array,received:n.parsedType}),C;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(o||c)&&(E(n,{code:o?x.too_big:x.too_small,minimum:c?i.exactLength.value:void 0,maximum:o?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&&(E(n,{code:x.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&&(E(n,{code:x.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((o,c)=>i.type._parseAsync(new ye(n,o,n.path,c)))).then(o=>X.mergeArray(r,o));let s=[...n.data].map((o,c)=>i.type._parseSync(new ye(n,o,n.path,c)));return X.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(t){return this.min(1,t)}};We.create=(e,t)=>new We({type:e,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...P(t)});a(xn,"deepPartialify");pe=class e extends M{static{a(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==T.object){let d=this._getOrReturnCtx(t);return E(d,{code:x.invalid_type,expected:T.object,received:d.parsedType}),C}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof ve&&this._def.unknownKeys==="strip"))for(let d in i.data)o.includes(d)||c.push(d);let l=[];for(let d of o){let u=s[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ye(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof ve){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&&(E(i,{code:x.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 ye(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,h=await u.value;d.push({key:p,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>X.mergeObjectSync(r,d)):X.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:a((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:a(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:a(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:O.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:a(()=>n,"shape")})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:a(()=>n,"shape")})}deepPartial(){return xn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:a(()=>n,"shape")})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ge;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:a(()=>n,"shape")})}keyof(){return pu(L.objectKeys(this.shape))}};pe.create=(e,t)=>new pe({shape:a(()=>e,"shape"),unknownKeys:"strip",catchall:ve.create(),typeName:O.ZodObject,...P(t)});pe.strictCreate=(e,t)=>new pe({shape:a(()=>e,"shape"),unknownKeys:"strict",catchall:ve.create(),typeName:O.ZodObject,...P(t)});pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:ve.create(),typeName:O.ZodObject,...P(t)});Ot=class extends M{static{a(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let o=s.map(c=>new ue(c.ctx.common.issues));return E(n,{code:x.invalid_union,unionErrors:o}),C}if(a(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=o.map(l=>new ue(l));return E(n,{code:x.invalid_union,unionErrors:c}),C}}get options(){return this._def.options}};Ot.create=(e,t)=>new Ot({options:e,typeName:O.ZodUnion,...P(t)});Ge=a(e=>e instanceof Pt?Ge(e.schema):e instanceof _e?Ge(e.innerType()):e instanceof Mt?[e.value]:e instanceof Lt?e.options:e instanceof $t?L.objectValues(e.enum):e instanceof Ft?Ge(e._def.innerType):e instanceof Nt?[void 0]:e instanceof Ct?[null]:e instanceof ge?[void 0,...Ge(e.unwrap())]:e instanceof Ne?[null,...Ge(e.unwrap())]:e instanceof br||e instanceof Ut?Ge(e.unwrap()):e instanceof jt?Ge(e._def.innerType):[],"getDiscriminator"),Ri=class e extends M{static{a(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return E(n,{code:x.invalid_type,expected:T.object,received:n.parsedType}),C;let r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(E(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let s of n){let o=Ge(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of o){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:O.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...P(r)})}};a(jo,"mergeValues");Dt=class extends M{static{a(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=a((s,o)=>{if(Ti(s)||Ti(o))return C;let c=jo(s.value,o.value);return c.valid?((Ai(s)||Ai(o))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:x.invalid_intersection_types}),C)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,o])=>i(s,o)):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}))}};Dt.create=(e,t,n)=>new Dt({left:e,right:t,typeName:O.ZodIntersection,...P(n)});Ie=class e extends M{static{a(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.array)return E(r,{code:x.invalid_type,expected:T.array,received:r.parsedType}),C;if(r.data.length<this._def.items.length)return E(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((o,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ye(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>X.mergeArray(n,o)):X.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ie.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ie({items:e,typeName:O.ZodTuple,rest:null,...P(t)})};Ii=class e extends M{static{a(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!==T.object)return E(r,{code:x.invalid_type,expected:T.object,received:r.parsedType}),C;let i=[],s=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ye(r,c,r.path,c)),value:o._parse(new ye(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?X.mergeObjectAsync(n,i):X.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:O.ZodRecord,...P(r)}):new e({keyType:lt.create(),valueType:t,typeName:O.ZodRecord,...P(n)})}},Tn=class extends M{static{a(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!==T.map)return E(r,{code:x.invalid_type,expected:T.map,received:r.parsedType}),C;let i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ye(r,c,r.path,[d,"key"])),value:s._parse(new ye(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return C;(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 o){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};Tn.create=(e,t,n)=>new Tn({valueType:t,keyType:e,typeName:O.ZodMap,...P(n)});An=class e extends M{static{a(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.set)return E(r,{code:x.invalid_type,expected:T.set,received:r.parsedType}),C;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(E(r,{code:x.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&&(E(r,{code:x.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function o(l){let d=new Set;for(let u of l){if(u.status==="aborted")return C;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}a(o,"finalizeSet");let c=[...r.data.values()].map((l,d)=>s._parse(new ye(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};An.create=(e,t)=>new An({valueType:e,minSize:null,maxSize:null,typeName:O.ZodSet,...P(t)});Ni=class e extends M{static{a(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return E(n,{code:x.invalid_type,expected:T.function,received:n.parsedType}),C;function r(c,l){return _r({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vn(),He].filter(d=>!!d),issueData:{code:x.invalid_arguments,argumentsError:l}})}a(r,"makeArgsIssue");function i(c,l){return _r({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vn(),He].filter(d=>!!d),issueData:{code:x.invalid_return_type,returnTypeError:l}})}a(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof ut){let c=this;return re(async function(...l){let d=new ue([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(o,this,u);return await c._def.returns._def.type.parseAsync(p,s).catch(m=>{throw d.addIssue(i(p,m)),d})})}else{let c=this;return re(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new ue([r(l,d.error)]);let u=Reflect.apply(o,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new ue([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:Ie.create(t).rest(Be.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||Ie.create([]).rest(Be.create()),returns:n||Be.create(),typeName:O.ZodFunction,...P(r)})}},Pt=class extends M{static{a(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})}};Pt.create=(e,t)=>new Pt({getter:e,typeName:O.ZodLazy,...P(t)});Mt=class extends M{static{a(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}};Mt.create=(e,t)=>new Mt({value:e,typeName:O.ZodLiteral,...P(t)});a(pu,"createZodEnum");Lt=class e extends M{static{a(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:L.joinValues(r),received:n.parsedType,code:x.invalid_type}),C}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 E(n,{received:n.data,code:x.invalid_enum_value,options:r}),C}return re(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})}};Lt.create=pu;$t=class extends M{static{a(this,"ZodNativeEnum")}_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==T.string&&r.parsedType!==T.number){let i=L.objectValues(n);return E(r,{expected:L.joinValues(i),received:r.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=L.objectValues(n);return E(r,{received:r.data,code:x.invalid_enum_value,options:i}),C}return re(t.data)}get enum(){return this._def.values}};$t.create=(e,t)=>new $t({values:e,typeName:O.ZodNativeEnum,...P(t)});ut=class extends M{static{a(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return E(n,{code:x.invalid_type,expected:T.promise,received:n.parsedType}),C;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return re(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ut.create=(e,t)=>new ut({type:e,typeName:O.ZodPromise,...P(t)});_e=class extends M{static{a(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:a(o=>{E(r,o),o.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async c=>{if(n.value==="aborted")return C;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?C:l.status==="dirty"?Et(l.value):n.value==="dirty"?Et(l.value):l});{if(n.value==="aborted")return C;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?C:c.status==="dirty"?Et(c.value):n.value==="dirty"?Et(c.value):c}}if(i.type==="refinement"){let o=a(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),o(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"?C:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ct(o))return C;let c=i.transform(o.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ct(o)?Promise.resolve(i.transform(o.value,s)).then(c=>({status:n.value,value:c})):C);L.assertNever(i)}};_e.create=(e,t,n)=>new _e({schema:e,typeName:O.ZodEffects,effect:t,...P(n)});_e.createWithPreprocess=(e,t,n)=>new _e({schema:t,effect:{type:"preprocess",transform:e},typeName:O.ZodEffects,...P(n)});ge=class extends M{static{a(this,"ZodOptional")}_parse(t){return this._getType(t)===T.undefined?re(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ge.create=(e,t)=>new ge({innerType:e,typeName:O.ZodOptional,...P(t)});Ne=class extends M{static{a(this,"ZodNullable")}_parse(t){return this._getType(t)===T.null?re(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ne.create=(e,t)=>new Ne({innerType:e,typeName:O.ZodNullable,...P(t)});Ft=class extends M{static{a(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===T.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ft.create=(e,t)=>new Ft({innerType:e,typeName:O.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...P(t)});jt=class extends M{static{a(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return kn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ue(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ue(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};jt.create=(e,t)=>new jt({innerType:e,typeName:O.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...P(t)});Rn=class extends M{static{a(this,"ZodNaN")}_parse(t){if(this._getType(t)!==T.nan){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.nan,received:r.parsedType}),C}return{status:"valid",value:t.data}}};Rn.create=e=>new Rn({typeName:O.ZodNaN,...P(e)});dk=Symbol("zod_brand"),br=class extends M{static{a(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},wr=class e extends M{static{a(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return a(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?C:s.status==="dirty"?(n.dirty(),Et(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?C: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:O.ZodPipeline})}},Ut=class extends M{static{a(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=a(i=>(ct(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return kn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Ut.create=(e,t)=>new Ut({innerType:e,typeName:O.ZodReadonly,...P(t)});a(cu,"cleanParams");a(fu,"custom");uk={object:pe.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"})(O||(O={}));pk=a((e,t={message:`Input not instance of ${e.name}`})=>fu(n=>n instanceof e,t),"instanceOfType"),mu=lt.create,hu=Tt.create,fk=Rn.create,mk=At.create,gu=Rt.create,hk=It.create,gk=Sn.create,yk=Nt.create,_k=Ct.create,bk=dt.create,wk=Be.create,vk=ve.create,kk=En.create,xk=We.create,Sk=pe.create,Ek=pe.strictCreate,Tk=Ot.create,Ak=Ri.create,Rk=Dt.create,Ik=Ie.create,Nk=Ii.create,Ck=Tn.create,Ok=An.create,Dk=Ni.create,Pk=Pt.create,Mk=Mt.create,Lk=Lt.create,$k=$t.create,Fk=ut.create,jk=_e.create,Uk=ge.create,Hk=Ne.create,Gk=_e.createWithPreprocess,Bk=wr.create,Wk=a(()=>mu().optional(),"ostring"),Kk=a(()=>hu().optional(),"onumber"),Vk=a(()=>gu().optional(),"oboolean"),zk={string:a(e=>lt.create({...e,coerce:!0}),"string"),number:a(e=>Tt.create({...e,coerce:!0}),"number"),boolean:a(e=>Rt.create({...e,coerce:!0}),"boolean"),bigint:a(e=>At.create({...e,coerce:!0}),"bigint"),date:a(e=>It.create({...e,coerce:!0}),"date")},qk=C});var f={};ne(f,{BRAND:()=>dk,DIRTY:()=>Et,EMPTY_PATH:()=>Gv,INVALID:()=>C,NEVER:()=>qk,OK:()=>re,ParseStatus:()=>X,Schema:()=>M,ZodAny:()=>dt,ZodArray:()=>We,ZodBigInt:()=>At,ZodBoolean:()=>Rt,ZodBranded:()=>br,ZodCatch:()=>jt,ZodDate:()=>It,ZodDefault:()=>Ft,ZodDiscriminatedUnion:()=>Ri,ZodEffects:()=>_e,ZodEnum:()=>Lt,ZodError:()=>ue,ZodFirstPartyTypeKind:()=>O,ZodFunction:()=>Ni,ZodIntersection:()=>Dt,ZodIssueCode:()=>x,ZodLazy:()=>Pt,ZodLiteral:()=>Mt,ZodMap:()=>Tn,ZodNaN:()=>Rn,ZodNativeEnum:()=>$t,ZodNever:()=>ve,ZodNull:()=>Ct,ZodNullable:()=>Ne,ZodNumber:()=>Tt,ZodObject:()=>pe,ZodOptional:()=>ge,ZodParsedType:()=>T,ZodPipeline:()=>wr,ZodPromise:()=>ut,ZodReadonly:()=>Ut,ZodRecord:()=>Ii,ZodSchema:()=>M,ZodSet:()=>An,ZodString:()=>lt,ZodSymbol:()=>Sn,ZodTransformer:()=>_e,ZodTuple:()=>Ie,ZodType:()=>M,ZodUndefined:()=>Nt,ZodUnion:()=>Ot,ZodUnknown:()=>Be,ZodVoid:()=>En,addIssueToContext:()=>E,any:()=>bk,array:()=>xk,bigint:()=>mk,boolean:()=>gu,coerce:()=>zk,custom:()=>fu,date:()=>hk,datetimeRegex:()=>uu,defaultErrorMap:()=>He,discriminatedUnion:()=>Ak,effect:()=>jk,enum:()=>Lk,function:()=>Dk,getErrorMap:()=>vn,getParsedType:()=>Re,instanceof:()=>pk,intersection:()=>Rk,isAborted:()=>Ti,isAsync:()=>kn,isDirty:()=>Ai,isValid:()=>ct,late:()=>uk,lazy:()=>Pk,literal:()=>Mk,makeIssue:()=>_r,map:()=>Ck,nan:()=>fk,nativeEnum:()=>$k,never:()=>vk,null:()=>_k,nullable:()=>Hk,number:()=>hu,object:()=>Sk,objectUtil:()=>Mo,oboolean:()=>Vk,onumber:()=>Kk,optional:()=>Uk,ostring:()=>Wk,pipeline:()=>Bk,preprocess:()=>Gk,promise:()=>Fk,quotelessJson:()=>jv,record:()=>Nk,set:()=>Ok,setErrorMap:()=>Hv,strictObject:()=>Ek,string:()=>mu,symbol:()=>gk,transformer:()=>jk,tuple:()=>Ik,undefined:()=>yk,union:()=>Tk,unknown:()=>wk,util:()=>L,void:()=>kk});var Uo=_(()=>{Ei();$o();su();yr();yu();Si()});var ie=_(()=>{Uo();Uo()});var Ho,Go=_(()=>{"use strict";ie();Ho=f.object({id:f.string().min(1),title:f.string().min(1).max(200),type:f.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:f.enum(["community","curated"]),lesson_class:f.enum(["general","architecture"]).default("general"),quality_tier:f.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:f.object({source:f.enum(["memory","vault","claude-md"]),source_id:f.string().min(1),migrated_at:f.string(),migrated_from_workspace:f.string().optional()}).optional(),context:f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),summary:f.string().min(1).max(500),problem:f.string().optional(),solution:f.string().optional(),gotchas:f.array(f.string()).default([]),template_body:f.string().min(1).optional(),target_file:f.string().min(1).optional(),submitted_by:f.string().optional(),evidence:f.string().optional(),last_validated_at:f.string().optional(),tool_versions:f.record(f.string(),f.string()).optional(),upvotes:f.number().int().nonnegative().default(0),version:f.number().int().min(1).default(1),changed_at:f.string().optional(),changelog:f.string().max(500).optional(),revision_of:f.string().optional(),org_id:f.string().uuid().optional(),org_name:f.string().optional(),scope:f.literal("private").optional(),body:f.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var Yk,_u=_(()=>{"use strict";ie();Go();Yk=Ho.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:f.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:f.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var bu,wu,vu,ku,Bo,xu,Su,Eu,Jk,Tu=_(()=>{"use strict";ie();bu=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],wu=f.enum(bu),vu=["new_to_ai_agents","new_to_this_client","experienced"],ku=f.enum(vu),Bo=[{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"}],xu=Bo.map(e=>e.header),Su=f.object({experience_level:f.array(ku).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),Eu=f.object({id:f.string().min(1),client:wu,title:f.string().min(1),last_updated:f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:Su,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Jk=Eu.extend({body:f.string().min(1)})});var Ru,Ci,Iu,Oi,Xk,Zk,Nu,Cu,Ou,Du,Di,Qk,ex,Au,tx,Pu,nx,Mu=_(()=>{"use strict";ie();Ru=["operating_procedure","code_review","communication_style"],Ci=f.enum(Ru),Iu=["info","recommended","required"],Oi=f.enum(Iu),Xk=["optional","default_on","mandatory"],Zk=f.enum(Xk),Nu=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Cu=f.enum(Nu),Ou=["verify","contribute","mixed"],Du=f.enum(Ou),Di=f.object({clients:f.array(Cu).default([]),stacks:f.array(f.string()).default([]),intents:f.array(Du).default([])}).default({clients:[],stacks:[],intents:[]}),Qk=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,ex=64,Au=200,tx=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Pu=f.object({id:f.string().min(5).max(ex).regex(Qk,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:Ci,version:f.number().int().min(1),changed_at:tx,changelog:f.string().max(500).optional(),applies_to:Di,severity:Oi.default("recommended"),disableability:Zk.default("default_on"),summary:f.string().min(1).max(Au,`summary must be \u2264 ${Au} chars (rendered as one line in init-push)`),review_gate:f.object({enabled:f.boolean(),min_matched_symbols:f.number().int().min(1).max(8).default(2),hard:f.boolean().default(!1)}).optional(),gateway_gate:f.object({enabled:f.boolean(),deny_tools:f.array(f.string().min(1).max(128)).min(1).max(16),servers:f.array(f.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),nx=Pu.extend({body:f.string().min(1)})});var pt=_(()=>{"use strict";Go();_u();Tu();Mu()});var Wo,Pi,Ko,Lu,$u,Fu,rx,ju=_(()=>{"use strict";ie();Wo=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),Pi=f.number().min(0).max(1).optional(),Ko=f.object({type:f.literal("media"),kind:f.enum(["image","video"]),url:f.string().url().max(2048),alt:f.string().max(500).optional(),caption:f.string().max(500).optional(),fog:f.object({top:Pi,right:Pi,bottom:Pi,left:Pi}).optional()}),Lu=f.object({label:f.string().min(1).max(40),color:f.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),$u=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Lu.optional(),blocks:f.array(f.discriminatedUnion("type",[Wo,Ko])).max(50)}),Fu=f.discriminatedUnion("type",[Wo,Ko,$u]),rx=f.array(Fu).max(100)});var Uu,ix,Hu,Gu,sx,ox,ax,Bu=_(()=>{"use strict";ie();Uu=["free","solo_pro","team","enterprise"],ix=f.enum(Uu),Hu=["solo_pro","team","enterprise"],Gu=f.enum(Hu),sx=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),ox=f.object({user_id:f.string().uuid(),tier:Gu,reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:sx.nullable().optional(),auto_revoke_on_stripe:f.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"}),ax=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Wu=_(()=>{"use strict"});var cx,lx,dx,Ku=_(()=>{"use strict";ie();cx=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),lx=f.object({org_id:f.string().uuid(),seats:f.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:cx.nullable().optional(),auto_revoke_on_stripe:f.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"}),dx=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Vu,ux,zu,qu,Yu,Ju,px,Xu=_(()=>{"use strict";ie();Vu=f.enum(["info","important","critical"]),ux=f.enum(["pass","warn","fail"]),zu=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),qu=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),Yu=f.discriminatedUnion("kind",[f.object({kind:f.literal("file-exists"),path:f.string().min(1)}),f.object({kind:f.literal("any-file-exists"),paths:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("any-agent-config")}),f.object({kind:f.literal("file-size-budget"),field:f.enum(["claude_md","readme"]),max_chars:f.number().int().positive()}),f.object({kind:f.literal("readme-section-present"),headers:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("adr-dir-present")}),f.object({kind:f.literal("git-present")}),f.object({kind:f.literal("quality-gates-configured"),pass_if_at_least:f.number().int().min(1).max(4).optional(),warn_if_at_least:f.number().int().min(0).max(4).optional()}),f.object({kind:f.literal("storage-risk-safe"),allow_unknown:f.boolean().optional()}),f.object({kind:f.literal("doc-path-discoverability")})]),Ju=f.object({id:f.string().min(1),title:f.string().min(1),severity:Vu,weight:f.number().int().positive().max(100),applies_when:qu,check:Yu,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:zu.optional()}),px=f.object({version:f.literal(1),checks:f.array(Ju).min(1)})});function mx(e){if(!fx.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Mi(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 hx(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var fx,Li,Zu,Qu,Ce,Vo,ep,gx,tp=_(()=>{"use strict";ie();fx=/^\d{4}-\d{2}-\d{2}$/;a(mx,"isRealDate");Li=f.string().refine(mx,{message:"expected a real calendar date as YYYY-MM-DD"}),Zu=["exact","prefix"],Qu=f.enum(Zu),Ce=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Vo=[2e5,272e3],ep=f.object({model_pattern:f.string().min(1).max(100),match_kind:Qu,valid_from:Li,valid_to:Li.nullable().optional(),input:Ce,output:Ce,cache_read:Ce,cache_write_5m:Ce,cache_write_1h:Ce,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Ce.optional(),output_above_200k:Ce.optional(),cache_read_above_200k:Ce.optional(),cache_write_5m_above_200k:Ce.optional(),cache_write_1h_above_200k:Ce.optional(),context_threshold_tokens:f.number().int().positive().nullable().optional(),source_url:f.string().url().max(500).nullable().optional(),note:f.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=>Mi(e)===0||Mi(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"||Mi(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=>Mi(e)===0||e.context_threshold_tokens==null||Vo.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Vo.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});a(Mi,"aboveRateCount");a(hx,"rowKey");gx=f.object({changelog:f.string().min(1).max(500),as_of:Li,source_url:f.string().url().max(500),rows:f.array(ep).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let o=hx(i),c=n.get(o);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${o} (first at rows[${c}])`}):n.set(o,s)});let r=new Map;e.rows.forEach((i,s)=>{let o=`${i.model_pattern}|${i.match_kind}`,c=r.get(o)??[];c.push({i:s,r:i}),r.set(o,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,o)=>s.r.valid_from.localeCompare(o.r.valid_from));for(let s=0;s<i.length-1;s++){let o=i[s],c=i[s+1];(!o.r.valid_to||o.r.valid_to>c.r.valid_from)&&t.addIssue({code:f.ZodIssueCode.custom,path:["rows",o.i,"valid_to"],message:`window overlaps the next one for ${o.r.model_pattern} (${o.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var In=_(()=>{"use strict"});var vr=_(()=>{"use strict"});var sp=_(()=>{"use strict";vr();In()});var op=_(()=>{"use strict";In()});var ap=_(()=>{"use strict";pt();vr();In()});var cp=_(()=>{"use strict";vr();In()});var lp=_(()=>{"use strict";In();sp();op();ap();cp();vr()});var Mx,Lx,dp,$x,up,zo,pp,fp,mp,hp,Fx,qo=_(()=>{"use strict";ie();pt();Mx=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Lx=64,dp=200,$x=1e3,up=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),zo=f.enum(["low","medium","high"]),pp=f.object({owner:f.string().min(1).max(160).optional(),risk_level:zo.optional(),reviewed_at:up.optional()}).default({}),fp=f.object({tags:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),limit:f.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),mp=f.object({lesson_query:fp,lesson_pins:f.array(f.string()).default([]),lesson_excludes:f.array(f.string()).default([]),convention_ids:f.array(f.string()).default([]),template_ids:f.array(f.string()).default([]),setup_guide_ids:f.array(f.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),hp=f.object({id:f.string().min(6).max(Lx).regex(Mx,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:up,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(dp,`summary must be \u2264 ${dp} chars (rendered as one line in skill_index)`),description:f.string().max($x).optional(),applies_to:Di,membership:mp,governance:pp}),Fx=hp.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var gp,yp,_p,bp,wp,vp,jx,kp,Ux,Hx,xp=_(()=>{"use strict";ie();qo();gp=f.enum(["maind","agent-skill"]),yp=f.enum(["ready","needs_attention","blocked"]),_p=f.enum(["info","important","critical"]),bp=f.enum(["pass","warn","fail"]),wp=f.enum(["structure","governance","scope","membership","package","references"]),vp=f.object({id:f.string().min(1),title:f.string().min(1),status:bp,severity:_p,category:wp,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),jx=f.object({lesson_ids:f.array(f.string()).optional(),convention_ids:f.array(f.string()).optional(),template_ids:f.array(f.string()).optional(),setup_guide_ids:f.array(f.string()).optional()}).default({}),kp=f.object({name:f.string().min(1).max(64),description:f.string().min(1).max(1024),license:f.string().optional(),compatibility:f.union([f.string(),f.array(f.string())]).optional(),metadata:f.record(f.string()).default({}),"allowed-tools":f.union([f.string(),f.array(f.string())]).optional()}).passthrough(),Ux=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:kp,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),Hx=f.object({format:gp,subject:f.string().min(1),status:yp,summary:f.string().min(1),counts:f.object({pass:f.number().int().min(0),warn:f.number().int().min(0),fail:f.number().int().min(0)}),checks:f.array(vp),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var Yo=_(()=>{"use strict"});var Sp,Bx,Ep,Tp,Ap,Nn,Wx,Rp,Ip,Np,Cp,Op,Dp,Pp,Mp,Kx,Lp,$p,Fp,ft,Jo,jp,Up,Vx,Hp=_(()=>{"use strict";ie();pt();Yo();Sp=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Bx=f.enum(Sp),Ep=["verdict","advisory"],Tp=f.enum(Ep),Ap=["block","warn","note"],Nn=f.enum(Ap),Wx=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:Oi,scope:Ci,grade:Tp,matched_symbols:f.array(f.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:f.array(f.string().min(1).max(512)).max(64).default([]),summary:f.string().max(2e3),hard:f.boolean().optional()}),Rp=["open","warn","info"],Ip=f.enum(Rp),Np=["introduced","pre_existing"],Cp=f.enum(Np),Op=["full","partial","none"],Dp=f.enum(Op),Pp=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),rule_id:f.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:Ip,baseline:Cp,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Mp=f.object({version:f.literal(1).default(1),actions:f.object({required:Nn.default("block"),recommended:Nn.default("warn"),info:Nn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:Nn})).max(64).default([]),risk_flag_action:f.enum(["warn","note","ignore"]).default("warn"),detector_overrides:f.array(f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Nn,reason:f.string().min(1).max(200)})).max(32).optional()}),Kx=Mp.parse({}),Lp=["ran","not_applicable","unavailable","ungraded"],$p=f.enum(Lp),Fp=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),state:$p}),ft=1e3,Jo=f.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),jp=f.object({name:f.string().min(1).max(200),qualified_name:f.string().min(1).max(512).optional(),kind:f.string().min(1).max(64).optional(),language:f.string().min(1).max(32).optional(),change:f.enum(["added","modified","co_located"]).optional(),changed_line_count:f.number().int().min(0).max(1e4).optional()}),Up=f.object({base_kind:f.enum(["uncommitted","ref"]),changed_file_count:f.number().int().min(0),stale_file_count:f.number().int().min(0),unindexed_file_count:f.number().int().min(0).optional(),truncated:f.boolean(),hunk_coverage:f.enum(["full","partial","none"]),detector_coverage:Dp}),Vx=f.object({changed_symbols:f.array(jp).max(ft),risk_flags:f.array(f.string().max(64)).max(16),detector_findings:f.array(Pp).max(64),detector_runs:f.array(Fp).min(1).max(32),diff_stats:Up,commit_sha:Jo.optional(),base_sha:Jo.optional(),merge_base_sha:Jo.optional(),dirty:f.boolean().optional(),code_index_version:f.string().min(1).max(32).optional()})});var Gp,Bp,Wp,Kp,Vp,Xo,zx,qx,zp,qp,Yp,Jp,Xp,Yx,Jx,Zp,Qp,ef,Xx,tf=_(()=>{"use strict";ie();Gp=14,Bp=14,Wp=14,Kp=1,Vp=365,Xo=f.number().int().min(Kp).max(Vp),zx=["propose","direct"],qx="propose",zp=["propose","direct"],qp="propose",Yp=["propose","direct"],Jp="propose",Xp=["off","propose","direct"],Yx=["member","admin","owner"],Jx="member",Zp="off",Qp="en",ef=f.object({version:f.literal(1).default(1),at_risk_days:Xo.default(Gp),stagnation_days:Xo.default(Bp),agent_date_mode:f.enum(zx).default(qx),health_manual_ttl_days:Xo.default(Wp),agent_event_mode:f.enum(zp).default(qp),agent_update_mode:f.enum(Yp).default(Jp),agent_pull_mode:f.enum(Xp).default(Zp),org_wide_authoring_min_role:f.enum(Yx).default(Jx),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Qp)}),Xx=ef.parse({})});var nf,Zx,rf=_(()=>{"use strict";ie();nf=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Zx=nf.parse({})});var sf,of,Qx,eS,af=_(()=>{"use strict";ie();sf=f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),of=f.object({id:f.string().uuid(),user_id:f.string().uuid(),project:f.string().max(200).nullable().optional(),title:f.string().min(1).max(200),body:f.string().min(1).max(2e4),context:sf.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:f.string(),updated_at:f.string(),last_recalled_at:f.string().nullable().optional(),recall_count:f.number().int().nonnegative().default(0),graduated_draft_id:f.string().uuid().nullable().optional(),deleted_at:f.string().nullable().optional()}),Qx=of.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:f.number()}),eS=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var cf=_(()=>{"use strict"});function $i(e){let t=[],n=null;return e.split(`
|
|
3
|
-
`).forEach((r,i)=>{let s=r.trim(),o=r.length-r.trimStart().length;if(n!==null){if(s===""||o>n)return;n=null}if(s===""||s.startsWith("#"))return;let c=
|
|
4
|
-
`).slice(0,1e3)}var
|
|
5
|
-
`).filter(l=>
|
|
2
|
+
var du=Object.defineProperty;var a=(e,t)=>du(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)du(e,n,{get:t[n],enumerable:!0})};function pu(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let o=n.params;if(typeof o=="object"&&o!==null){let c=o.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function vn(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 jo(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Uo(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Ho(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Bo=_(()=>{"use strict";a(pu,"parseFrame");a(vn,"denyResult");a(jo,"toolEvent");a(Uo,"policyEvent");a(Ho,"shaEvent")});import{execFileSync as hu}from"node:child_process";function gu(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=lk}function dk(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let s of ok){let o=r[s];typeof o=="string"&&fu.test(o)&&i.push({field:s,sha:o})}for(let[s,o]of ak){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[o];typeof l=="string"&&fu.test(l)&&i.push({field:`${s}.${o}`,sha:l})}return i}function uk(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,mu);for(let i=mu;i>=ck;i--){let s=r.slice(0,i),o=t(s);if(o!==null&&o.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:o,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function kn(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 yu(){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 xi(e=process.cwd()){try{let n=hu("git",["rev-parse","--show-toplevel"],{cwd:e,env:yu(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function pk(e){return t=>{try{let r=hu("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:yu(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function Si(e,t){if(t===null)return[];let n=dk(e);if(n.length===0)return[];let r=pk(t),i=[];for(let{field:s,sha:o}of n){let c=uk(o,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var ok,ak,fu,ck,mu,lk,Go=_(()=>{"use strict";ok=["commit_sha","base_sha","head_sha"],ak=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],fu=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,ck=7,mu=12,lk=10;a(gu,"isDenyGrade");a(dk,"extractShaArgs");a(uk,"classifySha");a(kn,"shaFindingText");a(yu,"cleanGitEnv");a(xi,"resolveRepoRootForSha");a(pk,"gitShaResolver");a(Si,"inspectLineForShas")});var bu=_(()=>{"use strict"});var L,Ko,A,Oe,br=_(()=>{(function(e){e.assertEqual=i=>{};function t(i){}a(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}a(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),o={};for(let c of s)o[c]=i[c];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}a(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ko||(Ko={}));A=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Oe=a(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 S,fk,ue,Ei=_(()=>{br();S=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),fk=a(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ue=class e extends Error{static{a(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},i=a(s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let c=r,l=0;for(;l<o.path.length;){let d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ue.create=e=>new ue(e)});var mk,We,Vo=_(()=>{Ei();br();mk=a((e,t)=>{let n;switch(e.code){case S.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case S.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,L.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case S.invalid_union:n="Invalid input";break;case S.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case S.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case S.invalid_arguments:n="Invalid function arguments";break;case S.invalid_return_type:n="Invalid function return type";break;case S.invalid_date:n="Invalid date";break;case S.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case S.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 S.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 S.custom:n="Invalid input";break;case S.invalid_intersection_types:n="Intersection results could not be merged";break;case S.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case S.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},"errorMap"),We=mk});function hk(e){wu=e}function xn(){return wu}var wu,Ti=_(()=>{Vo();wu=We;a(hk,"setErrorMap");a(xn,"getErrorMap")});function T(e,t){let n=xn(),r=wr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===We?void 0:We].filter(i=>!!i)});e.common.issues.push(r)}var wr,gk,te,O,Et,ie,Ai,Ri,lt,Sn,zo=_(()=>{Ti();Vo();wr=a(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(o,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),gk=[];a(T,"addIssueToContext");te=class e{static{a(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return O;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let s=await i.key,o=await i.value;r.push({key:s,value:o})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return O;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:t.value,value:r}}},O=Object.freeze({status:"aborted"}),Et=a(e=>({status:"dirty",value:e}),"DIRTY"),ie=a(e=>({status:"valid",value:e}),"OK"),Ai=a(e=>e.status==="aborted","isAborted"),Ri=a(e=>e.status==="dirty","isDirty"),lt=a(e=>e.status==="valid","isValid"),Sn=a(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var vu=_(()=>{});var N,ku=_(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(N||(N={}))});function P(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:a((o,c)=>{let{message:l}=e;return o.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function Tu(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 Dk(e){return new RegExp(`^${Tu(e)}$`)}function Au(e){let t=`${Eu}T${Tu(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 Pk(e,t){return!!((t==="v4"||!t)&&Tk.test(e)||(t==="v6"||!t)&&Rk.test(e))}function Mk(e,t){if(!kk.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 Lk(e,t){return!!((t==="v4"||!t)&&Ak.test(e)||(t==="v6"||!t)&&Ik.test(e))}function $k(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function En(e){if(e instanceof pe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ge.create(En(r))}return new pe({...e._def,shape:a(()=>t,"shape")})}else return e instanceof ze?new ze({...e._def,type:En(e.element)}):e instanceof ge?ge.create(En(e.unwrap())):e instanceof Pe?Pe.create(En(e.unwrap())):e instanceof De?De.create(e.items.map(t=>En(t))):e}function Yo(e,t){let n=Oe(e),r=Oe(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let i=L.objectKeys(t),s=L.objectKeys(e).filter(c=>i.indexOf(c)!==-1),o={...e,...t};for(let c of s){let l=Yo(e[c],t[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],c=t[s],l=Yo(o,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 Ru(e,t){return new Lt({values:e,typeName:D.ZodEnum,...P(t)})}function Su(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Iu(e,t={},n){return e?ut.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(o=>{if(!o){let c=Su(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let o=Su(t,r),c=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:c})}}):ut.create()}var ye,xu,M,yk,_k,bk,wk,vk,kk,xk,Sk,Ek,qo,Tk,Ak,Rk,Ik,Nk,Ck,Eu,Ok,dt,Tt,At,Rt,It,Tn,Nt,Ct,ut,Ve,ve,An,ze,pe,Ot,Ke,Ii,Dt,De,Ni,Rn,In,Ci,Pt,Mt,Lt,$t,pt,_e,ge,Pe,Ft,jt,Nn,Fk,vr,kr,Ut,jk,D,Uk,Nu,Cu,Hk,Bk,Ou,Gk,Wk,Kk,Vk,zk,qk,Yk,Jk,Xk,Zk,Qk,ex,tx,nx,rx,ix,sx,ox,ax,cx,lx,dx,ux,px,fx,mx,hx,gx,yx,_x,bx,wx,vx,kx,Du=_(()=>{Ei();Ti();ku();zo();br();ye=class{static{a(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}},xu=a((e,t)=>{if(lt(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 ue(e.common.issues);return this._error=n,this._error}}},"handleResult");a(P,"processCreateParams");M=class{static{a(this,"ZodType")}get description(){return this._def.description}_getType(t){return Oe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new te,ctx:{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Sn(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:Oe(t)},i=this._parseSync({data:t,path:r.path,parent:r});return xu(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Oe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return lt(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=>lt(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:Oe(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(Sn(i)?i:Promise.resolve(i));return xu(r,s)}refine(t,n){let r=a(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let o=t(i),c=a(()=>s.addIssue({code:S.custom,...r(i)}),"setError");return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!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 _e({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a(n=>this["~validate"](n),"validate")}}optional(){return ge.create(this,this._def)}nullable(){return Pe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return pt.create(this,this._def)}or(t){return Ot.create([this,t],this._def)}and(t){return Dt.create(this,t,this._def)}transform(t){return new _e({...P(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Ft({...P(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new vr({typeName:D.ZodBranded,type:this,...P(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new jt({...P(this._def),innerType:this,catchValue:n,typeName:D.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return kr.create(this,t)}readonly(){return Ut.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yk=/^c[^\s-]{8,}$/i,_k=/^[0-9a-z]+$/,bk=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wk=/^[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,vk=/^[a-z0-9_-]{21}$/i,kk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xk=/^[-+]?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)?)??$/,Sk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ek="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Tk=/^(?:(?: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])$/,Ak=/^(?:(?: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])$/,Rk=/^(([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]))$/,Ik=/^(([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])$/,Nk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ck=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Eu="((\\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])))",Ok=new RegExp(`^${Eu}$`);a(Tu,"timeRegexSource");a(Dk,"timeRegex");a(Au,"datetimeRegex");a(Pk,"isValidIP");a(Mk,"isValidJWT");a(Lk,"isValidCidr");dt=class e extends M{static{a(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let s=this._getOrReturnCtx(t);return T(s,{code:S.invalid_type,expected:A.string,received:s.parsedType}),O}let r=new te,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let o=t.data.length>s.value,c=t.data.length<s.value;(o||c)&&(i=this._getOrReturnCtx(t,i),o?T(i,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&T(i,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Sk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"email",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")qo||(qo=new RegExp(Ek,"u")),qo.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"emoji",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")wk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"uuid",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")vk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"nanoid",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")yk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cuid",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")_k.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cuid2",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")bk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"ulid",code:S.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),T(i,{validation:"url",code:S.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"regex",code:S.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),T(i,{code:S.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),T(i,{code:S.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),T(i,{code:S.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Au(s).test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:S.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Ok.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:S.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Dk(s).test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:S.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?xk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"duration",code:S.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Pk(t.data,s.version)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"ip",code:S.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Mk(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"jwt",code:S.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Lk(t.data,s.version)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cidr",code:S.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Nk.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"base64",code:S.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Ck.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"base64url",code:S.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:S.invalid_string,...N.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...N.errToObj(t)})}url(t){return this._addCheck({kind:"url",...N.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...N.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...N.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...N.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...N.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...N.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...N.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...N.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...N.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...N.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...N.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...N.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...N.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...N.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...N.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...N.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...N.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...N.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...N.errToObj(n)})}nonempty(t){return this.min(1,N.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}};dt.create=e=>new dt({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...P(e)});a($k,"floatSafeRemainder");Tt=class e extends M{static{a(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let s=this._getOrReturnCtx(t);return T(s,{code:S.invalid_type,expected:A.number,received:s.parsedType}),O}let r,i=new te;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),T(r,{code:S.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),T(r,{code:S.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),T(r,{code:S.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?$k(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),T(r,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),T(r,{code:S.not_finite,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:N.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:N.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Tt.create=e=>new Tt({checks:[],typeName:D.ZodNumber,coerce:e?.coerce||!1,...P(e)});At=class e extends M{static{a(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 te;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),T(r,{code:S.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),T(r,{code:S.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),T(r,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return T(n,{code:S.invalid_type,expected:A.bigint,received:n.parsedType}),O}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.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:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.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}};At.create=e=>new At({checks:[],typeName:D.ZodBigInt,coerce:e?.coerce??!1,...P(e)});Rt=class extends M{static{a(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return T(r,{code:S.invalid_type,expected:A.boolean,received:r.parsedType}),O}return ie(t.data)}};Rt.create=e=>new Rt({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...P(e)});It=class e extends M{static{a(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let s=this._getOrReturnCtx(t);return T(s,{code:S.invalid_type,expected:A.date,received:s.parsedType}),O}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return T(s,{code:S.invalid_date}),O}let r=new te,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:S.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:S.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:N.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:N.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}};It.create=e=>new It({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...P(e)});Tn=class extends M{static{a(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return T(r,{code:S.invalid_type,expected:A.symbol,received:r.parsedType}),O}return ie(t.data)}};Tn.create=e=>new Tn({typeName:D.ZodSymbol,...P(e)});Nt=class extends M{static{a(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return T(r,{code:S.invalid_type,expected:A.undefined,received:r.parsedType}),O}return ie(t.data)}};Nt.create=e=>new Nt({typeName:D.ZodUndefined,...P(e)});Ct=class extends M{static{a(this,"ZodNull")}_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return T(r,{code:S.invalid_type,expected:A.null,received:r.parsedType}),O}return ie(t.data)}};Ct.create=e=>new Ct({typeName:D.ZodNull,...P(e)});ut=class extends M{static{a(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ie(t.data)}};ut.create=e=>new ut({typeName:D.ZodAny,...P(e)});Ve=class extends M{static{a(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ie(t.data)}};Ve.create=e=>new Ve({typeName:D.ZodUnknown,...P(e)});ve=class extends M{static{a(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return T(n,{code:S.invalid_type,expected:A.never,received:n.parsedType}),O}};ve.create=e=>new ve({typeName:D.ZodNever,...P(e)});An=class extends M{static{a(this,"ZodVoid")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return T(r,{code:S.invalid_type,expected:A.void,received:r.parsedType}),O}return ie(t.data)}};An.create=e=>new An({typeName:D.ZodVoid,...P(e)});ze=class e extends M{static{a(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==A.array)return T(n,{code:S.invalid_type,expected:A.array,received:n.parsedType}),O;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(o||c)&&(T(n,{code:o?S.too_big:S.too_small,minimum:c?i.exactLength.value:void 0,maximum:o?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&&(T(n,{code:S.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&&(T(n,{code:S.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((o,c)=>i.type._parseAsync(new ye(n,o,n.path,c)))).then(o=>te.mergeArray(r,o));let s=[...n.data].map((o,c)=>i.type._parseSync(new ye(n,o,n.path,c)));return te.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:N.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:N.toString(n)}})}nonempty(t){return this.min(1,t)}};ze.create=(e,t)=>new ze({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...P(t)});a(En,"deepPartialify");pe=class e extends M{static{a(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let d=this._getOrReturnCtx(t);return T(d,{code:S.invalid_type,expected:A.object,received:d.parsedType}),O}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof ve&&this._def.unknownKeys==="strip"))for(let d in i.data)o.includes(d)||c.push(d);let l=[];for(let d of o){let u=s[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ye(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof ve){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&&(T(i,{code:S.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 ye(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,h=await u.value;d.push({key:p,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>te.mergeObjectSync(r,d)):te.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return N.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:a((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:N.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:a(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:a(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:D.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:a(()=>n,"shape")})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:a(()=>n,"shape")})}deepPartial(){return En(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:a(()=>n,"shape")})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ge;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:a(()=>n,"shape")})}keyof(){return Ru(L.objectKeys(this.shape))}};pe.create=(e,t)=>new pe({shape:a(()=>e,"shape"),unknownKeys:"strip",catchall:ve.create(),typeName:D.ZodObject,...P(t)});pe.strictCreate=(e,t)=>new pe({shape:a(()=>e,"shape"),unknownKeys:"strict",catchall:ve.create(),typeName:D.ZodObject,...P(t)});pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:ve.create(),typeName:D.ZodObject,...P(t)});Ot=class extends M{static{a(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let o=s.map(c=>new ue(c.ctx.common.issues));return T(n,{code:S.invalid_union,unionErrors:o}),O}if(a(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=o.map(l=>new ue(l));return T(n,{code:S.invalid_union,unionErrors:c}),O}}get options(){return this._def.options}};Ot.create=(e,t)=>new Ot({options:e,typeName:D.ZodUnion,...P(t)});Ke=a(e=>e instanceof Pt?Ke(e.schema):e instanceof _e?Ke(e.innerType()):e instanceof Mt?[e.value]:e instanceof Lt?e.options:e instanceof $t?L.objectValues(e.enum):e instanceof Ft?Ke(e._def.innerType):e instanceof Nt?[void 0]:e instanceof Ct?[null]:e instanceof ge?[void 0,...Ke(e.unwrap())]:e instanceof Pe?[null,...Ke(e.unwrap())]:e instanceof vr||e instanceof Ut?Ke(e.unwrap()):e instanceof jt?Ke(e._def.innerType):[],"getDiscriminator"),Ii=class e extends M{static{a(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return T(n,{code:S.invalid_type,expected:A.object,received:n.parsedType}),O;let r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(T(n,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let s of n){let o=Ke(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of o){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:D.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...P(r)})}};a(Yo,"mergeValues");Dt=class extends M{static{a(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=a((s,o)=>{if(Ai(s)||Ai(o))return O;let c=Yo(s.value,o.value);return c.valid?((Ri(s)||Ri(o))&&n.dirty(),{status:n.value,value:c.data}):(T(r,{code:S.invalid_intersection_types}),O)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,o])=>i(s,o)):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}))}};Dt.create=(e,t,n)=>new Dt({left:e,right:t,typeName:D.ZodIntersection,...P(n)});De=class e extends M{static{a(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return T(r,{code:S.invalid_type,expected:A.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return T(r,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(T(r,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((o,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ye(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>te.mergeArray(n,o)):te.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};De.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new De({items:e,typeName:D.ZodTuple,rest:null,...P(t)})};Ni=class e extends M{static{a(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 T(r,{code:S.invalid_type,expected:A.object,received:r.parsedType}),O;let i=[],s=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ye(r,c,r.path,c)),value:o._parse(new ye(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?te.mergeObjectAsync(n,i):te.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:D.ZodRecord,...P(r)}):new e({keyType:dt.create(),valueType:t,typeName:D.ZodRecord,...P(n)})}},Rn=class extends M{static{a(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 T(r,{code:S.invalid_type,expected:A.map,received:r.parsedType}),O;let i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ye(r,c,r.path,[d,"key"])),value:s._parse(new ye(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return O;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of o){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return O;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};Rn.create=(e,t,n)=>new Rn({valueType:t,keyType:e,typeName:D.ZodMap,...P(n)});In=class e extends M{static{a(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return T(r,{code:S.invalid_type,expected:A.set,received:r.parsedType}),O;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(T(r,{code:S.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&&(T(r,{code:S.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function o(l){let d=new Set;for(let u of l){if(u.status==="aborted")return O;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}a(o,"finalizeSet");let c=[...r.data.values()].map((l,d)=>s._parse(new ye(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:N.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};In.create=(e,t)=>new In({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...P(t)});Ci=class e extends M{static{a(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return T(n,{code:S.invalid_type,expected:A.function,received:n.parsedType}),O;function r(c,l){return wr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,xn(),We].filter(d=>!!d),issueData:{code:S.invalid_arguments,argumentsError:l}})}a(r,"makeArgsIssue");function i(c,l){return wr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,xn(),We].filter(d=>!!d),issueData:{code:S.invalid_return_type,returnTypeError:l}})}a(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof pt){let c=this;return ie(async function(...l){let d=new ue([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),p=await Reflect.apply(o,this,u);return await c._def.returns._def.type.parseAsync(p,s).catch(m=>{throw d.addIssue(i(p,m)),d})})}else{let c=this;return ie(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new ue([r(l,d.error)]);let u=Reflect.apply(o,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new ue([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:De.create(t).rest(Ve.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||De.create([]).rest(Ve.create()),returns:n||Ve.create(),typeName:D.ZodFunction,...P(r)})}},Pt=class extends M{static{a(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})}};Pt.create=(e,t)=>new Pt({getter:e,typeName:D.ZodLazy,...P(t)});Mt=class extends M{static{a(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return T(n,{received:n.data,code:S.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:t.data}}get value(){return this._def.value}};Mt.create=(e,t)=>new Mt({value:e,typeName:D.ZodLiteral,...P(t)});a(Ru,"createZodEnum");Lt=class e extends M{static{a(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return T(n,{expected:L.joinValues(r),received:n.parsedType,code:S.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return T(n,{received:n.data,code:S.invalid_enum_value,options:r}),O}return ie(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})}};Lt.create=Ru;$t=class extends M{static{a(this,"ZodNativeEnum")}_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let i=L.objectValues(n);return T(r,{expected:L.joinValues(i),received:r.parsedType,code:S.invalid_type}),O}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=L.objectValues(n);return T(r,{received:r.data,code:S.invalid_enum_value,options:i}),O}return ie(t.data)}get enum(){return this._def.values}};$t.create=(e,t)=>new $t({values:e,typeName:D.ZodNativeEnum,...P(t)});pt=class extends M{static{a(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 T(n,{code:S.invalid_type,expected:A.promise,received:n.parsedType}),O;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return ie(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};pt.create=(e,t)=>new pt({type:e,typeName:D.ZodPromise,...P(t)});_e=class extends M{static{a(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:a(o=>{T(r,o),o.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async c=>{if(n.value==="aborted")return O;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?O:l.status==="dirty"?Et(l.value):n.value==="dirty"?Et(l.value):l});{if(n.value==="aborted")return O;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?O:c.status==="dirty"?Et(c.value):n.value==="dirty"?Et(c.value):c}}if(i.type==="refinement"){let o=a(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?O:(c.status==="dirty"&&n.dirty(),o(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?O:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!lt(o))return O;let c=i.transform(o.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>lt(o)?Promise.resolve(i.transform(o.value,s)).then(c=>({status:n.value,value:c})):O);L.assertNever(i)}};_e.create=(e,t,n)=>new _e({schema:e,typeName:D.ZodEffects,effect:t,...P(n)});_e.createWithPreprocess=(e,t,n)=>new _e({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...P(n)});ge=class extends M{static{a(this,"ZodOptional")}_parse(t){return this._getType(t)===A.undefined?ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ge.create=(e,t)=>new ge({innerType:e,typeName:D.ZodOptional,...P(t)});Pe=class extends M{static{a(this,"ZodNullable")}_parse(t){return this._getType(t)===A.null?ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Pe.create=(e,t)=>new Pe({innerType:e,typeName:D.ZodNullable,...P(t)});Ft=class extends M{static{a(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}};Ft.create=(e,t)=>new Ft({innerType:e,typeName:D.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...P(t)});jt=class extends M{static{a(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 Sn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ue(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ue(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};jt.create=(e,t)=>new jt({innerType:e,typeName:D.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...P(t)});Nn=class extends M{static{a(this,"ZodNaN")}_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return T(r,{code:S.invalid_type,expected:A.nan,received:r.parsedType}),O}return{status:"valid",value:t.data}}};Nn.create=e=>new Nn({typeName:D.ZodNaN,...P(e)});Fk=Symbol("zod_brand"),vr=class extends M{static{a(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}},kr=class e extends M{static{a(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return a(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?O:s.status==="dirty"?(n.dirty(),Et(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?O:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:D.ZodPipeline})}},Ut=class extends M{static{a(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=a(i=>(lt(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Sn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Ut.create=(e,t)=>new Ut({innerType:e,typeName:D.ZodReadonly,...P(t)});a(Su,"cleanParams");a(Iu,"custom");jk={object:pe.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(D||(D={}));Uk=a((e,t={message:`Input not instance of ${e.name}`})=>Iu(n=>n instanceof e,t),"instanceOfType"),Nu=dt.create,Cu=Tt.create,Hk=Nn.create,Bk=At.create,Ou=Rt.create,Gk=It.create,Wk=Tn.create,Kk=Nt.create,Vk=Ct.create,zk=ut.create,qk=Ve.create,Yk=ve.create,Jk=An.create,Xk=ze.create,Zk=pe.create,Qk=pe.strictCreate,ex=Ot.create,tx=Ii.create,nx=Dt.create,rx=De.create,ix=Ni.create,sx=Rn.create,ox=In.create,ax=Ci.create,cx=Pt.create,lx=Mt.create,dx=Lt.create,ux=$t.create,px=pt.create,fx=_e.create,mx=ge.create,hx=Pe.create,gx=_e.createWithPreprocess,yx=kr.create,_x=a(()=>Nu().optional(),"ostring"),bx=a(()=>Cu().optional(),"onumber"),wx=a(()=>Ou().optional(),"oboolean"),vx={string:a(e=>dt.create({...e,coerce:!0}),"string"),number:a(e=>Tt.create({...e,coerce:!0}),"number"),boolean:a(e=>Rt.create({...e,coerce:!0}),"boolean"),bigint:a(e=>At.create({...e,coerce:!0}),"bigint"),date:a(e=>It.create({...e,coerce:!0}),"date")},kx=O});var f={};ee(f,{BRAND:()=>Fk,DIRTY:()=>Et,EMPTY_PATH:()=>gk,INVALID:()=>O,NEVER:()=>kx,OK:()=>ie,ParseStatus:()=>te,Schema:()=>M,ZodAny:()=>ut,ZodArray:()=>ze,ZodBigInt:()=>At,ZodBoolean:()=>Rt,ZodBranded:()=>vr,ZodCatch:()=>jt,ZodDate:()=>It,ZodDefault:()=>Ft,ZodDiscriminatedUnion:()=>Ii,ZodEffects:()=>_e,ZodEnum:()=>Lt,ZodError:()=>ue,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Ci,ZodIntersection:()=>Dt,ZodIssueCode:()=>S,ZodLazy:()=>Pt,ZodLiteral:()=>Mt,ZodMap:()=>Rn,ZodNaN:()=>Nn,ZodNativeEnum:()=>$t,ZodNever:()=>ve,ZodNull:()=>Ct,ZodNullable:()=>Pe,ZodNumber:()=>Tt,ZodObject:()=>pe,ZodOptional:()=>ge,ZodParsedType:()=>A,ZodPipeline:()=>kr,ZodPromise:()=>pt,ZodReadonly:()=>Ut,ZodRecord:()=>Ni,ZodSchema:()=>M,ZodSet:()=>In,ZodString:()=>dt,ZodSymbol:()=>Tn,ZodTransformer:()=>_e,ZodTuple:()=>De,ZodType:()=>M,ZodUndefined:()=>Nt,ZodUnion:()=>Ot,ZodUnknown:()=>Ve,ZodVoid:()=>An,addIssueToContext:()=>T,any:()=>zk,array:()=>Xk,bigint:()=>Bk,boolean:()=>Ou,coerce:()=>vx,custom:()=>Iu,date:()=>Gk,datetimeRegex:()=>Au,defaultErrorMap:()=>We,discriminatedUnion:()=>tx,effect:()=>fx,enum:()=>dx,function:()=>ax,getErrorMap:()=>xn,getParsedType:()=>Oe,instanceof:()=>Uk,intersection:()=>nx,isAborted:()=>Ai,isAsync:()=>Sn,isDirty:()=>Ri,isValid:()=>lt,late:()=>jk,lazy:()=>cx,literal:()=>lx,makeIssue:()=>wr,map:()=>sx,nan:()=>Hk,nativeEnum:()=>ux,never:()=>Yk,null:()=>Vk,nullable:()=>hx,number:()=>Cu,object:()=>Zk,objectUtil:()=>Ko,oboolean:()=>wx,onumber:()=>bx,optional:()=>mx,ostring:()=>_x,pipeline:()=>yx,preprocess:()=>gx,promise:()=>px,quotelessJson:()=>fk,record:()=>ix,set:()=>ox,setErrorMap:()=>hk,strictObject:()=>Qk,string:()=>Nu,symbol:()=>Wk,transformer:()=>fx,tuple:()=>rx,undefined:()=>Kk,union:()=>ex,unknown:()=>qk,util:()=>L,void:()=>Jk});var Jo=_(()=>{Ti();zo();vu();br();Du();Ei()});var se=_(()=>{Jo();Jo()});var Xo,Zo=_(()=>{"use strict";se();Xo=f.object({id:f.string().min(1),title:f.string().min(1).max(200),type:f.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:f.enum(["community","curated"]),lesson_class:f.enum(["general","architecture"]).default("general"),quality_tier:f.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:f.object({source:f.enum(["memory","vault","claude-md"]),source_id:f.string().min(1),migrated_at:f.string(),migrated_from_workspace:f.string().optional()}).optional(),context:f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),summary:f.string().min(1).max(500),problem:f.string().optional(),solution:f.string().optional(),gotchas:f.array(f.string()).default([]),template_body:f.string().min(1).optional(),target_file:f.string().min(1).optional(),submitted_by:f.string().optional(),evidence:f.string().optional(),last_validated_at:f.string().optional(),tool_versions:f.record(f.string(),f.string()).optional(),upvotes:f.number().int().nonnegative().default(0),version:f.number().int().min(1).default(1),changed_at:f.string().optional(),changelog:f.string().max(500).optional(),revision_of:f.string().optional(),org_id:f.string().uuid().optional(),org_name:f.string().optional(),scope:f.literal("private").optional(),body:f.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var xx,Pu=_(()=>{"use strict";se();Zo();xx=Xo.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:f.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:f.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var Mu,Lu,$u,Fu,Qo,ju,Uu,Hu,Sx,Bu=_(()=>{"use strict";se();Mu=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Lu=f.enum(Mu),$u=["new_to_ai_agents","new_to_this_client","experienced"],Fu=f.enum($u),Qo=[{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"}],ju=Qo.map(e=>e.header),Uu=f.object({experience_level:f.array(Fu).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),Hu=f.object({id:f.string().min(1),client:Lu,title:f.string().min(1),last_updated:f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:Uu,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Sx=Hu.extend({body:f.string().min(1)})});var Wu,Oi,Ku,Di,Ex,Tx,Vu,zu,qu,Yu,Pi,Ax,Rx,Gu,Ix,Ju,Nx,Xu=_(()=>{"use strict";se();Wu=["operating_procedure","code_review","communication_style"],Oi=f.enum(Wu),Ku=["info","recommended","required"],Di=f.enum(Ku),Ex=["optional","default_on","mandatory"],Tx=f.enum(Ex),Vu=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],zu=f.enum(Vu),qu=["verify","contribute","mixed"],Yu=f.enum(qu),Pi=f.object({clients:f.array(zu).default([]),stacks:f.array(f.string()).default([]),intents:f.array(Yu).default([])}).default({clients:[],stacks:[],intents:[]}),Ax=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Rx=64,Gu=200,Ix=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Ju=f.object({id:f.string().min(5).max(Rx).regex(Ax,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:Oi,version:f.number().int().min(1),changed_at:Ix,changelog:f.string().max(500).optional(),applies_to:Pi,severity:Di.default("recommended"),disableability:Tx.default("default_on"),summary:f.string().min(1).max(Gu,`summary must be \u2264 ${Gu} chars (rendered as one line in init-push)`),review_gate:f.object({enabled:f.boolean(),min_matched_symbols:f.number().int().min(1).max(8).default(2),hard:f.boolean().default(!1)}).optional(),gateway_gate:f.object({enabled:f.boolean(),deny_tools:f.array(f.string().min(1).max(128)).min(1).max(16),servers:f.array(f.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),Nx=Ju.extend({body:f.string().min(1)})});var ft=_(()=>{"use strict";Zo();Pu();Bu();Xu()});var ea,Mi,ta,Zu,Qu,ep,Cx,tp=_(()=>{"use strict";se();ea=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),Mi=f.number().min(0).max(1).optional(),ta=f.object({type:f.literal("media"),kind:f.enum(["image","video"]),url:f.string().url().max(2048),alt:f.string().max(500).optional(),caption:f.string().max(500).optional(),fog:f.object({top:Mi,right:Mi,bottom:Mi,left:Mi}).optional()}),Zu=f.object({label:f.string().min(1).max(40),color:f.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),Qu=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Zu.optional(),blocks:f.array(f.discriminatedUnion("type",[ea,ta])).max(50)}),ep=f.discriminatedUnion("type",[ea,ta,Qu]),Cx=f.array(ep).max(100)});var np,Ox,rp,ip,Dx,Px,Mx,sp=_(()=>{"use strict";se();np=["free","solo_pro","team","enterprise"],Ox=f.enum(np),rp=["solo_pro","team","enterprise"],ip=f.enum(rp),Dx=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Px=f.object({user_id:f.string().uuid(),tier:ip,reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:Dx.nullable().optional(),auto_revoke_on_stripe:f.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"}),Mx=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var op=_(()=>{"use strict"});var Lx,$x,Fx,ap=_(()=>{"use strict";se();Lx=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),$x=f.object({org_id:f.string().uuid(),seats:f.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:Lx.nullable().optional(),auto_revoke_on_stripe:f.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"}),Fx=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var cp,jx,lp,dp,up,pp,Ux,fp=_(()=>{"use strict";se();cp=f.enum(["info","important","critical"]),jx=f.enum(["pass","warn","fail"]),lp=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),dp=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),up=f.discriminatedUnion("kind",[f.object({kind:f.literal("file-exists"),path:f.string().min(1)}),f.object({kind:f.literal("any-file-exists"),paths:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("any-agent-config")}),f.object({kind:f.literal("file-size-budget"),field:f.enum(["claude_md","readme"]),max_chars:f.number().int().positive()}),f.object({kind:f.literal("readme-section-present"),headers:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("adr-dir-present")}),f.object({kind:f.literal("git-present")}),f.object({kind:f.literal("quality-gates-configured"),pass_if_at_least:f.number().int().min(1).max(4).optional(),warn_if_at_least:f.number().int().min(0).max(4).optional()}),f.object({kind:f.literal("storage-risk-safe"),allow_unknown:f.boolean().optional()}),f.object({kind:f.literal("doc-path-discoverability")})]),pp=f.object({id:f.string().min(1),title:f.string().min(1),severity:cp,weight:f.number().int().positive().max(100),applies_when:dp,check:up,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:lp.optional()}),Ux=f.object({version:f.literal(1),checks:f.array(pp).min(1)})});function Bx(e){if(!Hx.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Li(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 Gx(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var Hx,$i,mp,hp,Me,na,gp,Wx,yp=_(()=>{"use strict";se();Hx=/^\d{4}-\d{2}-\d{2}$/;a(Bx,"isRealDate");$i=f.string().refine(Bx,{message:"expected a real calendar date as YYYY-MM-DD"}),mp=["exact","prefix"],hp=f.enum(mp),Me=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),na=[2e5,272e3],gp=f.object({model_pattern:f.string().min(1).max(100),match_kind:hp,valid_from:$i,valid_to:$i.nullable().optional(),input:Me,output:Me,cache_read:Me,cache_write_5m:Me,cache_write_1h:Me,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Me.optional(),output_above_200k:Me.optional(),cache_read_above_200k:Me.optional(),cache_write_5m_above_200k:Me.optional(),cache_write_1h_above_200k:Me.optional(),context_threshold_tokens:f.number().int().positive().nullable().optional(),source_url:f.string().url().max(500).nullable().optional(),note:f.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=>Li(e)===0||Li(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"||Li(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=>Li(e)===0||e.context_threshold_tokens==null||na.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${na.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});a(Li,"aboveRateCount");a(Gx,"rowKey");Wx=f.object({changelog:f.string().min(1).max(500),as_of:$i,source_url:f.string().url().max(500),rows:f.array(gp).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let o=Gx(i),c=n.get(o);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${o} (first at rows[${c}])`}):n.set(o,s)});let r=new Map;e.rows.forEach((i,s)=>{let o=`${i.model_pattern}|${i.match_kind}`,c=r.get(o)??[];c.push({i:s,r:i}),r.set(o,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,o)=>s.r.valid_from.localeCompare(o.r.valid_from));for(let s=0;s<i.length-1;s++){let o=i[s],c=i[s+1];(!o.r.valid_to||o.r.valid_to>c.r.valid_from)&&t.addIssue({code:f.ZodIssueCode.custom,path:["rows",o.i,"valid_to"],message:`window overlaps the next one for ${o.r.model_pattern} (${o.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var Cn=_(()=>{"use strict"});var xr=_(()=>{"use strict"});var vp=_(()=>{"use strict";xr();Cn()});var kp=_(()=>{"use strict";Cn()});var xp=_(()=>{"use strict";ft();xr();Cn()});var Sp=_(()=>{"use strict";xr();Cn()});var Ep=_(()=>{"use strict";Cn();vp();kp();xp();Sp();xr()});var lS,dS,Tp,uS,Ap,ra,Rp,Ip,Np,Cp,pS,ia=_(()=>{"use strict";se();ft();lS=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,dS=64,Tp=200,uS=1e3,Ap=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),ra=f.enum(["low","medium","high"]),Rp=f.object({owner:f.string().min(1).max(160).optional(),risk_level:ra.optional(),reviewed_at:Ap.optional()}).default({}),Ip=f.object({tags:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),limit:f.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),Np=f.object({lesson_query:Ip,lesson_pins:f.array(f.string()).default([]),lesson_excludes:f.array(f.string()).default([]),convention_ids:f.array(f.string()).default([]),template_ids:f.array(f.string()).default([]),setup_guide_ids:f.array(f.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Cp=f.object({id:f.string().min(6).max(dS).regex(lS,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:Ap,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(Tp,`summary must be \u2264 ${Tp} chars (rendered as one line in skill_index)`),description:f.string().max(uS).optional(),applies_to:Pi,membership:Np,governance:Rp}),pS=Cp.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var Op,Dp,Pp,Mp,Lp,$p,fS,Fp,mS,hS,jp=_(()=>{"use strict";se();ia();Op=f.enum(["maind","agent-skill"]),Dp=f.enum(["ready","needs_attention","blocked"]),Pp=f.enum(["info","important","critical"]),Mp=f.enum(["pass","warn","fail"]),Lp=f.enum(["structure","governance","scope","membership","package","references"]),$p=f.object({id:f.string().min(1),title:f.string().min(1),status:Mp,severity:Pp,category:Lp,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),fS=f.object({lesson_ids:f.array(f.string()).optional(),convention_ids:f.array(f.string()).optional(),template_ids:f.array(f.string()).optional(),setup_guide_ids:f.array(f.string()).optional()}).default({}),Fp=f.object({name:f.string().min(1).max(64),description:f.string().min(1).max(1024),license:f.string().optional(),compatibility:f.union([f.string(),f.array(f.string())]).optional(),metadata:f.record(f.string()).default({}),"allowed-tools":f.union([f.string(),f.array(f.string())]).optional()}).passthrough(),mS=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:Fp,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),hS=f.object({format:Op,subject:f.string().min(1),status:Dp,summary:f.string().min(1),counts:f.object({pass:f.number().int().min(0),warn:f.number().int().min(0),fail:f.number().int().min(0)}),checks:f.array($p),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var sa=_(()=>{"use strict"});var Up,yS,Hp,Bp,Gp,On,_S,Wp,Kp,Vp,zp,qp,Yp,Jp,Xp,bS,Zp,Qp,ef,mt,oa,tf,nf,wS,rf=_(()=>{"use strict";se();ft();sa();Up=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],yS=f.enum(Up),Hp=["verdict","advisory"],Bp=f.enum(Hp),Gp=["block","warn","note"],On=f.enum(Gp),_S=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:Di,scope:Oi,grade:Bp,matched_symbols:f.array(f.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:f.array(f.string().min(1).max(512)).max(64).default([]),summary:f.string().max(2e3),hard:f.boolean().optional()}),Wp=["open","warn","info"],Kp=f.enum(Wp),Vp=["introduced","pre_existing"],zp=f.enum(Vp),qp=["full","partial","none"],Yp=f.enum(qp),Jp=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),rule_id:f.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:Kp,baseline:zp,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Xp=f.object({version:f.literal(1).default(1),actions:f.object({required:On.default("block"),recommended:On.default("warn"),info:On.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:On})).max(64).default([]),risk_flag_action:f.enum(["warn","note","ignore"]).default("warn"),detector_overrides:f.array(f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),action:On,reason:f.string().min(1).max(200)})).max(32).optional()}),bS=Xp.parse({}),Zp=["ran","not_applicable","unavailable","ungraded"],Qp=f.enum(Zp),ef=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),state:Qp}),mt=1e3,oa=f.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),tf=f.object({name:f.string().min(1).max(200),qualified_name:f.string().min(1).max(512).optional(),kind:f.string().min(1).max(64).optional(),language:f.string().min(1).max(32).optional(),change:f.enum(["added","modified","co_located"]).optional(),changed_line_count:f.number().int().min(0).max(1e4).optional()}),nf=f.object({base_kind:f.enum(["uncommitted","ref"]),changed_file_count:f.number().int().min(0),stale_file_count:f.number().int().min(0),unindexed_file_count:f.number().int().min(0).optional(),truncated:f.boolean(),hunk_coverage:f.enum(["full","partial","none"]),detector_coverage:Yp}),wS=f.object({changed_symbols:f.array(tf).max(mt),risk_flags:f.array(f.string().max(64)).max(16),detector_findings:f.array(Jp).max(64),detector_runs:f.array(ef).min(1).max(32),diff_stats:nf,commit_sha:oa.optional(),base_sha:oa.optional(),merge_base_sha:oa.optional(),dirty:f.boolean().optional(),code_index_version:f.string().min(1).max(32).optional()})});var sf,of,af,cf,lf,aa,vS,kS,df,uf,pf,ff,mf,xS,SS,hf,gf,yf,ES,_f=_(()=>{"use strict";se();sf=14,of=14,af=14,cf=1,lf=365,aa=f.number().int().min(cf).max(lf),vS=["propose","direct"],kS="propose",df=["propose","direct"],uf="propose",pf=["propose","direct"],ff="propose",mf=["off","propose","direct"],xS=["member","admin","owner"],SS="member",hf="off",gf="en",yf=f.object({version:f.literal(1).default(1),at_risk_days:aa.default(sf),stagnation_days:aa.default(of),agent_date_mode:f.enum(vS).default(kS),health_manual_ttl_days:aa.default(af),agent_event_mode:f.enum(df).default(uf),agent_update_mode:f.enum(pf).default(ff),agent_pull_mode:f.enum(mf).default(hf),org_wide_authoring_min_role:f.enum(xS).default(SS),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(gf)}),ES=yf.parse({})});var bf,TS,wf=_(()=>{"use strict";se();bf=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),TS=bf.parse({})});var vf,kf,AS,RS,xf=_(()=>{"use strict";se();vf=f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),kf=f.object({id:f.string().uuid(),user_id:f.string().uuid(),project:f.string().max(200).nullable().optional(),title:f.string().min(1).max(200),body:f.string().min(1).max(2e4),context:vf.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:f.string(),updated_at:f.string(),last_recalled_at:f.string().nullable().optional(),recall_count:f.number().int().nonnegative().default(0),graduated_draft_id:f.string().uuid().nullable().optional(),deleted_at:f.string().nullable().optional()}),AS=kf.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:f.number()}),RS=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var Sf=_(()=>{"use strict"});function Fi(e){let t=[],n=null;return e.split(`
|
|
3
|
+
`).forEach((r,i)=>{let s=r.trim(),o=r.length-r.trimStart().length;if(n!==null){if(s===""||o>n)return;n=null}if(s===""||s.startsWith("#"))return;let c=NS.exec(r);if(!c)return;let l=c[3]??"";if(IS.has(l.trim())){n=o;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:i+1,value:d})}),t}var IS,NS,Ef=_(()=>{"use strict";IS=new Set(["|",">","|-",">-","|+",">+"]),NS=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;a(Fi,"plainScalarViolations")});function Er(e,t){let n=a(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(p=>{let h=Number(p);return Number.isFinite(h)?h:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,i]=n(e),[s,o]=n(t);for(let c=0;c<Math.max(r.length,s.length);c+=1){let l=(r[c]??0)-(s[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&o.length===0)return 0;if(i.length===0)return 1;if(o.length===0)return-1;for(let c=0;c<Math.max(i.length,o.length);c+=1){let l=i[c],d=o[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 h=Number(l)-Number(d);if(h!==0)return h<0?-1:1}else{if(u!==p)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var Tf=_(()=>{"use strict";a(Er,"compareSemver")});var Tr=_(()=>{"use strict";ft();tp();ft();ft();sp();op();ap();fp();yp();Ep();ft();ia();jp();rf();_f();wf();xf();Sf();sa();Ef();Tf()});function Af(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
4
|
+
`).slice(0,1e3)}var Rf=_(()=>{"use strict";a(Af,"nodeEmbedText")});var ca,la=_(()=>{"use strict";ca=["function","method","class","interface","enum","type_alias"]});function If(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let o=0;o<n;o++){let c=e[o],l=t[o];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}var Nf=_(()=>{"use strict";a(If,"cosineSimilarity")});import{execFileSync as CS}from"node:child_process";import{createHash as OS}from"node:crypto";import{readFileSync as DS}from"node:fs";import{posix as ke}from"node:path";function Cf(e){let t=OS("sha256"),n=[];try{n=CS("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
5
|
+
`).filter(l=>PS.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,i=a(l=>{if(r.has(l))return r.get(l);try{let d=DS(ke.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),s=[],o=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=Of(l,i,0),u=ke.dirname(l)==="."?"":ke.dirname(l);l.endsWith("tsconfig.json")&&o.set(u,d),d.paths&&s.push({dir:d.pathsDir??u,baseUrl:d.baseUrl,paths:d.paths})}let c=[];for(let l of n.filter(d=>d.endsWith("package.json"))){let d=Df(i(l));if(!d||typeof d.name!="string")continue;let u=ke.dirname(l)==="."?"":ke.dirname(l),p=o.get(u);c.push({name:d.name,dir:u,exports:d.exports,main:typeof d.main=="string"?d.main:void 0,module:typeof d.module=="string"?d.module:void 0,types:typeof d.types=="string"?d.types:void 0,outDir:p?.outDir,rootDir:p?.rootDir})}for(let l of[...r.keys()].sort())t.update(l).update("\0").update(r.get(l)).update("\0");return{config:{packages:c,tsconfigs:s},fingerprint:t.digest("hex")}}function Of(e,t,n){let r=Df(t(e));if(!r)return{};let i=ke.dirname(e)==="."?"":ke.dirname(e),s={},o=r.extends;if(typeof o=="string"&&o.startsWith(".")&&n<4){let d=ke.normalize(ke.join(i,o.endsWith(".json")?o:o+".json"));s=Of(d,t,n+1)}let c=r.compilerOptions??{},l={...s};return typeof c.outDir=="string"&&(l.outDir=ke.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=ke.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 Df(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(aS(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function aS(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let s=r+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e[s]==="}"||e[s]==="]")continue}t+=i}return t}var oS,_f=_(()=>{"use strict";oS=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;a(hf,"loadModuleConfig");a(gf,"compilerFacts");a(yf,"parseJsonc");a(aS,"dropTrailingCommas")});import{posix as xe}from"node:path";function Er(e,t){let n=xe.normalize(e).replace(/^\.\//,""),r=[],i=Fi.some(c=>n.endsWith(c));i&&r.push(n);let s=/\.d\.(m|c)?ts$/.exec(n);s&&r.push(n.slice(0,-s[0].length)+".ts",n.slice(0,-s[0].length)+".tsx");let o=/\.(js|jsx|mjs|cjs)$/.exec(n);if(o){let c=n.slice(0,-o[0].length);for(let l of Fi)r.push(c+l)}if(!i&&!s){for(let c of Fi)r.push(n+c);for(let c of Fi)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function wf(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let s=wf(i,t);if(s)return s}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return Tr(n[t]);for(let i of r){let s=i.indexOf("*");if(s<0)continue;let o=i.slice(0,s),c=i.slice(s+1);if(t.startsWith(o)&&t.endsWith(c)){let l=Tr(n[i]);if(l)return l.replace("*",t.slice(o.length,t.length-c.length))}}return null}return t==="."?Tr(e):null}function Tr(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Tr(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of cS)if(n in t){let r=Tr(t[n]);if(r)return r}}return null}function lS(e,t){let n=xe.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=xe.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=xe.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(xe.join(s,n.slice(i.length+1)))}return r}var Fi,cS,ea,bf,Cn,ta=_(()=>{"use strict";Fi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],cS=["import","default","node","require","types"],ea={kind:"unresolved"},bf={kind:"external"};a(Er,"resolvePathCandidates");Cn=class{static{a(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=`${xe.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let s=Er(xe.join(xe.dirname(t),n),this.files);return s?{kind:"file",path:s}:ea}if(n.startsWith("node:"))return bf;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(s=>n===s.name||n.startsWith(s.name+"/"));if(i){let s=n===i.name?".":"./"+n.slice(i.name.length+1),o=this.viaPackage(i,s);return o?{kind:"file",path:o}:ea}return bf}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(s=>s.dir===""||t.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=xe.join(r.dir,r.baseUrl??".");for(let[s,o]of Object.entries(r.paths)){let c=s.indexOf("*"),l=null;if(c<0)s===n&&(l="");else{let d=s.slice(0,c),u=s.slice(c+1);n.startsWith(d)&&n.endsWith(u)&&n.length>=d.length+u.length&&(l=n.slice(d.length,n.length-u.length))}if(l!==null){for(let d of o){let u=Er(xe.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return ea}}return null}viaPackage(t,n){let r=[],i=wf(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let s of[t.module,t.main,t.types])s&&r.push(s);r.push("index")}else r.push(n);for(let s of r)for(let o of lS(t,s)){let c=Er(xe.join(t.dir,o),this.files);if(c)return c}return null}};a(wf,"exportTarget");a(Tr,"conditionTarget");a(lS,"toSource")});function mt(e){return`${e}#<module>`}function Oe(e,t,n){return`${e}#${t}:${n}`}var On=_(()=>{"use strict";a(mt,"moduleKey");a(Oe,"symbolKey")});import{posix as vf}from"node:path";function xf(e){let t=new Map,n=new Set,r=new Map,i=new Map,s=new Set,o=a((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),s.add(c.nodeKey),dS.has(c.kind)&&o(t,c.name,c.nodeKey),c.kind==="method"&&o(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Oe(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),o(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:s}}function Sf(e,t,n=new Cn({packages:[],tsconfigs:[]},t.files)){let r=mS(),i=new na(e,t,n);for(let s of e)s.language==="python"?hS(s.filePath,s.refs,s.imports,t,r.push):i.resolveFile(s,r.push);return r.edges}function fS(e,t,n){return t.startsWith(".")?Er(vf.join(vf.dirname(e),t),n):null}function mS(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let s=`${n} ${r} ${i}`;e.has(s)||(e.add(s),t.push({srcKey:n,dstKey:r,kind:i}))}}}function hS(e,t,n,r,i){for(let s of t){let o=r.nameToKeys.get(s.targetName);!o||o.length!==1||i(s.fromKey,o[0],s.kind)}for(let s of n){let o=fS(e,s.specifier,r.files);o&&i(s.fromModuleKey,mt(o),"imports")}}function gS(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return Oe(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var dS,kf,uS,pS,na,Ef=_(()=>{"use strict";On();ta();dS=new Set(["function","method","class","interface","enum","type_alias"]),kf=["function","class","variable","enum","interface","type_alias"],uS=8,pS=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"]);a(xf,"buildResolutionIndex");a(Sf,"resolveCrossFileEdges");a(fS,"resolveImportTarget");a(mS,"edgeCollector");a(hS,"legacyFacts");a(gS,"classKeyOfMethod");na=class{static{a(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let s=new Map;for(let o of i.imports)o.localName&&o.importedName&&s.set(o.localName,{specifier:o.specifier,importedName:o.importedName});this.bindings.set(i.filePath,s);for(let o of i.refs){if(o.kind==="calls")continue;let c=this.heritage.get(o.fromKey);c?c.push({file:i.filePath,ref:o}):this.heritage.set(o.fromKey,[{file:i.filePath,ref:o}])}}}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(mt(t.filePath),mt(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let o=this.resolveLocal(t,n.targetName,0);return o?.kind==="symbol"?o.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 o=r.endsWith(".*"),c=o?r.slice(0,-2):r;if(pS.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(!o){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),s=(this.index.methodsByName.get(n.targetName)??[]).filter(o=>{let c=gS(o);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return s.length===1?s[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),s;if(i<0)s=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);s=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(s?.kind!=="symbol")return null;let o=s.key.endsWith(":class")?[s.key]:[...this.implementers(s.key)];return o.length!==1?null:this.methodOf(o[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=Oe(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let s of this.supertypes(t)){if(!s.endsWith(":class"))continue;let o=s.indexOf("#"),c=Oe(s.slice(0,o),`${s.slice(o+1,s.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let s=this.resolveRef(r,i);if(s){n.add(s);for(let o of this.supertypes(s))n.add(o)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let s=t.slice(0,r),o=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?o.slice(0,o.lastIndexOf(".")):c==="class"?o:null;if(!l)return null;let d=Oe(s,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>uS)return null;this.memo.set(i,null);let s=this.computeExport(t,n,r);return this.memo.set(i,s),s}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let s=this.topLevel(t,n);if(s)return s;let o=this.bindings.get(t)?.get(n);if(o)return this.resolveBinding(t,o,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=a(s=>{let o=kf.indexOf(s.slice(s.lastIndexOf(":")+1));return o<0?kf.length:o},"rank");return{kind:"symbol",key:[...r].sort((s,o)=>i(s)-i(o))[0]}}}});function ji(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 ra(e){return e.toLowerCase().endsWith(".d.ts")}var Ui=_(()=>{"use strict";a(ji,"languageForPath");a(ra,"isSkippablePath")});import{appendFileSync as yS,existsSync as Tf,mkdirSync as _S,readFileSync as bS}from"node:fs";import{join as wS}from"node:path";function Ar(e,t={}){try{if(!Tf(e)){if(!t.create)return"skipped";_S(e,{recursive:!0})}let n=wS(e,".gitignore"),r=Tf(n)?bS(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=Hi.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let o=r===null?[...vS,...s]:s,c=r&&!r.endsWith(`
|
|
7
|
+
`}else if(i==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=i}try{let r=JSON.parse(MS(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function MS(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let s=r+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e[s]==="}"||e[s]==="]")continue}t+=i}return t}var PS,Pf=_(()=>{"use strict";PS=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;a(Cf,"loadModuleConfig");a(Of,"compilerFacts");a(Df,"parseJsonc");a(MS,"dropTrailingCommas")});import{posix as xe}from"node:path";function Ar(e,t){let n=xe.normalize(e).replace(/^\.\//,""),r=[],i=ji.some(c=>n.endsWith(c));i&&r.push(n);let s=/\.d\.(m|c)?ts$/.exec(n);s&&r.push(n.slice(0,-s[0].length)+".ts",n.slice(0,-s[0].length)+".tsx");let o=/\.(js|jsx|mjs|cjs)$/.exec(n);if(o){let c=n.slice(0,-o[0].length);for(let l of ji)r.push(c+l)}if(!i&&!s){for(let c of ji)r.push(n+c);for(let c of ji)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function Lf(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let s=Lf(i,t);if(s)return s}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return Rr(n[t]);for(let i of r){let s=i.indexOf("*");if(s<0)continue;let o=i.slice(0,s),c=i.slice(s+1);if(t.startsWith(o)&&t.endsWith(c)){let l=Rr(n[i]);if(l)return l.replace("*",t.slice(o.length,t.length-c.length))}}return null}return t==="."?Rr(e):null}function Rr(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Rr(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of LS)if(n in t){let r=Rr(t[n]);if(r)return r}}return null}function $S(e,t){let n=xe.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=xe.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=xe.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(xe.join(s,n.slice(i.length+1)))}return r}var ji,LS,da,Mf,Dn,ua=_(()=>{"use strict";ji=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],LS=["import","default","node","require","types"],da={kind:"unresolved"},Mf={kind:"external"};a(Ar,"resolvePathCandidates");Dn=class{static{a(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=`${xe.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let s=Ar(xe.join(xe.dirname(t),n),this.files);return s?{kind:"file",path:s}:da}if(n.startsWith("node:"))return Mf;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(s=>n===s.name||n.startsWith(s.name+"/"));if(i){let s=n===i.name?".":"./"+n.slice(i.name.length+1),o=this.viaPackage(i,s);return o?{kind:"file",path:o}:da}return Mf}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(s=>s.dir===""||t.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=xe.join(r.dir,r.baseUrl??".");for(let[s,o]of Object.entries(r.paths)){let c=s.indexOf("*"),l=null;if(c<0)s===n&&(l="");else{let d=s.slice(0,c),u=s.slice(c+1);n.startsWith(d)&&n.endsWith(u)&&n.length>=d.length+u.length&&(l=n.slice(d.length,n.length-u.length))}if(l!==null){for(let d of o){let u=Ar(xe.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return da}}return null}viaPackage(t,n){let r=[],i=Lf(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let s of[t.module,t.main,t.types])s&&r.push(s);r.push("index")}else r.push(n);for(let s of r)for(let o of $S(t,s)){let c=Ar(xe.join(t.dir,o),this.files);if(c)return c}return null}};a(Lf,"exportTarget");a(Rr,"conditionTarget");a($S,"toSource")});function ht(e){return`${e}#<module>`}function Le(e,t,n){return`${e}#${t}:${n}`}var Pn=_(()=>{"use strict";a(ht,"moduleKey");a(Le,"symbolKey")});import{posix as $f}from"node:path";function jf(e){let t=new Map,n=new Set,r=new Map,i=new Map,s=new Set,o=a((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),s.add(c.nodeKey),FS.has(c.kind)&&o(t,c.name,c.nodeKey),c.kind==="method"&&o(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Le(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),o(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:s}}function Uf(e,t,n=new Dn({packages:[],tsconfigs:[]},t.files)){let r=BS(),i=new pa(e,t,n);for(let s of e)s.language==="python"?GS(s.filePath,s.refs,s.imports,t,r.push):i.resolveFile(s,r.push);return r.edges}function HS(e,t,n){return t.startsWith(".")?Ar($f.join($f.dirname(e),t),n):null}function BS(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let s=`${n} ${r} ${i}`;e.has(s)||(e.add(s),t.push({srcKey:n,dstKey:r,kind:i}))}}}function GS(e,t,n,r,i){for(let s of t){let o=r.nameToKeys.get(s.targetName);!o||o.length!==1||i(s.fromKey,o[0],s.kind)}for(let s of n){let o=HS(e,s.specifier,r.files);o&&i(s.fromModuleKey,ht(o),"imports")}}function WS(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return Le(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var FS,Ff,jS,US,pa,Hf=_(()=>{"use strict";Pn();ua();FS=new Set(["function","method","class","interface","enum","type_alias"]),Ff=["function","class","variable","enum","interface","type_alias"],jS=8,US=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"]);a(jf,"buildResolutionIndex");a(Uf,"resolveCrossFileEdges");a(HS,"resolveImportTarget");a(BS,"edgeCollector");a(GS,"legacyFacts");a(WS,"classKeyOfMethod");pa=class{static{a(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let s=new Map;for(let o of i.imports)o.localName&&o.importedName&&s.set(o.localName,{specifier:o.specifier,importedName:o.importedName});this.bindings.set(i.filePath,s);for(let o of i.refs){if(o.kind==="calls")continue;let c=this.heritage.get(o.fromKey);c?c.push({file:i.filePath,ref:o}):this.heritage.set(o.fromKey,[{file:i.filePath,ref:o}])}}}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(ht(t.filePath),ht(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let o=this.resolveLocal(t,n.targetName,0);return o?.kind==="symbol"?o.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 o=r.endsWith(".*"),c=o?r.slice(0,-2):r;if(US.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(!o){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),s=(this.index.methodsByName.get(n.targetName)??[]).filter(o=>{let c=WS(o);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return s.length===1?s[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),s;if(i<0)s=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);s=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(s?.kind!=="symbol")return null;let o=s.key.endsWith(":class")?[s.key]:[...this.implementers(s.key)];return o.length!==1?null:this.methodOf(o[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=Le(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let s of this.supertypes(t)){if(!s.endsWith(":class"))continue;let o=s.indexOf("#"),c=Le(s.slice(0,o),`${s.slice(o+1,s.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let s=this.resolveRef(r,i);if(s){n.add(s);for(let o of this.supertypes(s))n.add(o)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let s=t.slice(0,r),o=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?o.slice(0,o.lastIndexOf(".")):c==="class"?o:null;if(!l)return null;let d=Le(s,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>jS)return null;this.memo.set(i,null);let s=this.computeExport(t,n,r);return this.memo.set(i,s),s}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let s=this.topLevel(t,n);if(s)return s;let o=this.bindings.get(t)?.get(n);if(o)return this.resolveBinding(t,o,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=a(s=>{let o=Ff.indexOf(s.slice(s.lastIndexOf(":")+1));return o<0?Ff.length:o},"rank");return{kind:"symbol",key:[...r].sort((s,o)=>i(s)-i(o))[0]}}}});function Ui(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 fa(e){return e.toLowerCase().endsWith(".d.ts")}var Hi=_(()=>{"use strict";a(Ui,"languageForPath");a(fa,"isSkippablePath")});import{appendFileSync as KS,existsSync as Bf,mkdirSync as VS,readFileSync as zS}from"node:fs";import{join as qS}from"node:path";function Ir(e,t={}){try{if(!Bf(e)){if(!t.create)return"skipped";VS(e,{recursive:!0})}let n=qS(e,".gitignore"),r=Bf(n)?zS(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=Bi.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let o=r===null?[...YS,...s]:s,c=r&&!r.endsWith(`
|
|
8
8
|
`)?`
|
|
9
|
-
`:"";return
|
|
9
|
+
`:"";return KS(n,c+o.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),h=p.indexOf(" -> ");h>=0&&(p=p.slice(h+4)),p=
|
|
15
|
-
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=
|
|
16
|
-
`),"norm"),l=c(s),d=c(o);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||o.has(u))&&o.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:o,coverage:c}}function
|
|
19
|
-
`)){if(l.startsWith("diff --git ")){c(),s=!1,o=!1;continue}if(l.startsWith("new file mode")){o=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:o?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=
|
|
20
|
-
`),v=Ff(y[0]??"");if(!v)continue;let w=y.slice(1).filter(b=>b.trim().length>0).length;m.push({sha:v.sha,dateIso:v.dateIso,authorName:v.authorName,subject:v.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,zi),truncated:m.length>zi}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:o.length>ua}}var LS,$S,jf,ua,zi,Lf,Uf,fa=_(()=>{"use strict";ae();LS="",$S="\0",jf=200,ua=50,zi=100,Lf="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",Uf=10;a(pa,"aggregateHistoryContext");a(FS,"clamp");a($f,"splitRecords");a(Ff,"parseHistoryRecord");a(jS,"aggregateOwnership");a(Hf,"readFileHistory")});import{execFileSync as US}from"node:child_process";import{readdirSync as HS,statSync as Gf}from"node:fs";import{isAbsolute as GS,join as ma,relative as BS,resolve as WS}from"node:path";function VS(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function zS(e,t){try{let n=US("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 qS(e){let t;try{t=HS(e)}catch{return null}for(let n of t.filter(VS))try{let r=Gf(ma(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function YS(e){try{return Gf(e).isDirectory()}catch{return!1}}function JS(e,t){let n=BS(e,t);return!n||n.startsWith("..")?t:n}function ha(e){let t=KS.filter(c=>YS(ma(e,c))),n=zS(e,"core.hooksPath"),r=n?GS(n)?n:WS(e,n):ma(e,".git","hooks"),i=JS(e,r),s=qS(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let o=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:o,hookDirs:t,hooksPath:n,effectiveDir:i}}function ga(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 KS,ya=_(()=>{"use strict";KS=[".githooks",".husky"];a(VS,"isRealHook");a(zS,"gitConfig");a(qS,"hasExecutableHook");a(YS,"isDir");a(JS,"displayPath");a(ha,"resolveHookState");a(ga,"describeHookState")});import{posix as Bf}from"node:path";function Dn(e){let t=XS.exec(e);return t?t[1]:null}function Ke(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Ht(e,t){let n=A(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=a(s=>!t||t.length===0?!0:t.some(o=>{let c=o.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let o=Bf.basename(s),c=Dn(o);if(c===null)continue;let l=Bf.dirname(s),d=i.get(l)??[];d.push({path:s,name:o,version:c}),i.set(l,d)}return[...i.entries()].map(([s,o])=>({dir:s,files:o.sort((c,l)=>Ke(c.version,l.version))})).sort((s,o)=>s.dir.localeCompare(o.dir))}function Ir(e){let t=A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var XS,Nr=_(()=>{"use strict";ae();XS=/^(\d+)_.+\.sql$/;a(Dn,"parseMigrationVersion");a(Ke,"compareVersions");a(Ht,"discoverSupabaseProjects");a(Ir,"resolveDefaultBranch")});import{execFileSync as ZS}from"node:child_process";import{existsSync as se,readFileSync as gt,readdirSync as qi,statSync as ba}from"node:fs";import{posix as $}from"node:path";function nE(e,t){let n=(()=>{let i=A(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=$.dirname(e);for(let i=0;i<8&&r&&r!==$.dirname(r);i++){if(se($.join(r,".git"))){let s=(()=>{let c=A(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&va(n,s))){let c=rE(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=$.dirname(r)}return null}function rE(e,t){let n=[];for(let r of eE){let i;try{i=qi($.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let o=`${r}/${s}`,c=$.join(e,o),l=$.join(t,o);try{let d=ba(c),u=ba(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(o);continue}if(d.size>tE)continue;gt(c).equals(gt(l))||n.push(o)}catch{continue}}}return n.sort()}function Jf(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let s=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(s){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!s&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${ka}.`})}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 ${$.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=a(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 o=iE(e.hooks);return o&&t.push(o),sE(t)}function iE(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:ga(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 sE(e){return[...e].sort((t,n)=>Wf[t.status]-Wf[n.status]||t.id.localeCompare(n.id))}function Xf(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Ve(e){let t=e?.trim();return t||null}function oE(e){let t=Ve(A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function aE(e){let t=Ve(A(e,["rev-parse","--git-dir"]));if(!t)return null;let n=$.isAbsolute(t)?t:$.join(e,t);return se($.join(n,"rebase-merge"))||se($.join(n,"rebase-apply"))?"rebase":se($.join(n,"MERGE_HEAD"))?"merge":se($.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function cE(e){let t=[],n=null,r=a(()=>{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(
|
|
25
|
-
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let o=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);o?t.push(o[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=$.join(e,"package.json");if(
|
|
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)||s("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...o.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 s=/(\d+\.\d+\.\d+)/.exec(i);s&&t.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":
|
|
32
|
-
`)
|
|
33
|
-
|
|
34
|
-
`).
|
|
11
|
+
`),r===null?"created":"appended"}catch{return"skipped"}}var Bi,ma,YS,Gi=_(()=>{"use strict";Bi=["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"],ma=["# 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).'],YS=ma;a(Ir,"ensureMaindLocalIgnore")});import{execFileSync as JS}from"node:child_process";import{createHash as XS}from"node:crypto";import{readFileSync as ZS,readdirSync as QS,statSync as eE}from"node:fs";import{posix as ga,sep as Gf}from"node:path";function R(e,t){try{return JS("git",[...tE,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function nE(e){return Gf==="/"?e:e.split(Gf).join("/")}function Wi(e){let t=[];for(let n of e){let r=nE(n).trim();if(!r||fa(r))continue;let i=Ui(r);i&&t.push({path:r,language:i})}return t}function Kf(e){return Wi(e)}function Vf(e){let t=gt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Wi(t.split(`
|
|
12
|
+
`));let n=[];return zf(e,"",n),Wi(n)}function zf(e,t,n){let r;try{r=QS(ga.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Wf.has(i.name)||Wf.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?zf(e,s,n):i.isFile()&&n.push(s)}}function ya(e,t){return _a(e,t)??t}function _a(e,t){let n=R(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Ki(e,t={}){if(Nr(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?ya(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=gt(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map;for(let c of s.split(`
|
|
13
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=ha((l.length>=3?l[l.length-1]:l[1]).trim());u&&(d==="A"||d==="C"?o.set(u,"added"):d==="R"?o.set(u,"renamed"):o.set(u,"modified"))}if(n){let c=gt(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),h=p.indexOf(" -> ");h>=0&&(p=p.slice(h+4)),p=ha(p),!(!p||o.has(p))&&(d==="?"||d==="A"||u==="A"?o.set(p,"added"):d==="R"?o.set(p,"renamed"):o.set(p,"modified"))}}return o}function ha(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function ba(e,t={}){let n=Ki(e,t);return n===null?null:Wi(n.keys())}function qf(e,t){try{let n=eE(ga.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Vi(e){return XS("sha256").update(e).digest("hex")}function Nr(e){return gt(e,["rev-parse","HEAD"])?.trim()??null}function zi(e,t){return gt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function wa(e){let t=gt(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=rE(e);return n.some(i=>r===null||!iE(e,i,r))}function rE(e){let t=gt(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function iE(e,t,n){let r=t[0],i=t[1];if(ha(t.slice(3))!==n)return!1;let s;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))s="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let p=gt(e,["show",`HEAD:${n}`]);if(p===null)return!1;s=p}else return!1;let o;try{o=ZS(ga.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=a(p=>p.replace(/\r\n/g,`
|
|
16
|
+
`),"norm"),l=c(s),d=c(o);if(!d.startsWith(l))return!1;let u=new Set([...Bi,...ma]);return d.slice(l.length).split(`
|
|
17
|
+
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var Wf,tE,gt,ce=_(()=>{"use strict";Hi();Gi();Wf=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),tE=["-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"];a(R,"runGit");gt=R;a(nE,"toPosix");a(Wi,"classify");a(Kf,"classifyPaths");a(Vf,"discoverSourceFiles");a(zf,"walk");a(ya,"resolveDiffBase");a(_a,"resolveMergeBase");a(Ki,"enumerateChangedPaths");a(ha,"unquote");a(ba,"changedSourceFiles");a(qf,"statFile");a(Vi,"hashContent");a(Nr,"headCommit");a(zi,"resolveCommitSha");a(wa,"isWorktreeDirty");a(rE,"toolIgnoreRepoPath");a(iE,"isToolOnlyIgnoreChange")});function Jf(e,t={}){if(R(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?ya(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=R(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map,c="full";if(Buffer.byteLength(s,"utf8")>sE?c="none":lE(s,o,()=>{c="partial"}),n){let l=R(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||o.has(u))&&o.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:o,coverage:c}}function lE(e,t,n){let r=null,i=0,s=!1,o=!1,c=a(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
19
|
+
`)){if(l.startsWith("diff --git ")){c(),s=!1,o=!1;continue}if(l.startsWith("new file mode")){o=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:o?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=cE.exec(l);if(d){if(i++,i>oE){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<aE&&r.addedLines.push(l.slice(1))}c()}var sE,oE,aE,Yf,cE,Xf=_(()=>{"use strict";ce();sE=16*1024*1024,oE=500,aE=4e3,Yf=256*1024,cE=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;a(Jf,"changedHunks");a(lE,"parseUnifiedDiff")});function ka(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let o of e.history){let c=o.ownership?.commitsInWindow??o.lastCommits.length;c>=nm&&r++,c>i&&(i=c);for(let d of o.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=o.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>s&&(s=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}function pE(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Qf(e){return e.split(dE).filter(t=>t.trim().length>0)}function em(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(uE);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function fE(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 rm(e,t,n={}){let r=pE(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,tm),o=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=o.slice(0,va),l=[];for(let u of c){let p=R(e,["log","-n",String(s),Zf,"--",u]),h=p===null?[]:Qf(p).map(em).filter(m=>m!==null);l.push({path:u,lastCommits:h.slice(0,r),ownership:i?{topAuthors:fE(h),commitsInWindow:h.length}:null})}let d=null;if(n.since){let u=zi(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],h=R(e,["log",...p,"-n",String(qi+1),Zf,"--name-only","--",...c]),m=[];if(h!==null)for(let g of Qf(h)){let y=g.split(`
|
|
20
|
+
`),v=em(y[0]??"");if(!v)continue;let b=y.slice(1).filter(k=>k.trim().length>0).length;m.push({sha:v.sha,dateIso:v.dateIso,authorName:v.authorName,subject:v.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,qi),truncated:m.length>qi}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:o.length>va}}var dE,uE,tm,va,qi,Zf,nm,xa=_(()=>{"use strict";ce();dE="",uE="\0",tm=200,va=50,qi=100,Zf="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",nm=10;a(ka,"aggregateHistoryContext");a(pE,"clamp");a(Qf,"splitRecords");a(em,"parseHistoryRecord");a(fE,"aggregateOwnership");a(rm,"readFileHistory")});import{execFileSync as mE}from"node:child_process";import{readdirSync as hE,statSync as im}from"node:fs";import{isAbsolute as gE,join as Sa,relative as yE,resolve as _E}from"node:path";function wE(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function vE(e,t){try{let n=mE("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 kE(e){let t;try{t=hE(e)}catch{return null}for(let n of t.filter(wE))try{let r=im(Sa(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function xE(e){try{return im(e).isDirectory()}catch{return!1}}function SE(e,t){let n=yE(e,t);return!n||n.startsWith("..")?t:n}function Ea(e){let t=bE.filter(c=>xE(Sa(e,c))),n=vE(e,"core.hooksPath"),r=n?gE(n)?n:_E(e,n):Sa(e,".git","hooks"),i=SE(e,r),s=kE(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let o=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:o,hookDirs:t,hooksPath:n,effectiveDir:i}}function Ta(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 bE,Aa=_(()=>{"use strict";bE=[".githooks",".husky"];a(wE,"isRealHook");a(vE,"gitConfig");a(kE,"hasExecutableHook");a(xE,"isDir");a(SE,"displayPath");a(Ea,"resolveHookState");a(Ta,"describeHookState")});import{posix as sm}from"node:path";function Mn(e){let t=EE.exec(e);return t?t[1]:null}function qe(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Ht(e,t){let n=R(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=a(s=>!t||t.length===0?!0:t.some(o=>{let c=o.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let o=sm.basename(s),c=Mn(o);if(c===null)continue;let l=sm.dirname(s),d=i.get(l)??[];d.push({path:s,name:o,version:c}),i.set(l,d)}return[...i.entries()].map(([s,o])=>({dir:s,files:o.sort((c,l)=>qe(c.version,l.version))})).sort((s,o)=>s.dir.localeCompare(o.dir))}function Cr(e){let t=R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var EE,Or=_(()=>{"use strict";ce();EE=/^(\d+)_.+\.sql$/;a(Mn,"parseMigrationVersion");a(qe,"compareVersions");a(Ht,"discoverSupabaseProjects");a(Cr,"resolveDefaultBranch")});import{execFileSync as TE}from"node:child_process";import{existsSync as oe,readFileSync as yt,readdirSync as Yi,statSync as Ia}from"node:fs";import{posix as $}from"node:path";function NE(e,t){let n=(()=>{let i=R(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=$.dirname(e);for(let i=0;i<8&&r&&r!==$.dirname(r);i++){if(oe($.join(r,".git"))){let s=(()=>{let c=R(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&Ca(n,s))){let c=CE(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=$.dirname(r)}return null}function CE(e,t){let n=[];for(let r of RE){let i;try{i=Yi($.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let o=`${r}/${s}`,c=$.join(e,o),l=$.join(t,o);try{let d=Ia(c),u=Ia(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(o);continue}if(d.size>IE)continue;yt(c).equals(yt(l))||n.push(o)}catch{continue}}}return n.sort()}function pm(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let s=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(s){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!s&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${Oa}.`})}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 ${$.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=a(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 o=OE(e.hooks);return o&&t.push(o),DE(t)}function OE(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:Ta(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 DE(e){return[...e].sort((t,n)=>om[t.status]-om[n.status]||t.id.localeCompare(n.id))}function fm(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Ye(e){let t=e?.trim();return t||null}function PE(e){let t=Ye(R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function ME(e){let t=Ye(R(e,["rev-parse","--git-dir"]));if(!t)return null;let n=$.isAbsolute(t)?t:$.join(e,t);return oe($.join(n,"rebase-merge"))||oe($.join(n,"rebase-apply"))?"rebase":oe($.join(n,"MERGE_HEAD"))?"merge":oe($.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function LE(e){let t=[],n=null,r=a(()=>{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 $E(e){let t=$.join(e,Oa);if(!oe(t))return[];try{return yt(t,"utf8").split(`
|
|
22
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function FE(e){try{return Ht(e).map(t=>$.join($.dirname(t.dir),"config.toml"))}catch{return[]}}function jE(e){let t=R(e,["ls-files","-z","--",...AE]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=um[$.basename(r)];if(i===void 0)continue;let s=$.dirname(r);if(!UE(e,s))continue;let o=s==="."?"node_modules":$.join(s,"node_modules");n.has(o)||n.set(o,{dir:o,install:i})}return[...n.values()]}function UE(e,t){return t==="."?!0:Na(e,t)}function Na(e,t){if(oe($.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(yt($.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function mm(e,t={}){if(Ye(R(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=Ye(R(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,o=PE(e),c=Ye(R(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let B=Ye(R(e,["rev-parse","HEAD"])),H=Ye(R(e,["rev-parse","@{u}"]));l=B!=null&&H!=null?B===H:null,d=R(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(o){let B=Ye(R(e,["rev-list","--left-right","--count",`origin/${o}...HEAD`]));if(B){let[H,C]=B.split(/\s+/).map(U=>Number.parseInt(U,10));Number.isFinite(H)&&(p=H),Number.isFinite(C)&&(u=C)}}let m=(R(e,["status","--porcelain"])??"").split(`
|
|
23
|
+
`).filter(B=>B.trim().length>0).length,g=ME(e),y=Ye(R(e,["rev-parse","--show-toplevel"]))??e,v=LE(R(e,["worktree","list","--porcelain"])??""),b=v[0]?.path??null,k=b!=null&&Ca(b,y),E=Math.max(0,v.length-1),w=null;if(b&&!Ca(b,y)){let B=a(C=>oe($.join(b,C))&&!oe($.join(y,C)),"here"),H=[...dm,...FE(y),...$E(y),...t.probePaths??[]];w={mainWorktreePath:b,currentWorktreePath:y,missing:[...new Set(H.filter(B))],missingDeps:jE(y).filter(C=>B(C.dir))}}let x=NE(y,e),I=t.includeRelease===!1?null:zE(e,s),F=[];return o&&(F=(R(e,["diff","--name-only","--diff-filter=A",`origin/${o}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
24
|
+
`).map(H=>H.trim()).filter(H=>H.length>0)),{isRepo:!0,branch:s,defaultBranch:o,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:m,detachedHead:i,inProgressOp:g,isSharedMainTree:k,otherWorktrees:E,worktreeParity:w,toolCopyDrift:x,stalePackageBuilds:hm(y),release:I,unmergedMigrations:F,hooks:Ea(e)}}function Ca(e,t){let n=a(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function GE(e){let t=new Set;Na(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<cm;){let i=n.pop();if(i===void 0)break;if(i.depth>=BE)continue;let s;try{s=Yi($.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let o of s){if(!o.isDirectory()||o.name.startsWith(".")||o.name==="node_modules")continue;let c=i.rel==="."?o.name:$.join(i.rel,o.name);if(r+=1,r>=cm)break;Na(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function WE(e){let t=[];try{let n=$.join(e,"pnpm-workspace.yaml");if(oe(n)){let r=!1;for(let i of yt(n,"utf8").split(`
|
|
25
|
+
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let o=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);o?t.push(o[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=$.join(e,"package.json");if(oe(r)){let i=JSON.parse(yt(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(o=>typeof o=="string"))}}}catch{return[]}return t}function KE(e){let t=[];for(let n of GE(e)){let r=n==="."?e:$.join(e,n),i=a(s=>n==="."?s:$.join(n,s),"prefix");for(let s of WE(r)){if(t.length>=Ra)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let o=s.slice(0,-2),c=$.join(r,o);if(!oe(c))continue;for(let l of Yi(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i($.join(o,l.name))),t.length>=Ra)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,Ra)}function lm(e){let t=null,n=0,r=[e];for(;r.length>0&&n<am;){let i=r.pop();if(i===void 0)break;let s;try{s=Yi(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let c=$.join(i,o.name);if(o.isDirectory())r.push(c);else if(o.isFile()){n+=1;try{let l=Ia(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=am)break}}}return t}function VE(e,t){let n=new Set;for(let r of t)try{let i=$.join(e,r,"package.json");if(!oe(i))continue;let s=JSON.parse(yt(i,"utf8"));for(let o of["dependencies","devDependencies","peerDependencies"]){let c=s[o];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 hm(e){let t=[],n=KE(e),r=VE(e,n);for(let i of n)try{let s=$.join(e,i,"package.json");if(!oe(s))continue;let o=JSON.parse(yt(s,"utf8"));if(typeof o.name!="string"||!r.has(o.name))continue;let c=a(b=>{if(typeof b!="string")return null;let k=b.replace(/^\.\//,"").split("/")[0];return k==="build"||k==="dist"?k:null},"builtSeg"),l=c(o.types??o.typings),d=c(o.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",h=$.join(e,i,"src"),m=$.join(e,i,u);if(!oe(h)||!oe(m))continue;let g=lm(h),y=lm(m);if(g===null||y===null)continue;let v=g-y;v>HE&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(v),impact:p})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function zE(e,t){if(!t)return null;let n=qE(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function qE(e,t){try{return TE("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function Dr(e,t={}){let n=await mm(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=pm(n),i=fm(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var dm,Oa,um,AE,RE,IE,om,HE,Ra,am,BE,cm,Da=_(()=>{"use strict";Aa();ce();Or();dm=["supabase/config.toml","supabase/.temp",".env"],Oa=".maind/worktree-requirements",um={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},AE=Object.keys(um).flatMap(e=>[e,"*/"+e]),RE=["scripts"],IE=512*1024;a(NE,"gatherToolCopyDrift");a(CE,"compareToolDirs");a(pm,"computeDivergence");a(OE,"computeHookFinding");om={open:0,warn:1,info:2,passed:3};a(DE,"sortFindings");a(fm,"isHealthy");a(Ye,"trimOrNull");a(PE,"resolveDefaultBranch");a(ME,"detectInProgressOp");a(LE,"parseWorktrees");a($E,"readWorktreeRequirements");a(FE,"discoverSupabaseConfigProbes");a(jE,"discoverDependencyDirs");a(UE,"isWorkspaceRoot");a(Na,"hasWorkspaceMarkers");a(mm,"gatherRepoHealthFacts");a(Ca,"samePath");HE=2e3,Ra=64,am=4e3,BE=3,cm=400;a(GE,"findWorkspaceRoots");a(WE,"workspacePatternsAt");a(KE,"listWorkspacePackageDirs");a(lm,"newestMtimeUnder");a(VE,"consumedWorkspaceNames");a(hm,"gatherStalePackageBuilds");a(zE,"gatherReleaseFact");a(qE,"runGh");a(Dr,"checkDivergence")});import{existsSync as Pa,readdirSync as gm}from"node:fs";import{posix as $e}from"node:path";function La(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Ma)}function _m(e,t={}){let n=t.minFiles??$a;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??ym)}function $n(e){return`${e.dir}#${e.prefix}`}function Pr(e){let t=YE.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function bm(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=$n(i),o=e.sightingsByNamespace.get(s);if(!o)continue;let c=new Set(o.keys());for(let[l,d]of o){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),h=u.filter(g=>g!==p),m=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${h.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}${Fa(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${s}#${l}`,status:"info",namespace:i,number:l,title:`${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,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}function wm(e){return!e.some(t=>t.status==="open")}function Fa(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 ja(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function vm(e,t){let n=ja(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=Pr($e.basename(n));if(!i)return r;let s=`${$e.dirname(n)}#${i.prefix}`,o=e.namespaces.find(u=>$n(u)===s)??null;if(!o)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:o,number:i.number,taken:d.length>0,sightings:d,suggestion:Fa(c.keys(),i.number)}}function Ji(e){let t=e?.trim();return t||null}function Ln(e){return e?e.split(`
|
|
26
|
+
`).filter(Boolean):[]}function JE(e){let t=Ji(R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function km(e,t={}){let n=t.minFiles??$a,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=R(e,r);if(i===null)return[];let s=new Map;for(let o of i.split("\0").filter(Boolean)){let c=$e.dirname(o),l=Pr($e.basename(o));if(!l)continue;let d=`${c}#${l.prefix}`,u=s.get(d);u?u.numbers.push(l.number):s.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...s.values()].filter(o=>_m(o.numbers,{...t,minFiles:n})).map(o=>({dir:o.dir,prefix:o.prefix,fileCount:o.numbers.length,distinctRatio:new Set(o.numbers).size/o.numbers.length})).sort((o,c)=>$n(o).localeCompare($n(c)))}async function Ua(e,t={}){let n=[];if(Ji(R(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=km(e,t),s=new Map(i.map(m=>[$n(m),m])),o=[...new Set(i.map(m=>m.dir))],c=new Map,l=a((m,g,y)=>{let v=$e.dirname(m),b=Pr($e.basename(m));if(!b)return;let k=`${v}#${b.prefix}`;if(!s.has(k))return;let E=c.get(k)??new Map,w=E.get(b.number)??[];w.push({kind:g,where:y,path:m}),E.set(b.number,w),c.set(k,E)},"record"),d=a((m,g,y)=>{if(o.length===0)return;let v=R(e,["ls-tree","-r","--name-only",m,"--",...o]);if(v===null){n.push(`could not read ${y}`);return}for(let b of Ln(v))l(b,g,y)},"scanTree");for(let m of o){let g=$e.join(e,m);if(Pa(g))try{for(let y of gm(g))l(`${m}/${y}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let u=JE(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=Ji(R(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of Ln(R(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==m&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let m=Ji(R(e,["rev-parse","--show-toplevel"]));for(let g of Ln(R(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===m||!Pa(y)))for(let v of o){let b=$e.join(y,v);if(Pa(b))try{for(let k of gm(b))l(`${v}/${k}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${v} in ${y}`)}}}}let h=[];if(p&&o.length>0){let m=R(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...o]);m===null?n.push(Ma):h=Ln(m);let g=R(e,["ls-files","--others","--exclude-standard","--",...o]);g!==null&&(h=[...h,...Ln(g)]);let y=R(e,["diff","--cached","--name-only","--diff-filter=A","--",...o]);y!==null&&(h=[...h,...Ln(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:h,skipped:n}}async function Bt(e,t={}){let n=await Ua(e,t),r=bm(n);return{ok:wm(r),findings:r,facts:n}}async function Gt(e,t,n={}){let r=ja(t);if(!Pr($e.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Ua(e,{...n,dirs:n.dirs??[$e.dirname(r)]});return vm(i,r)}var Ma,YE,$a,ym,Mr=_(()=>{"use strict";ce();Ma="could not diff against the base ref \u2014 everything reported as info";a(La,"isNumberCollisionsGraded");YE=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,$a=3,ym=.8;a(_m,"isCounterNamespace");a($n,"namespaceKey");a(Pr,"parseNumbered");a(bm,"computeNumberCollisions");a(wm,"isCollisionFree");a(Fa,"suggestNextNumber");a(ja,"normaliseRepoPath");a(vm,"checkProposedNumber");a(Ji,"trimOrNull");a(Ln,"lines");a(JE,"resolveDefaultBranch");a(km,"detectNamespaces");a(Ua,"gatherNumberCollisionFacts");a(Bt,"checkNumberCollisions");a(Gt,"checkNumberForPath")});import{execFileSync as XE}from"node:child_process";import{createHash as ZE}from"node:crypto";function Ha(e){return ZE("sha256").update(e).digest("hex")}function QE(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 e0(e){let t=QE(e);return t?Ha(t):null}function n0(e){return typeof e=="string"&&t0.test(e)}function xm(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(n0(t))return t;let n;try{n=XE("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?e0(n):null}var t0,Ba=_(()=>{"use strict";a(Ha,"sha256Hex");a(QE,"normalizeRemoteUrl");a(e0,"projectKeyFromRemote");t0=/^[a-f0-9]{64}$/;a(n0,"isProjectKey");a(xm,"computeProjectKey")});function Va(e){return`spec.${e}`}function Fn(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 r0(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){let o=(n[s].codePointAt(0)??0)-(r[s].codePointAt(0)??0);if(o!==0)return o}return n.length-r.length}function Sm(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(r0)}function $r(e){return Ha(JSON.stringify(Sm(e)))}var Lr,Ga,Wa,Ka,za=_(()=>{"use strict";Ba();Lr={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"]}},Ga="number.collision",Wa="theme.dead_class",Ka="acl.missing_revoke";a(Va,"specDriftRuleId");a(Fn,"gradeEngineStatus");a(r0,"codePointCompare");a(Sm,"normalizeEvidenceForHash");a($r,"hashDetectorEvidence")});import{existsSync as i0,readFileSync as Em}from"node:fs";import{posix as s0}from"node:path";function Qi(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 es(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 Fr(e){return e==='"'||e==="'"||e==="`"}function ts(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Xi(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(Fr(s)){i=Qi(e,i);continue}if(ts(e,i)){i=es(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function o0(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(ts(e,t)){t=es(e,t);continue}break}return e.slice(t)}function jn(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(Fr(s)){i=Qi(e,i);continue}if(ts(e,i)){i=es(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>o0(s).trim()).filter(s=>s.length>0)}function Im(e){let t=Qi(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
28
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function a0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ya(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${a0(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let o=e[i];if(Fr(o)){i=Qi(e,i);continue}if(ts(e,i)){i=es(e,i);continue}if(!s){if(o==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(o===";")return null;i++;continue}if(o==="[")return Xi(e,i);if(o===";")return null;i++}return null}function Ja(e){let t={};if(!e.startsWith("{"))return t;for(let n of jn(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();Fr(s[0]??"")&&(t[i]=Im(s))}return t}function c0(e,t){if(!e.startsWith("{"))return null;for(let n of jn(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 Nm(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Cm(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Om(e,t){let n=Ya(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Cm(),i=[],s=0;for(let o of jn(n.slice(1,-1))){if(!o.startsWith("{")){s++;continue}let c=Ja(o),l=c[t.key_field];if(!l){s++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:Nm(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Dm(e,t){let n=Ya(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=Cm(),i=[],s=0,o=a((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let h of jn(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!h.startsWith("{")){s++;continue}let y=Ja(h);for(let[v,b]of Object.entries(u.fields??{}))m[v]=y[String(b)]??"";if(!p&&typeof u.children=="string"){let v=c0(h,u.children);g=v&&v.startsWith("[")?Xi(v,0):null}}else{if(!h.startsWith("[")){s++;continue}let y=jn(h.slice(1,-1));for(let[v,b]of Object.entries(u.fields??{})){let k=y[Number(b)];m[v]=k!==void 0&&Fr(k[0]??"")?Im(k):""}if(!p&&typeof u.children=="number"){let v=y[u.children];g=v!==void 0&&v.startsWith("[")?Xi(v,0):null}}if(p){let y=m[t.key_field];if(!y){s++;continue}let v=(t.partition_by??[]).map(b=>m[b]??"");i.push({key:y,fields:Nm(m,t.fields),orderPath:v,ordinal:r(v)});continue}g!==null&&o(g,l+1,m)}},"walk");return o(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Tm(e,t){return t.extractor==="object-array"?Om(e,t):Dm(e,t)}function Pm(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 Mm(e,t,n){return`spec.drift:${e}#${t}:${n}`}function l0(e){return e.orderPath.join(" / ")||"(flat)"}function Lm(e,t,n,r){let i=[],s=a((d,u,p,h,m,g)=>{i.push({id:Mm(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:h,detail:m,hint:g})},"push"),o=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=o.get(d.key);if(!u){s("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${l0(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 h=d.fields[p]??"",m=u.fields[p]??"";h!==m&&s("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${m||"\u2014"}", the specification says "${h||"\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=>o.has(y.key)).map(y=>y.key),h=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),m=new Set(h),g=p.filter(y=>m.has(y));if(h.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";s("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${h.join(" \u2192 ")}
|
|
29
|
+
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||s("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...o.keys(),...c.keys()])){if(Pm(d,e.grounding,r))continue;let u=o.has(d);s("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function d0(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let o=s.indexOf(i.prefix);if(o===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(o+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 Am(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 $m(e,t={}){let n=a(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=a(u=>{let p=[],h=[];for(let m of r){let g=u.get(m.spec.path),y=u.get(m.impl.path);if(g==null||y==null){let E=g==null?m.spec.path:m.impl.path;p.push(Am(m.id,`Declared file could not be read: ${E}`)),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let v=Tm(g,m.spec),b=Tm(y,m.impl);if(v.error||b.error){p.push(Am(m.id,v.error??b.error??"unknown")),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=v.dropped>0||b.dropped>0;h.push({id:m.id,measured:!0,specRecords:v.records.length,implRecords:b.records.length,partial:k}),k&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${v.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(...Lm(m,v.records,b.records,e.files)),p.push(...d0(m,{spec:v.records.length,impl:b.records.length},u))}return{findings:p,contracts:h}},"runOnce"),s=i(e.sources),o=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:")||o.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(Mm(u.id,p.dimension,p.key),p);let l=s.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:o.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)=>Rm[u.status]-Rm[p.status]||u.id.localeCompare(p.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:s.contracts}}function qa(e){let t=e?.trim();return t||null}function ns(e){let t;try{t=JSON.parse(e)}catch(o){return{manifest:null,error:`manifest is not valid JSON: ${o.message}`}}let n=a(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null,"obj"),r=a(o=>typeof o=="string"?o:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=a(o=>({manifest:null,error:o}),"bad");for(let[o,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${o+1}`;if(!l)return s(`${u}: not an object`);if(!d)return s(`${u}: \`id\` is missing`);if(!r(l.reason))return s(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let h=n(l[p]);if(!h)return s(`${u}: \`${p}\` is missing`);let m=r(h.extractor);if(!m)return s(`${u}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return s(`${u}: unknown \`${p}.extractor\` "${m}"`);if(!r(h.path)||!r(h.symbol)||!r(h.key_field))return s(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(h.levels))return s(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let h=n(p);if(!h||!r(h.reason))return s(`${u}: exception for "${r(h?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function u0(e){let t=qa(R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function p0(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 Fm(e,t={}){let n=a((g,y)=>s0.join(g,y),"join"),r=t.manifestPath??Zi,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(qa(R(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let o=n(e,r);if(!i0(o))return{...s,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=ns(Em(o,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...s,isRepo:!0,manifestError:l};let d=new Map;for(let g of p0(c))try{d.set(g,Em(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=R(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 h=null,m=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:u0(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(h=qa(R(e,["merge-base",y,"HEAD"])),!h)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let v of d.keys())m.set(v,R(e,["show",`${h}:${v}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:h,files:u,skipped:i}}async function Wt(e,t={}){let n=await Fm(e,t);return{...$m(n,t),facts:n}}function Xa(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Zi,Rm,jr=_(()=>{"use strict";ce();Zi=".maind/spec-contracts.json";a(Qi,"endOfString");a(es,"skipComment");a(Fr,"isQuote");a(ts,"isCommentStart");a(Xi,"sliceBalanced");a(o0,"stripLeadingTrivia");a(jn,"splitTopLevel");a(Im,"readStringLiteral");a(a0,"escapeRe");a(Ya,"findSymbolArray");a(Ja,"parseObjectFields");a(c0,"objectFieldRaw");a(Nm,"pickFields");a(Cm,"makeOrdinals");a(Om,"extractObjectArray");a(Dm,"extractNestedList");a(Tm,"extractRecords");a(Pm,"isGrounded");a(Mm,"findingId");a(l0,"partitionOf");a(Lm,"compareContract");a(d0,"checkAssertions");a(Am,"unreadable");Rm={open:0,warn:1,info:2,passed:3};a($m,"computeSpecDrift");a(qa,"trimOrNull");a(ns,"parseManifest");a(u0,"resolveDefaultBranch");a(p0,"declaredPaths");a(Fm,"gatherSpecDriftFacts");a(Wt,"checkSpecDrift");a(Xa,"isSpecDriftGraded")});import{execFileSync as f0}from"node:child_process";import{existsSync as m0,readFileSync as h0}from"node:fs";import{join as g0}from"node:path";function Ur(e){let t=[],n=e.split(`
|
|
31
|
+
`);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let s=/(\d+\.\d+\.\d+)/.exec(i);s&&t.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":y0.test(i)?"never-published":"released"})}return t}function Um(e){let t=new Map;for(let n of Ur(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 Hm(e,t){let n=Um(e);if(t===null)return{introduced:[],preExisting:n.map(o=>({...o,countBefore:o.count})),baseResolved:!1};let r=new Map;for(let o of Ur(t))r.set(o.version,(r.get(o.version)??0)+1);let i=[],s=[];for(let o of n){let c=r.get(o.version)??0;(o.count>c?i:s).push({...o,countBefore:c})}return{introduced:i,preExisting:s,baseResolved:!0}}function Bm(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=Hm(r.head,e.baseRef===null?null:r.base);for(let s of i.introduced)t.push({path:r.path,version:s.version,level:"open",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} has ${s.count} headings (was ${s.countBefore})`});for(let s of i.preExisting)t.push({path:r.path,version:s.version,level:"info",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} already had ${s.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function jm(e,t){try{return f0("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function _0(e,t={}){let n=jm(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null,s=r.map(o=>{let c=g0(e,o);return{path:o,head:m0(c)?h0(c,"utf8"):null,base:i===null?null:jm(["show",`${i}:${o}`],e)}});return{isRepo:!0,baseRef:i,files:s}}function Za(e,t={}){return Bm(_0(e,t))}var y0,rs=_(()=>{"use strict";y0=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;a(Ur,"parseVersionHeadings");a(Um,"findDuplicateHeadings");a(Hm,"classifyIntroduced");a(Bm,"computeChangelogDuplicates");a(jm,"git");a(_0,"gatherChangelogFacts");a(Za,"checkChangelogDuplicates")});import{execFileSync as b0}from"node:child_process";import{existsSync as w0,readFileSync as Gm}from"node:fs";import{dirname as Wm,join as Km}from"node:path";function zm(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),i=new Set(n.documentedBase??n.documented),s=[...n.documented].sort(Er);for(let o of s){if(r.has(o)||Er(o,n.version)>=0)continue;let c=!i.has(o);t.push({package:n.name,version:o,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${o} is newly documented as released but the registry never served it`:`${n.name}@${o} is documented as released but the registry never served it`})}for(let o of[...n.neverPublished??[]].sort(Er))r.has(o)&&t.push({package:n.name,version:o,level:"info",rule:"release.mislabelled",title:`${n.name}@${o} 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 Vm(e){let t=Ur(e),n=[...new Set(t.filter(s=>s.shape!=="never-published").map(s=>s.version))],r=new Set(n),i=[...new Set(t.filter(s=>s.shape==="never-published"&&!r.has(s.version)).map(s=>s.version))];return{documented:n,neverPublished:i}}function Qa(e,t){try{return b0("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function qm(e,t=null){let n=Qa(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let s;try{s=JSON.parse(Gm(Km(e,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let o=Wm(i)==="."?"":Wm(i),c=Km(e,o,"CHANGELOG.md"),{documented:l,neverPublished:d}=w0(c)?Vm(Gm(c,"utf8")):{documented:[],neverPublished:[]},u=o===""?"CHANGELOG.md":`${o}/CHANGELOG.md`,p=t===null?null:Qa(["show",`${t}:${u}`],e),h=t===null?null:p===null?[]:Vm(p).documented;r.push({dir:o,name:s.name,version:s.version,documented:l,documentedBase:h,neverPublished:d})}return r}async function v0(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 Ym(e,t={}){if(Qa(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=qm(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??v0,i={};for(let s of n)try{i[s.name]=await r(s.name)}catch(o){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${s.name}: ${o.message}`}}return{isRepo:!0,packages:n,published:i,registryReachable:!0,registryError:null}}async function ec(e,t={}){return zm(await Ym(e,t))}var tc=_(()=>{"use strict";Tr();rs();a(zm,"computeReleaseClaims");a(Vm,"claimsOf");a(Qa,"git");a(qm,"discoverPackages");a(v0,"packument");a(Ym,"gatherReleaseClaimsFacts");a(ec,"checkReleaseClaims")});import{execFileSync as k0}from"node:child_process";import{existsSync as x0,readFileSync as S0}from"node:fs";import{join as E0}from"node:path";function rc(e){let t=[],n=!1;for(let r of e.split(`
|
|
32
|
+
`)){let i=r.trim();if(n){i===Qm&&(n=!1);continue}if(i===Zm){n=!0;continue}t.push(r)}return t.join(`
|
|
33
|
+
`)}function Jm(e){return e.split(`
|
|
34
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function eh(e,t){let n=new Map;for(let s of Jm(t??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of Jm(e)){let o=n.get(s)??0;o>0?n.set(s,o-1):r.push(s)}let i=0;for(let s of n.values())i+=s;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function th(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=eh(rc(n.head),n.base===null?null:rc(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 nc(e,t){try{return k0("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function nh(e,t={}){let n=nc(["ls-files","-z","--",...Xm],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&nc(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(o=>{let c=E0(e,o);return{path:o,head:x0(c)?S0(c,"utf8"):null,base:r===null?null:nc(["show",`${r}:${o}`],e)}});return{isRepo:!0,baseRef:r,files:s}}function ic(e,t={}){return th(nh(e,t))}var Xm,Zm,Qm,sc=_(()=>{"use strict";Xm=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],Zm="<!-- maind:conventions v1 begin -->",Qm="<!-- maind:conventions v1 end -->";a(rc,"stripManagedConventionsBlock");a(Jm,"contentLines");a(eh,"proseDelta");a(th,"computeAgentDocProse");a(nc,"git");a(nh,"gatherAgentDocProseFacts");a(ic,"checkAgentDocProse")});var rh,ih,oc=_(()=>{"use strict";rh=[".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"],ih=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 T0}from"node:child_process";import{existsSync as A0,readFileSync as R0}from"node:fs";import{join as I0}from"node:path";function oh(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?[]:Fi(n.base).map(i=>i.value));for(let i of Fi(n.content)){let s=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,o=e.baseRef!==null&&!r.has(i.value);t.push({path:n.path,level:o?"open":"info",line:i.line,value:i.value,title:`${n.path}:${i.line}: unquoted plain scalar containing ": " \u2014 ${s}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function sh(e,t){try{return T0("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function ah(e,t={}){let n=sh(["ls-files","-z","--",...rh],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(s=>{let o=I0(e,s);return{path:s,content:A0(o)?R0(o,"utf8"):null,base:i===null?null:sh(["show",`${i}:${s}`],e)}})}}function ac(e,t={}){return oh(ah(e,t))}var cc=_(()=>{"use strict";Tr();oc();a(oh,"computeWorkflowYaml");a(sh,"git");a(ah,"gatherWorkflowYamlFacts");a(ac,"checkWorkflowYaml")});import{readFileSync as N0}from"node:fs";import{join as C0,posix as O0}from"node:path";function ch(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
|
|
35
|
+
`;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let o=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||o){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 Se(e){let t=[],n="",r=!1,i=!1,s=a(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let o=t.filter(c=>c.length>0);return o.length===0||o.length>2?null:o.length===2?{schema:o[0],name:o[1]}:{schema:"public",name:o[0]}}function Je(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 D0(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let o=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(o&&!Je(o[1]).map(h=>Se(h)?.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||!Je(c[1]).map(p=>Se(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Je(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Se(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Je(i)){let h=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!h)continue;let m=h[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...Hr]};h[2]!=="("&&Hr.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function lh(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(n)return null;let o=i.trim();if(P0.test(o))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(o);if(l){if(!Je(l[1]).map(h=>Se(h)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=o.replace(/^TABLE\s+/i,""),h=Je(p).map(m=>Se(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(h.length===0)return null;c=h}let d=Je(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Se(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Je(r)){let h=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!h)continue;let m=h[1].toUpperCase(),g=h[2]==="(";if(m==="ALL")return{tables:c,roles:d,writePrivs:[...Hr]};!g&&Hr.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function dc(e){let t=new Map,n=[...e].sort((i,s)=>qe(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=ch(i.content);for(let o of s.split(";")){let c=o.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=D0(c);if(!p)continue;let h=p.roles.includes("anon"),m=p.roles.includes("authenticated");if(p.action==="revoke"){if(h&&(r.anonAddressed=!0),m)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(h&&(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=Se(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 h of Je(p)){let m=Se(h);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=Se(u[1]),h=Se(u[2]);if(p&&h&&p.schema==="public"){let m=t.get(p.name);m&&(t.delete(p.name),t.set(h.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=lh(c);if(!p)continue;let h=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 h){let v=t.get(y);if(v&&(m&&(v.anonAddressed=!0),g))for(let b of p.writePrivs)v.authWritesRevoked.add(b)}continue}}}return t}function lc(e){let t=[];for(let[n,r]of dc(e)){let i=[];r.anonAddressed||i.push("anon"),Hr.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function dh(e){let t=lc(e.files),n=new Map;if(e.baseFiles!==null)for(let r of lc(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),o=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:o,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 uh(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function pc(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(is)||t.endsWith(uc))}function L0(e,t){try{let n=N0(e,"utf8");return n.length>t?null:n}catch{return null}}function $0(e,t,n,r,i){let s=R(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(s===null)return i.push(`could not diff ${t} against ${r} ${is}`),null;let o=new Set,c=[];for(let u of s.split(`
|
|
36
|
+
`).filter(Boolean)){let[p,...h]=u.split(" ");p.startsWith("A")?o.add(h[0]):p.startsWith("R")?(c.push(h[0]),o.add(h[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(h[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!o.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=O0.basename(u),h=Mn(p);if(h===null)continue;let m=R(e,["show",`${r}:${u}`]);if(m===null)return i.push(`could not read ${u} at ${r} ${uc}`),null;l.push({name:p,version:h,content:m})}return l}function Kt(e,t={}){let n=t.maxFileBytes??M0,r=[],i=Ht(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=t.includeBaseline!==!1,o=null;if(s)if(t.baseRef)o=t.baseRef;else{let h=Cr(e);o=h?`origin/${h}`:null,o===null&&r.push(`no default branch resolvable ${is}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let h of i){let m=[];for(let v of h.files){let b=L0(C0(e,v.path),n);if(b===null){r.push(`could not read ${v.path} \u2014 excluded from the fold`);continue}m.push({ref:v,content:b})}let g=m.map(({ref:v,content:b})=>({name:v.name,version:v.version,content:b})),y=o===null?null:$0(e,h.dir,m,o,r);c.push(...dh({dir:h.dir,files:g,baseFiles:y})),l.push({dir:h.dir,migrationCount:g.length,tableCount:dc(g).size})}let d=l.reduce((h,m)=>h+m.migrationCount,0),u=uh(d,c.length),p={open:0,info:1};return c.sort((h,m)=>p[h.status]-p[m.status]||h.id.localeCompare(m.id)),{ok:u!=="no_opinion"&&!c.some(h=>h.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:o,skipped:r}}}var Hr,P0,M0,is,uc,ss=_(()=>{"use strict";ce();Or();a(ch,"stripSql");a(Se,"normalizeQualifiedIdent");a(Je,"splitTopLevel");Hr=["INSERT","UPDATE","DELETE"];a(D0,"parseDefaultAclTables");P0=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;a(lh,"parseTableRevoke");a(dc,"foldTableAcl");a(lc,"evaluateTableAcl");a(dh,"computeTableAclFindings");a(uh,"deriveTableAclVerdict");M0=5e6,is="\u2014 findings reported ungraded (open)",uc="\u2014 baseline degraded";a(pc,"isTableAclGraded");a(L0,"safeRead");a($0,"baseFilesFor");a(Kt,"checkTableAclLint")});import{readFileSync as F0}from"node:fs";import{join as fc}from"node:path";function hc(e){return e.verdict!=="no_opinion"&&e.graded}function gc(e){let t=new Set;for(let n of e.matchAll(j0))t.add(n[1]);return t}function yc(e){return new Set([...e].map(t=>t.split("-")[0]))}function yh(e){return e.split(`
|
|
35
37
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
36
|
-
`)}function
|
|
37
|
-
`).filter(Boolean)}function Vt(e,t={}){let n=t.maxFileBytes??
|
|
38
|
-
`).filter(Boolean)),l=a(p=>c.has(p)?
|
|
39
|
-
`).filter(i=>i.length>0&&n.some(s=>g0(i,s)))}function g0(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let s=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}function y0(e){let t=A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>A(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function rc(e,t){try{let n=d0(e,"utf8");return n.length>t?null:n}catch{return null}}var Zm,u0,p0,Ym,m0,ss=_(()=>{"use strict";ae();a(ic,"isThemeClassDriftGraded");Zm=["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"],u0=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,p0=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Zm.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");a(sc,"extractTokens");a(oc,"deriveNamespaces");a(Qm,"stripCommentLines");a(ac,"evaluateThemeClasses");a(qm,"findingKey");a(f0,"gradeAgainstBaseline");a(eh,"deriveThemeClassVerdict");Ym=["*.ts","*.tsx","*.js","*.jsx"],m0=15e5;a(cc,"isScannableSource");a(Jm,"listTracked");a(Vt,"checkThemeClassDrift");a(h0,"baselineFindings");a(Xm,"listTrackedAt");a(g0,"matchesSourcePattern");a(y0,"resolveBaseRef");a(rc,"safeRead")});function lc(e){return Pr[e].version}function Ye(e,t,n,r){return{detector_id:e,detector_version:lc(e),state:t,finding_count:n,...r?{reason:r}:{}}}function B(e,t,n){return{summary:Ye(e,t,0,n),findings:[]}}function oh(e){return e==="open"||e==="warn"||e==="info"}function _0(e){let t="det_number_collisions";if(!e.ok)return B(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return B(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return B(t,"not_applicable","no numbered namespaces");if(!Ta(n))return B(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!oh(s.status))continue;let{level:o,baseline:c}=Ln(s.status);i.push({detector_id:t,rule_id:Da,level:o,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:Ye(t,"ran",i.length),findings:i}}function b0(e){let t="det_spec_drift";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return B(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return B(t,"not_applicable",n.reason??"no opinion");if(!Ha(n))return B(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!oh(i.status))continue;let{level:s,baseline:o}=Ln(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:La(i.dimension),level:s,baseline:o,evidence:[i.id],title:i.title})}return{summary:Ye(t,"ran",r.length),findings:r}}function w0(e){let t="det_theme_class_drift";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable","no theme tokens");if(!ic(n))return B(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=Ln(i.status);r.push({detector_id:t,rule_id:Pa,level:s,baseline:o,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Ye(t,"ran",r.length),findings:r}}function v0(e){let t="det_table_acl_lint";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable","no supabase migrations");if(!tc(n))return B(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=Ln(i.status);r.push({detector_id:t,rule_id:Ma,level:s,baseline:o,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Ye(t,"ran",r.length),findings:r}}function k0(e){let t="det_changelog_duplicates";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return B(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:Ye(t,"ran",r.length),findings:r}}function x0(e){let t="det_workflow_yaml";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return B(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:Ye(t,"ran",r.length),findings:r}}function S0(e){let t="det_release_claims";if(!e.ok)return B(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?B(t,"ungraded",n.reason??"registry unreachable"):B(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:Ye(t,"ran",r.length),findings:r}}function E0(e){let t="det_agent_doc_prose";if(!e.ok)return B(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?B(t,"ungraded",n.reason??"no base ref to grade against"):B(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:Ye(t,"ran",r.length),findings:r}}function dc(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||os[e.level]-os[t.level]||nh[e.baseline]-nh[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function rh(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function T0(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=Mr(i.evidence),o=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(o);c?c.count+=1:t.set(o,{detector_id:i.detector_id,detector_version:lc(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,o=n.get(s);o?(o.evidence.push(...i.evidence),o.count+=1,os[i.level]<os[o.level]&&(o.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:lc(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Mr(i.evidence),count:i.count});return r.sort(dc)}function A0(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 be(e){let t={det_number_collisions:_0(e.number),det_spec_drift:b0(e.spec),det_theme_class_drift:w0(e.theme),det_table_acl_lint:v0(e.acl),det_changelog_duplicates:k0(e.changelog),det_workflow_yaml:x0(e.workflow),det_release_claims:S0(e.release),det_agent_doc_prose:E0(e.agentDoc)},n=th.map(l=>t[l].summary),r=th.flatMap(l=>t[l].findings),i=T0(r),s=[...i].sort((l,d)=>rh(l)-rh(d)||dc(l,d)).slice(0,ih).sort(dc),o=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Mr(l.evidence),title:l.title}));return{findings:s,coverage:A0(n,o),engines:n,local:c,truncated:o}}function qe(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 pc(e){return e instanceof Error?e.message:String(e)}async function yt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:pc(t)}}}async function fc(e,t={}){let n={...sh,...t.engines};try{if(!ah(e))return be(qe("not a git work tree"));let r=await ch(e,n,t.baseRef),i=await uc(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return be({...r,number:i})}catch(r){return be(qe(`detector adapter failed: ${pc(r)}`))}}async function mc(e,t={}){let n={...sh,...t.engines};try{if(!ah(e)){let o=be(qe("not a git work tree"));return{commit:o,local:o}}let r=await ch(e,n,t.baseRef),i=await uc(e,n,t.baseRef,"commit"),s=await uc(e,n,t.baseRef,"local");return{commit:be({...r,number:i}),local:be({...r,number:s})}}catch(r){let i=be(qe(`detector adapter failed: ${pc(r)}`));return{commit:i,local:i}}}function ah(e){return A(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function ch(e,t,n){let r=n?{baseRef:n}:{};return{spec:await yt(()=>t.spec(e,r)),theme:await yt(()=>t.theme(e,r)),acl:await yt(()=>t.acl(e,r)),changelog:await yt(()=>t.changelog(e,r)),workflow:await yt(()=>t.workflow(e,r)),release:await yt(()=>t.release(e,r)),agentDoc:await yt(()=>t.agentDoc(e,r))}}function uc(e,t,n,r,i){let s=r==="local";return yt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var ih,sh,th,os,nh,hc=_(()=>{"use strict";ae();$a();Dr();$r();Ka();qa();Xa();ns();is();ss();ih=64,sh={number:a((e,t)=>Gt(e,t),"number"),spec:a((e,t)=>Wt(e,t),"spec"),theme:a((e,t)=>Vt(e,t),"theme"),acl:a((e,t)=>Kt(e,t),"acl"),changelog:a((e,t)=>Ga(e,t),"changelog"),workflow:a((e,t)=>Ja(e,t),"workflow"),release:a((e,t)=>Wa(e,t),"release"),agentDoc:a((e,t)=>za(e,t),"agentDoc")},th=["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"];a(lc,"versionOf");a(Ye,"summary");a(B,"noFindings");a(oh,"isFindingStatus");a(_0,"adaptNumber");a(b0,"adaptSpec");a(w0,"adaptTheme");a(v0,"adaptAcl");a(k0,"adaptChangelog");a(x0,"adaptWorkflow");a(S0,"adaptRelease");a(E0,"adaptAgentDoc");os={open:0,warn:1,info:2},nh={introduced:0,pre_existing:1};a(dc,"compareWire");a(rh,"capPriority");a(T0,"buildWire");a(A0,"deriveCoverage");a(be,"adaptDetectorReports");a(qe,"unavailableDetectorReports");a(pc,"errorText");a(yt,"attempt");a(fc,"runRepoHealthDetectors");a(mc,"runRepoHealthDetectorScopes");a(ah,"insideWorkTree");a(ch,"runSharedEngines");a(uc,"runNumberEngine")});var lh,gc=_(()=>{"use strict";Ya();lh=[{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:Um},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function dh(e){let t=new Set;for(let[n,r]of e.paths)for(let i of lh){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=R0(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function R0(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
40
|
-
`):t.readUntracked(e)}var
|
|
38
|
+
`)}function _c(e){let t=yc(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=yh(i),o=new Set;for(let c of s.matchAll(U0)){let l=c[2],d=l.split("-")[0];if(!t.has(d)||e.tokens.has(l))continue;let u=`${c[1]}-${l}`;o.has(u)||(o.add(u),n.push({file:r,klass:u,token:l,namespace:d}))}}return n}function ph(e){return`${e.file} ${e.klass}`}function H0(e,t){let n=t===null?null:new Set(t.map(ph));return e.map(r=>({...r,status:n!==null&&n.has(ph(r))?"info":"open"}))}function _h(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function bc(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function mh(e,t){let n=R(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
39
|
+
`).filter(Boolean)}function Vt(e,t={}){let n=t.maxFileBytes??B0,r=new Set;for(let u of mh(e,["*.css"])){let p=mc(fc(e,u),n);if(p!==null)for(let h of gc(p))r.add(h)}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=>fh.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):fh,s=[];for(let u of mh(e,i)){if(!bc(u))continue;let p=mc(fc(e,u),n);p!==null&&s.push({path:u,content:p})}let o=_c({tokens:r,sources:s}),c=t.includeBaseline===!1?null:G0(e,i,n,t.baseRef),l=H0(o,c?.findings??null),d=_h(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:yc(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function G0(e,t,n,r){let i=r??K0(e);if(i===null)return null;let s=R(e,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let o=R(e,["diff","--name-only","--no-renames",s]);if(o===null)return null;let c=new Set(o.split(`
|
|
40
|
+
`).filter(Boolean)),l=a(p=>c.has(p)?R(e,["show",`${s}:${p}`]):mc(fc(e,p),n),"atBase"),d=new Set;for(let p of hh(e,s,["*.css"])){let h=l(p);if(h!==null)for(let m of gc(h))d.add(m)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let p of hh(e,s,t)){if(!bc(p))continue;let h=l(p);h===null||h.length>n||u.push({path:p,content:h})}return{findings:_c({tokens:d,sources:u}),mergeBase:s}}function hh(e,t,n){let r=R(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
41
|
+
`).filter(i=>i.length>0&&n.some(s=>W0(i,s)))}function W0(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let s=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}function K0(e){let t=R(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>R(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function mc(e,t){try{let n=F0(e,"utf8");return n.length>t?null:n}catch{return null}}var gh,j0,U0,fh,B0,os=_(()=>{"use strict";ce();a(hc,"isThemeClassDriftGraded");gh=["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"],j0=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,U0=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+gh.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");a(gc,"extractTokens");a(yc,"deriveNamespaces");a(yh,"stripCommentLines");a(_c,"evaluateThemeClasses");a(ph,"findingKey");a(H0,"gradeAgainstBaseline");a(_h,"deriveThemeClassVerdict");fh=["*.ts","*.tsx","*.js","*.jsx"],B0=15e5;a(bc,"isScannableSource");a(mh,"listTracked");a(Vt,"checkThemeClassDrift");a(G0,"baselineFindings");a(hh,"listTrackedAt");a(W0,"matchesSourcePattern");a(K0,"resolveBaseRef");a(mc,"safeRead")});function wc(e){return Lr[e].version}function Ze(e,t,n,r){return{detector_id:e,detector_version:wc(e),state:t,finding_count:n,...r?{reason:r}:{}}}function G(e,t,n){return{summary:Ze(e,t,0,n),findings:[]}}function Sh(e){return e==="open"||e==="warn"||e==="info"}function V0(e){let t="det_number_collisions";if(!e.ok)return G(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return G(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return G(t,"not_applicable","no numbered namespaces");if(!La(n))return G(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!Sh(s.status))continue;let{level:o,baseline:c}=Fn(s.status);i.push({detector_id:t,rule_id:Ga,level:o,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:Ze(t,"ran",i.length),findings:i}}function z0(e){let t="det_spec_drift";if(!e.ok)return G(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return G(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return G(t,"not_applicable",n.reason??"no opinion");if(!Xa(n))return G(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Sh(i.status))continue;let{level:s,baseline:o}=Fn(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Va(i.dimension),level:s,baseline:o,evidence:[i.id],title:i.title})}return{summary:Ze(t,"ran",r.length),findings:r}}function q0(e){let t="det_theme_class_drift";if(!e.ok)return G(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return G(t,"not_applicable","no theme tokens");if(!hc(n))return G(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=Fn(i.status);r.push({detector_id:t,rule_id:Wa,level:s,baseline:o,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Ze(t,"ran",r.length),findings:r}}function Y0(e){let t="det_table_acl_lint";if(!e.ok)return G(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return G(t,"not_applicable","no supabase migrations");if(!pc(n))return G(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=Fn(i.status);r.push({detector_id:t,rule_id:Ka,level:s,baseline:o,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Ze(t,"ran",r.length),findings:r}}function J0(e){let t="det_changelog_duplicates";if(!e.ok)return G(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return G(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return G(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:Ze(t,"ran",r.length),findings:r}}function X0(e){let t="det_workflow_yaml";if(!e.ok)return G(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return G(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return G(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:Ze(t,"ran",r.length),findings:r}}function Z0(e){let t="det_release_claims";if(!e.ok)return G(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?G(t,"ungraded",n.reason??"registry unreachable"):G(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:Ze(t,"ran",r.length),findings:r}}function Q0(e){let t="det_agent_doc_prose";if(!e.ok)return G(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?G(t,"ungraded",n.reason??"no base ref to grade against"):G(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:Ze(t,"ran",r.length),findings:r}}function vc(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||as[e.level]-as[t.level]||wh[e.baseline]-wh[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function vh(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function eT(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=$r(i.evidence),o=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(o);c?c.count+=1:t.set(o,{detector_id:i.detector_id,detector_version:wc(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,o=n.get(s);o?(o.evidence.push(...i.evidence),o.count+=1,as[i.level]<as[o.level]&&(o.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:wc(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:$r(i.evidence),count:i.count});return r.sort(vc)}function tT(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 be(e){let t={det_number_collisions:V0(e.number),det_spec_drift:z0(e.spec),det_theme_class_drift:q0(e.theme),det_table_acl_lint:Y0(e.acl),det_changelog_duplicates:J0(e.changelog),det_workflow_yaml:X0(e.workflow),det_release_claims:Z0(e.release),det_agent_doc_prose:Q0(e.agentDoc)},n=bh.map(l=>t[l].summary),r=bh.flatMap(l=>t[l].findings),i=eT(r),s=[...i].sort((l,d)=>vh(l)-vh(d)||vc(l,d)).slice(0,kh).sort(vc),o=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:$r(l.evidence),title:l.title}));return{findings:s,coverage:tT(n,o),engines:n,local:c,truncated:o}}function Xe(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 xc(e){return e instanceof Error?e.message:String(e)}async function _t(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:xc(t)}}}async function Sc(e,t={}){let n={...xh,...t.engines};try{if(!Eh(e))return be(Xe("not a git work tree"));let r=await Th(e,n,t.baseRef),i=await kc(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return be({...r,number:i})}catch(r){return be(Xe(`detector adapter failed: ${xc(r)}`))}}async function Ec(e,t={}){let n={...xh,...t.engines};try{if(!Eh(e)){let o=be(Xe("not a git work tree"));return{commit:o,local:o}}let r=await Th(e,n,t.baseRef),i=await kc(e,n,t.baseRef,"commit"),s=await kc(e,n,t.baseRef,"local");return{commit:be({...r,number:i}),local:be({...r,number:s})}}catch(r){let i=be(Xe(`detector adapter failed: ${xc(r)}`));return{commit:i,local:i}}}function Eh(e){return R(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function Th(e,t,n){let r=n?{baseRef:n}:{};return{spec:await _t(()=>t.spec(e,r)),theme:await _t(()=>t.theme(e,r)),acl:await _t(()=>t.acl(e,r)),changelog:await _t(()=>t.changelog(e,r)),workflow:await _t(()=>t.workflow(e,r)),release:await _t(()=>t.release(e,r)),agentDoc:await _t(()=>t.agentDoc(e,r))}}function kc(e,t,n,r,i){let s=r==="local";return _t(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var kh,xh,bh,as,wh,Tc=_(()=>{"use strict";ce();za();Mr();jr();tc();sc();cc();rs();ss();os();kh=64,xh={number:a((e,t)=>Bt(e,t),"number"),spec:a((e,t)=>Wt(e,t),"spec"),theme:a((e,t)=>Vt(e,t),"theme"),acl:a((e,t)=>Kt(e,t),"acl"),changelog:a((e,t)=>Za(e,t),"changelog"),workflow:a((e,t)=>ac(e,t),"workflow"),release:a((e,t)=>ec(e,t),"release"),agentDoc:a((e,t)=>ic(e,t),"agentDoc")},bh=["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"];a(wc,"versionOf");a(Ze,"summary");a(G,"noFindings");a(Sh,"isFindingStatus");a(V0,"adaptNumber");a(z0,"adaptSpec");a(q0,"adaptTheme");a(Y0,"adaptAcl");a(J0,"adaptChangelog");a(X0,"adaptWorkflow");a(Z0,"adaptRelease");a(Q0,"adaptAgentDoc");as={open:0,warn:1,info:2},wh={introduced:0,pre_existing:1};a(vc,"compareWire");a(vh,"capPriority");a(eT,"buildWire");a(tT,"deriveCoverage");a(be,"adaptDetectorReports");a(Xe,"unavailableDetectorReports");a(xc,"errorText");a(_t,"attempt");a(Sc,"runRepoHealthDetectors");a(Ec,"runRepoHealthDetectorScopes");a(Eh,"insideWorkTree");a(Th,"runSharedEngines");a(kc,"runNumberEngine")});var Ah,Ac=_(()=>{"use strict";oc();Ah=[{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:ih},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function Rh(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Ah){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=nT(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function nT(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
42
|
+
`):t.readUntracked(e)}var Ih=_(()=>{"use strict";Ac();a(Rh,"scanRiskFlags");a(nT,"contentForPath")});var Un,Nh,Hn,Bn,Rc,cs,Ic,ls,ds,us,Nc,Ch,Br=_(()=>{"use strict";Un="3",Nh=`
|
|
41
43
|
CREATE TABLE IF NOT EXISTS meta (
|
|
42
44
|
key TEXT PRIMARY KEY,
|
|
43
45
|
value TEXT NOT NULL
|
|
@@ -125,329 +127,20 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
125
127
|
vec BLOB NOT NULL,
|
|
126
128
|
content_hash TEXT NOT NULL
|
|
127
129
|
);
|
|
128
|
-
`,jn="schema_version",Un="last_index_commit",yc="last_indexed_at",as="edges_dirty",_c="resolve_config_fp",cs="embed_recipe_version",ls="embed_model",ds="embed_dim",bc="last_synced_at",fh="last_synced_commit"});function wc(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 mh(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of wc(e.name))t.add(i);for(let i of wc(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function hh(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 wc(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var vc=_(()=>{"use strict";a(wc,"splitIdentifier");a(mh,"buildSearchText");a(hh,"toFtsMatchQuery")});import{readFileSync as gh}from"node:fs";import{posix as yh}from"node:path";function _h(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 zt(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function bh(e){return e==="added"?0:e==="modified"?1:2}function I0(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 o of n.addedRanges){let c=Math.max(o.start,e.startLine),l=Math.min(o.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(o=>o>=e.startLine-1&&o<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Hr,kc=_(()=>{"use strict";Sr();pf();Qo();mf();_f();ta();Ef();ae();Mf();fa();xa();Dr();hc();$r();uh();Ur();vc();Hr=class{static{a(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(jn),i=await this.store.countFiles()>0;(t.full||i&&r!==Fn)&&await this.wipe();let s=await this.store.getAllFiles(),o;if(t.onlyChangedSince!==void 0){if(s.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let w=la(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(w===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");o=w}else o=Nf(this.repoRoot);let c=new Set(o.map(w=>w.path)),l=new Map(s.map(w=>[w.path,w])),d=s.length>0&&!t.full,u={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},p=!1,h=a(async()=>{p||(p=!0,await this.store.setMeta(as,"1"))},"markEdgesDirty");for(let w of s)c.has(w.path)||(await h(),await this.store.deleteFile(w.path),u.filesDeleted++);let m=0;for(let w of o){m++;let b=Of(this.repoRoot,w.path);if(!b){u.filesSkipped++;continue}let k=l.get(w.path);if(k&&k.mtimeMs===b.mtimeMs&&k.size===b.size){u.filesSkipped++;continue}let S=this.readRepoFile(w.path);if(S===null){u.filesSkipped++;continue}let R=Ki(S);if(k&&k.contentHash===R){await this.store.upsertFile({...k,mtimeMs:b.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let D=await this.parser.parse(w.path,S,w.language),F=new Map;for(let U of D.nodes)F.set(U.nodeKey,mh(U));let H={path:w.path,language:w.language,contentHash:R,mtimeMs:b.mtimeMs,size:b.size,indexedAt:n};await h(),await this.store.replaceFileNodes(H,D.nodes,F,{contains:D.edges,refs:D.refs,imports:D.imports,exports:D.exports}),u.filesParsed++,t.onProgress?.({path:w.path,done:m,total:o.length})}let g=hf(this.repoRoot),y=await this.store.getMeta(_c)!==g.fingerprint;if(p||y||await this.store.getMeta(as)==="1"){let w=xf(await this.store.getNameIndex()),b=new Cn(g.config,w.files),k=Sf(await this.store.getAllFacts(),w,b);await this.store.replaceCrossFileEdges(k),await this.store.setMeta(_c,g.fingerprint),await this.store.setMeta(as,"0")}if(this.embedder&&t.embed){let w=await this.store.getNodesByKinds([...Zo]),b=await this.store.getEmbeddingContentHashes(),k=[];for(let R of w){let D=uf(R),F=Ki(`${this.embedder.recipeVersion}\0${D}`);b.get(R.nodeKey)!==F&&k.push({nodeKey:R.nodeKey,text:D,hash:F})}let S=64;for(let R=0;R<k.length;R+=S){let D=k.slice(R,R+S),F=await this.embedder.embedDocuments(D.map(U=>U.text));await this.store.upsertEmbeddings(D.map((U,N)=>({nodeKey:U.nodeKey,dim:this.embedder.dim,vec:F[N],contentHash:U.hash})));let H=Math.min(R+S,k.length);t.onProgress?.({path:"embedding symbols",done:H,total:k.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(cs,this.embedder.recipeVersion),await this.store.setMeta(ls,this.embedder.model),await this.store.setMeta(ds,String(this.embedder.dim))}await this.store.setMeta(jn,Fn),await this.store.setMeta(yc,String(n));let v=Rr(this.repoRoot);return v&&await this.store.setMeta(Un,v),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(yc);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(Un),schemaVersion:await this.store.getMeta(jn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=zt(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let o of i){let c=await this.store.getNode(o.nodeKey);c&&s.push({..._h(c),score:o.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=zt(n.limit,20,100),i=await this.embedder.embedQuery(t),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:ff(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of o){let d=await this.store.getNode(l.nodeKey);d&&c.push({..._h(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=zt(n.maxDepth,3,5),s=zt(n.limit,100,1e3),o=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let h=[];for(let m of u){let g=await this.store.neighbors(m,r,o,s);for(let y of g){let v=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(v))continue;if(l.add(v),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let w=r==="out"?y.dstKey:y.srcKey;d.has(w)||(d.add(w),h.push(w))}}u=h}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=gh(yh.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 o of n)i[o.kind]=o.count;let s={};for(let o of r)s[o.language]=o.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(zt(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=la(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=zt(t.limit,64,200),i=[],s=0;for(let o of n){let c=await this.store.getNodesByFile(o.path);c.length>0&&s++,i.push(...c)}return i.sort((o,c)=>o.filePath.localeCompare(c.filePath)||o.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Wi(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(Rr(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Hf(this.repoRoot,n,t)}async checkDivergence(t={}){return Cr(this.repoRoot,t)}async checkNumberCollisions(t={}){return Gt(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Bt(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Wt(this.repoRoot,t)}async reviewDetectors(t={}){return fc(this.repoRoot,t)}async reviewDetectorScopes(t={}){return mc(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Wi(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Pf(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",o=dh({paths:n,hunks:i,readUntracked:a(h=>this.readRepoFileHead(h,Df),"readUntracked")}),c=If(n.keys()),l=zt(t.limit,64,t.attest?ft:200),d=[],u=0,p=0;for(let h of c){let m=await this.store.getNodesByFile(h.path);if(m.length===0)continue;u++;let g=await this.store.getFile(h.path),y=this.readRepoFile(h.path),v=g!==null&&y!==null&&Ki(y)!==g.contentHash;v&&(p++,s==="full"&&(s="partial"));let w=n.get(h.path)??"modified",b=i.get(h.path);for(let k of m)d.push(I0(k,w,b,v))}return d.sort((h,m)=>bh(h.change)-bh(m.change)||(h.filePath<m.filePath?-1:h.filePath>m.filePath?1:0)||h.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:o,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:Rr(this.repoRoot),dirty:da(this.repoRoot),baseSha:t.since?Vi(this.repoRoot,t.since):null,mergeBaseSha:t.since?ca(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 gh(yh.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};a(_h,"toHit");a(zt,"clampLimit");a(bh,"changeRank");a(I0,"classifyReviewSymbol")});var wh=_(()=>{"use strict";ae()});var N0,I1,vh=_(()=>{"use strict";ae();N0=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],I1=new RegExp(N0.join("|"),"g")});import{existsSync as xc,readdirSync as C0,readFileSync as O0}from"node:fs";import{spawnSync as D0}from"node:child_process";import{dirname as P0,join as us,posix as Sc}from"node:path";function xh(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 ${Ec} 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 ${Ec} 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,h=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${h?`: ${h}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),s=new Set(e.fileVersions),o=e.fileVersions.filter(p=>!i.has(p)).sort(Ke);o.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${o.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${o.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:o});let c=r.versions.filter(p=>!s.has(p)).sort(Ke),l=new Map,d=[];for(let p of c){let h=e.siblingVersions.get(p);if(h){let m=l.get(h)??[];m.push(p),l.set(h,m)}else d.push(p)}for(let[p,h]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${h.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${h.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:h});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),h=e.fileVersions.filter(g=>!p.has(g)).sort(Ke),m=e.remote.versions.filter(g=>!s.has(g)).sort(Ke);h.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${h.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${h.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:h}),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 Sh(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Th(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(`
|
|
129
|
-
`).filter(Boolean).slice(-1)[0]}}function
|
|
130
|
-
`).map(i=>i.trim()).filter(Boolean)}}function
|
|
131
|
-
`)){if(!s.startsWith("worktree "))continue;let o=s.slice(9).trim();if(!o||o===i||!
|
|
132
|
-
|
|
133
|
-
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:s})}function
|
|
134
|
-
`,{encoding:"utf8",mode:384});try{
|
|
135
|
-
`,{encoding:"utf8",mode:384});try{
|
|
136
|
-
`,{encoding:"utf8",mode:384}),ST(o,s)}catch{}}function qh(e=Ee()){try{let t=JSON.parse(xT(zh(e),"utf8"));return t.v!==1||typeof t.at!="string"||!AT.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 AT,RT,IT,Gc=_(()=>{"use strict";oe();AT=["ok","paired","auth_failed","not_paired"],RT="connection-state.json",IT=200;a(zh,"connectionStatePath");a(NT,"redactDetail");a(Zt,"writeConnectionState");a(qh,"readConnectionState")});var G,Xe=_(()=>{"use strict";G="0.83.0"});import{execFileSync as Yh}from"node:child_process";import{createHash as CT}from"node:crypto";function OT(e){return CT("sha256").update(e).digest("hex")}function DT(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 ws(e){let t=DT(e);return t?OT(t):null}function z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&PT.test(e))return e;let t;try{t=Yh("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?ws(t):null}function Jh(e){let t;try{t=Yh("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?ws(t):null}var PT,Pe=_(()=>{"use strict";a(OT,"sha256Hex");a(DT,"normalizeRemoteUrl");a(ws,"projectKeyFromRemote");PT=/^[a-f0-9]{64}$/;a(z,"computeProjectKey");a(Jh,"projectKeyForRepo")});import MT from"node:path";import{fileURLToPath as LT}from"node:url";function $T(e,t=MT.sep){return e.split(t).includes("_npx")}function Me(e){let t=e.extraArgs??[],n=a(r=>({command:"npx",args:["-y",Zh,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):$T(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 Le(){try{let e=LT(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Kn(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Xh(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Xh(n)).join(" ")}function vs(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Zh)}function ks(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Xh(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Zh,Vn=_(()=>{"use strict";Zh="@maind-dev/mcp-bridge";a($T,"isEphemeralEntry");a(Me,"resolveBridgeLaunch");a(Le,"currentBridgeEntry");a(Kn,"launchToShellCommand");a(vs,"isNpxForm");a(ks,"isLegacyHookForm");a(Xh,"shellQuote")});import*as Q from"node:path";function eg(e){let t=e.launch??Me({entryPath:Le(),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 jT(e){switch(e.platform){case"darwin":return Q.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??Q.join(e.homeDir,"AppData","Roaming");return Q.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??Q.join(e.homeDir,".config");return Q.join(t,"Claude","claude_desktop_config.json")}}}function tg(e){switch(e.platform){case"darwin":return Q.join(e.homeDir,"Library","Application Support","Code","User");case"win32":{let t=e.appData??Q.join(e.homeDir,"AppData","Roaming");return Q.join(t,"Code","User")}default:{let t=e.xdgConfigHome??Q.join(e.homeDir,".config");return Q.join(t,"Code","User")}}}function UT(e){return Q.join(tg(e),"mcp.json")}function Vr(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:Q.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:Q.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:jT(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:Q.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:Q.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:UT(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{dir:tg(e),skipDetail:"VS Code not found (no User profile dir)"}},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Q.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function ng(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function rg(e){return e.jsonShape??FT}function xs(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Qh(e.env.XDG_CONFIG_HOME),appData:Qh(e.env.APPDATA)}}function Qh(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}var FT,zr,qr=_(()=>{"use strict";Vn();FT={serversKey:"mcpServers"};a(eg,"buildMaindServerEntry");a(jT,"claudeDesktopConfigPath");a(tg,"vsCodeUserDir");a(UT,"vsCodeUserMcpPath");a(Vr,"getClientTargets");a(ng,"filterTargetsByFamily");a(rg,"jsonShapeOf");zr=[...new Set(Vr({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];a(xs,"makeDefaultContext");a(Qh,"nonEmpty")});import*as J from"node:fs/promises";import*as Es from"node:path";async function ce(e){try{return await J.readFile(e,"utf8")}catch(t){if(BT(t))return null;throw t}}async function pg(e){try{return await J.access(e),!0}catch{return!1}}async function Bc(e){await J.mkdir(e,{recursive:!0})}async function ee(e,t,n){let r=Es.dirname(e);await Bc(r);let i=Es.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await J.writeFile(i,t,{encoding:"utf8",mode:n});try{await J.rename(i,e)}catch(s){if(WT(s))try{await J.copyFile(i,e),await J.unlink(i).catch(()=>{}),n!==void 0&&await J.chmod(e,n).catch(()=>{});return}catch(o){throw await J.unlink(i).catch(()=>{}),o}throw await J.unlink(i).catch(()=>{}),s}}async function fg(e,t){let n=await ce(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function BT(e){return mg(e)&&e.code==="ENOENT"}function WT(e){return!mg(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function mg(e){return typeof e=="object"&&e!==null&&"code"in e}var $e=_(()=>{"use strict";a(ce,"readFileSafe");a(pg,"fileExists");a(Bc,"ensureDir");a(ee,"atomicWriteFile");a(fg,"hasLinePrefix");a(BT,"isNoEnt");a(WT,"isWindowsRenameFailure");a(mg,"isNodeError")});import{existsSync as fA}from"node:fs";import*as wg from"node:path";function en(e,t={},n=zc){let r=t.fileExists??fA,i=t.expectedCommand??mA,s={};if(e!==null&&e.trim().length>0)try{let o=JSON.parse(e);Vc(o)&&(s=o)}catch{}return n.map(o=>{let c={event:o.event,subcommand:o.subcommand},l=hA(s,o.event,o.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${o.label} is not wired \u2014 this bridge can run '${o.subcommand}', but nothing calls it.`};let d=` Replace its command with: ${i(o.subcommand)}`;if(ks(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${o.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+d};if(vs(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${o.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+d};let u=gA(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${o.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${o.label} is wired.`}})}function qc(e){return e.some(t=>t.status!=="ok")}function Rs(e){return e.some(t=>t.remedy==="run-install")}function mA(e){return Kn(Me({entryPath:Le(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function hA(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Vc(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!Vc(o))continue;let c=o.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function gA(e){for(let t of yA(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return wg.isAbsolute(t)?t:null;return null}function yA(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 Vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zc,As,Yn=_(()=>{"use strict";Vn();zc=[{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:"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:"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."}],As=[{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."},{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."}];a(en,"inspectHookWiring");a(qc,"hasWiringDrift");a(Rs,"needsInstallRun");a(mA,"defaultExpectedCommand");a(hA,"findCommand");a(gA,"extractScriptPath");a(yA,"tokenize");a(Vc,"isObject")});import*as Xc from"node:path";import*as kg from"node:readline";async function xg(e,t){let n=Xc.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 ce(n)}catch(h){return{target:r,action:"merge",status:"failed",detail:`read: ${Yc(h)}`}}let s,o="create";if(i===null||i.trim().length===0)s={};else{o="merge";try{let h=JSON.parse(i);if(!Jc(h))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};s=h}catch(h){return{target:r,action:"merge",status:"failed",detail:`parse: ${Yc(h)}`}}}let c=bA(s,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:o==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await wA(e.out,`
|
|
137
|
-
Merge a ${t.event} hook into ${n}?
|
|
138
|
-
${t.consentDescription}
|
|
139
|
-
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=s.hooks?.[t.event]??[],u={...s,hooks:{...s.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
140
|
-
`;if(e.dryRun)return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:n};try{await ee(n,p,384)}catch(h){return{target:r,action:"merge",status:"failed",detail:`write: ${Yc(h)}`}}return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:n}}async function Sg(e){let t=Xc.join(e.homeDir,vg);return xg(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:a(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${vg} into every new Claude Code session.`})}function _A(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Zc(e,t){let n=e.launch??Me({entryPath:Le(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Kn(n);return xg(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:_A(t),skipDetail:a(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return ks(i)?`${s}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:vs(i)?`${s}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:s},"skipDetail"),consentDescription:t.consentDescription})}async function Eg(e){let t=[];for(let n of zc)t.push(await Zc(e,n));return t}function bA(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Jc(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!Jc(o))continue;let c=o.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function wA(e,t){e.write(t);let n=kg.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function Jc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yc(e){return e instanceof Error?e.message:String(e)}var vg,Qc=_(()=>{"use strict";$e();Vn();Yn();vg=".claude/maind-session-start-reminder.md";a(xg,"mergeClaudeHook");a(Sg,"mergeSessionStartHook");a(_A,"targetKeyFor");a(Zc,"mergeSubcommandHook");a(Eg,"mergeAllSubcommandHooks");a(bA,"findExistingHookCommand");a(wA,"promptYesNo");a(Jc,"isObject");a(Yc,"errMessage")});import{existsSync as vA,readFileSync as kA}from"node:fs";import{join as xA}from"node:path";function Qe(){return xA(Ee(),"config.json")}function Fe(){try{let e=Qe();if(!vA(e))return null;let t=JSON.parse(kA(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),r}catch{return null}}var Jn=_(()=>{"use strict";oe();a(Qe,"bridgeConfigPath");a(Fe,"readBridgeConfig")});function Is(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function wt(e){return e+1}function Ns(e){return(e.text.split(`
|
|
141
|
-
`,1)[0]??"").trim().slice(0,200)}function CA(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 OA(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=CA(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function el(e,t,n,r){for(let i of OA(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function Xr(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 bt(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 bt(t.childForFieldName("name"));case"parenthesized_type":return bt(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?bt(n[0]):"#"}default:return"#"}}function PA(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function tl(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 Zr(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),s=bt(n.childForFieldName("type"))??tl(i)??(PA(i)?"#":null);s&&t.set(r.text,s)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=bt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function vt(e,t,n,r,i={locals:Zr(n)}){let s=new Set,o=a(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(s.has(d))return;s.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...DA]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")o(Xr(l.childForFieldName("function")));else if(l.type==="new_expression")o(Xr(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;o(Xr(d))}}var DA,Cs=_(()=>{"use strict";a(Is,"newResult");a(wt,"line1");a(Ns,"signatureOf");a(CA,"calleeName");a(OA,"collectCallTargets");a(el,"addCallRefs");a(Xr,"calleeRef");DA=["jsx_opening_element","jsx_self_closing_element"];a(bt,"typeNameOf");a(PA,"isMethodCallResult");a(tl,"newTypeOf");a(Zr,"collectTypeHints");a(vt,"addTsRefs")});function Pg(e,t){let n=Is();for(let r of e.namedChildren)MA(r,t,n);return n}function Mg(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function MA(e,t,n){let r=Mg(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??$A(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=Os(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=r.childForFieldName("body");o&&el(n,s.nodeKey,o,Dg);return}case"class_definition":LA(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(o=>o.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let o=Os(r,t,s.text,s.text,"variable");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}return}default:return}}function LA(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Os(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let o=e.childForFieldName("body");if(o)for(let c of o.namedChildren){let l=Mg(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=Os(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&el(n,p.nodeKey,h,Dg)}}function Os(e,t,n,r,i){return{nodeKey:Oe(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:wt(e.startPosition.row),endLine:wt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Ns(e),doc:null}}function $A(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var Dg,Lg=_(()=>{"use strict";On();Cs();Dg="call";a(Pg,"extractPython");a(Mg,"unwrapDecorated");a(MA,"handleTopLevel");a(LA,"addClass");a(Os,"makeNode");a($A,"firstDottedName")});function Fg(e,t){let n=Is(),r=t.language!=="typescript";for(let i of e.namedChildren)jA(i,t,n,r);return GA(e,t,n),n}function FA(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function jA(e,t,n,r){if(e.type==="export_statement"&&UA(e,t,n,r))return;let i=FA(e),s=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":HA(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let o=$g(i,t,n,"function",r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"class_declaration":case"abstract_class_declaration":{let o=WA(i,t,n,r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"interface_declaration":nl(i,t,n,"interface");return;case"type_alias_declaration":nl(i,t,n,"type_alias");return;case"enum_declaration":nl(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let o of i.namedChildren){if(o.type!=="variable_declarator")continue;let c=o.childForFieldName("name"),l=o.childForFieldName("value");if(!c||c.type!=="identifier"){l&&vt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";$g(o,t,n,d?"function":"variable",r,c,l)}return}default:vt(n,t.moduleKey,i,r);return}}function UA(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=il(e.childForFieldName("source")),s=e.namedChildren.find(l=>l.type==="export_clause"),o=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),s)for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(o){let l=o.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(s){for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):vt(n,t.moduleKey,c,r),!0):!1}function HA(e,t,n){let r=il(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),s=[],o=a((c,l)=>{s.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")o("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&o("*",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&&o(d,l.childForFieldName("alias")?.text??d)}s.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...s)}function GA(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,s=i?.type==="string"?il(i):null;if(s===null)continue;let c=BA(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:s})}}function BA(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function $g(e,t,n,r,i,s,o){let l=(s??e.childForFieldName("name"))?.text;if(!l)return null;let d=Ds(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=o??e.childForFieldName("body")??e;vt(n,d.nodeKey,u,i,{locals:Zr(e)})}else o&&vt(n,d.nodeKey,o,i);return d}function nl(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Ds(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function WA(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let s=Ds(e,t,i,i,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of o?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(p=>({kind:"implements",ref:rl(p)})):[{kind:"extends",ref:rl(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:h}of u)h&&n.refs.push({fromKey:s.nodeKey,kind:p,targetName:h.name,receiver:h.receiver})}let c=e.childForFieldName("body");if(!c)return s;let l=KA(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&vt(n,s.nodeKey,g,r,{locals:Zr(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,h=Ds(d,t,u,p,"method");n.nodes.push(h),n.edges.push({srcKey:s.nodeKey,dstKey:h.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&vt(n,h.nodeKey,m,r,{locals:Zr(d),thisFields:l})}return s}function KA(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=bt(n.childForFieldName("type"))??tl(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(o=>o.type==="accessibility_modifier"||o.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),s=bt(r.childForFieldName("type"));i?.type==="identifier"&&s&&t.set(i.text,s)}return t}function Ds(e,t,n,r,i){return{nodeKey:Oe(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:wt(e.startPosition.row),endLine:wt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Ns(e),doc:null}}function rl(e){if(!e)return null;switch(e.type){case"generic_type":return rl(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 Xr(e);default:return null}}function il(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var jg=_(()=>{"use strict";On();Cs();a(Fg,"extractTypescript");a(FA,"unwrapExport");a(jA,"handleTopLevel");a(UA,"handleExportForm");a(HA,"addImport");a(GA,"collectDynamicImports");a(BA,"enclosingDeclarator");a($g,"addFunctionLike");a(nl,"addSimpleNamed");a(WA,"addClass");a(KA,"classFieldTypes");a(Ds,"makeNode");a(rl,"heritageRef");a(il,"stringValue")});import{createRequire as VA}from"node:module";import{join as zA}from"node:path";function Gg(e,t){return t?zA(t,Ug[e]):VA(import.meta.url).resolve(`tree-sitter-wasms/out/${Ug[e]}`)}var Ug,Hg,Bg=_(()=>{"use strict";Ug={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Hg="tree-sitter.wasm";a(Gg,"grammarPath")});import{join as qA}from"node:path";import sl from"web-tree-sitter";var YA,Ps,Wg=_(()=>{"use strict";On();Ui();Lg();jg();Cs();Bg();YA=["typescript","tsx","javascript","python"],Ps=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await sl.init(this.assetDir?{locateFile:a(t=>qA(this.assetDir,t||Hg),"locateFile")}:void 0),this.parser=new sl,this.initialized=!0)}supports(t){return YA.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let o=s.rootNode,c=mt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:wt(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?Pg(o,d):Fg(o,d);return s.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await sl.Language.load(Gg(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as JA}from"node:module";function Vg(){return Kg("node:sqlite")}function Xn(){if(Qr)return Qr;try{let{DatabaseSync:e}=Vg(),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(),Qr={ok:!0}}finally{t.close()}}catch(e){Qr={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Qr}function XA(e){let{DatabaseSync:t}=Vg(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function ZA(e){let t=Kg("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}function QA(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Ms(e){let t=QA(),n=a(i=>{let s=i==="node:sqlite"?XA(e):ZA(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=Xn();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=Xn();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}var Kg,Qr,ol=_(()=>{"use strict";Kg=JA(import.meta.url);a(Vg,"loadBuiltin");Qr=null;a(Xn,"probeBuiltinSqlite");a(XA,"openBuiltin");a(ZA,"openBetter");a(QA,"backendOverride");a(Ms,"openSqliteDatabase")});function ey(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 ty(e,t,n,r){let i=new Map;for(let o of e)i.set(o.path,{filePath:o.path,language:o.language,refs:[],imports:[],exports:[]});let s=a(o=>i.get(String(o.file_path)),"entry");for(let o of t)s(o)?.refs.push({fromKey:String(o.src_key),kind:String(o.kind),targetName:String(o.target_name),receiver:nn(o.receiver),receiverType:nn(o.receiver_type)});for(let o of n){let c=s(o);if(!c)continue;let l={fromModuleKey:mt(c.filePath),specifier:String(o.specifier),importedName:nn(o.imported_name),localName:nn(o.local_name)};c.imports.push(l)}for(let o of r){let c={exportedName:String(o.exported_name),localName:nn(o.local_name),specifier:nn(o.specifier),importedName:nn(o.imported_name)};s(o)?.exports.push(c)}return[...i.values()]}var zg,qg,Yg,Jg,Xg,Zg,Qg,nn,ny=_(()=>{"use strict";On();zg=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],qg="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Yg="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Jg="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Xg="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Zg="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Qg="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";a(ey,"factRows");nn=a(e=>e==null?null:String(e),"str");a(ty,"assembleFacts")});function Ls(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 ry,ei,iy=_(()=>{"use strict";ol();Ur();ny();vc();a(Ls,"toNodeRow");ry=400,ei=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Ms(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(ph)}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 o=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)o.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=ey(t.path,i),u=this.db.prepare(qg);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Yg);for(let m of d.imports)p.run(...m);let h=this.db.prepare(Jg);for(let m of d.exports)h.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 ty(t,this.db.prepare(Xg).all(),this.db.prepare(Zg).all(),this.db.prepare(Qg).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 o of t)i.run(o);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of n)s.run(o.srcKey,o.dstKey,o.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?Ls(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Ls)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Ls)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Ls)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=hh(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
142
|
-
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
143
|
-
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
144
|
-
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
145
|
-
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
146
|
-
WHERE nodes_fts MATCH ?
|
|
147
|
-
ORDER BY score LIMIT ?`,o=this.db.prepare(s);return(n?o.all(i,n,r):o.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let o=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(o+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),o+=" LIMIT ?",c.push(i),this.db.prepare(o).all(...c).map(d=>({srcKey:d.src_key,dstKey:d.dst_key,kind:d.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
|
|
148
|
-
(SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
|
|
149
|
-
(SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
|
|
150
|
-
(SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
|
|
151
|
-
FROM nodes n
|
|
152
|
-
WHERE n.kind = 'module'
|
|
153
|
-
ORDER BY imports_in DESC, symbol_count DESC
|
|
154
|
-
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=ry)for(let o of n.slice(s,s+ry))r.run(o),i.run(o);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let s of zg)this.db.prepare(s).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
155
|
-
node_key, kind, name, qualified_name, file_path, language,
|
|
156
|
-
start_line, end_line, start_byte, end_byte, signature, doc
|
|
157
|
-
) 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)
|
|
158
|
-
VALUES(?, ?, ?, ?, ?, ?)
|
|
159
|
-
ON CONFLICT(path) DO UPDATE SET
|
|
160
|
-
language = excluded.language,
|
|
161
|
-
content_hash = excluded.content_hash,
|
|
162
|
-
mtime_ms = excluded.mtime_ms,
|
|
163
|
-
size = excluded.size,
|
|
164
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as eR}from"node:crypto";function Zn(e){return eR("sha256").update(e,"utf8").digest("hex")}function sy(e){return{node_key_hash:Zn(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Zn(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Zn(e.signature):null}}function oy(e){return{src_key_hash:Zn(e.srcKey),dst_key_hash:Zn(e.dstKey),kind:e.kind}}function ay(e,t,n){return{node_key_hash:Zn(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var cy=_(()=>{"use strict";a(Zn,"sha256");a(sy,"toCloudNode");a(oy,"toCloudEdge");a(ay,"toCloudEmbedding")});import{randomUUID as tR}from"node:crypto";function al(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ly(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function dy(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Qn,er,nR,cl=_(()=>{"use strict";Ur();cy();Qn=class extends Error{static{a(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},er=class{static{a(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(Un),lastSyncedAt:ly(await this.store.getMeta(bc))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(sy),n=(await this.store.getAllEdges()).map(oy),r=await this.store.getMeta(jn)??Fn,i=await this.store.getMeta(Un),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(v=>[v.language,v.count])),c=tR(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},d=0,u=al(t,this.chunk),p=al(n,this.chunk*2),h=Math.max(1,u.length+p.length);for(let v of u)await this.post("/api/codebase/push",{...l,nodes:v,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:h});for(let v of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:v,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:h});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let m=t.map(v=>v.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:h,total:h});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(bc,String(Date.now())),i&&await this.store.setMeta(fh,i),{nodes:t.length,edges:n.length,pruned:dy(g.nodes_deleted),edgesPruned:dy(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},o=(await this.store.allEmbeddings()).map(d=>ay(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&s[d.node_key_hash]!==d.content_hash);if(o.length===0)return 0;let c=al(o,nR),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 o.length}async embedMeta(){let t=await this.store.getMeta(cs),n=await this.store.getMeta(ls),r=ly(await this.store.getMeta(ds));if(!t||!n||!r)throw new Qn("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new Qn(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},nR=250;a(al,"chunkArray");a(ly,"numOrNull");a(dy,"numOr0")});var uy={};ne(uy,{CodeIndexSync:()=>er,DEFAULT_DB_RELPATH:()=>ll,SyncError:()=>Qn,createCodeIndexSync:()=>iR,createNodeCodeIndex:()=>Fs,openSqliteDatabase:()=>Ms,probeBuiltinSqlite:()=>Xn});import{mkdirSync as rR}from"node:fs";import{posix as $s}from"node:path";function Fs(e){let t=e.dbPath??$s.join(e.repoRoot,ll);rR($s.dirname(t),{recursive:!0}),e.dbPath===void 0&&Ar($s.dirname(t));let n=new ei(t),r=new Ps;return new Hr({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function iR(e){let t=e.dbPath??$s.join(e.repoRoot,ll),n=e.projectKey??am(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new ei(t);return new er(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var ll,dl=_(()=>{"use strict";Oa();Wg();kc();iy();cl();Gi();cl();ol();ll=".maind/code-index.sqlite";a(Fs,"createNodeCodeIndex");a(iR,"createCodeIndexSync")});import{execFileSync as py}from"node:child_process";import{existsSync as fy,realpathSync as my}from"node:fs";import{createRequire as sR}from"node:module";import{basename as oR,dirname as aR,isAbsolute as hy,join as cR,relative as gy,resolve as js,sep as yy}from"node:path";function _y(){let e=Xn();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return sR(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 by(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 fe(e=process.cwd()){try{let t=py("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 vy(e,t=fe(),n=process.cwd()){let r=hy(e)?[e]:[js(t,e),js(n,e)];for(let i of r){let s=aR(i);if(!fy(s))continue;let o;try{o=my(s)}catch{continue}let c=ky(o);if(c===null)continue;let l=gy(c,cR(o,oR(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(yy).join("/")}}return null}function tr(e,t=fe(),n=process.cwd()){let r=hy(e)?[e]:[js(t,e),js(n,e)];for(let i of r){if(!fy(i))continue;let s;try{s=my(i)}catch{continue}let o=ky(s);if(o===null)continue;let c=gy(o,s);if(!c.startsWith(".."))return{repoRoot:o,repoRelDir:c===""?"":c.split(yy).join("/")}}return null}function ky(e){try{let t=py("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 xy(){return Fs({repoRoot:fe()})}function Sy(e){return Fs({repoRoot:e})}var wy,rn=_(()=>{"use strict";dl();a(_y,"probeNativeStore");a(by,"isNativeStoreUnavailable");wy="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.";a(fe,"resolveRepoRoot");a(vy,"resolveRepoRootForPath");a(tr,"resolveRepoRootForDir");a(ky,"gitToplevelOf");a(xy,"defaultEngineFactory");a(Sy,"engineForRoot")});import{mkdirSync as Cy,rmdirSync as Oy,statSync as pR}from"node:fs";import{join as Dy}from"node:path";import{setTimeout as fR}from"node:timers/promises";function Py(e){return Dy(e,".maind","index-refresh.lock")}function Gs(e,t=Date.now()){let n=Py(e);try{if(t-pR(n).mtimeMs<mR)return!1;Oy(n)}catch{}try{return Cy(n,{recursive:!1}),!0}catch{return!1}}function ti(e){try{Oy(Py(e))}catch{}}async function My(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(o=>fR(o).then(()=>{})),s=r()+(n.waitMs??3e4);try{Cy(Dy(e,".maind"),{recursive:!0})}catch{}for(;!Gs(e,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{ti(e)}}var mR,ul=_(()=>{"use strict";mR=30*6e4;a(Py,"lockPath");a(Gs,"acquireLock");a(ti,"releaseLock");a(My,"withIndexLock")});import{execFile as Xy}from"node:child_process";import{randomUUID as $R}from"node:crypto";function BR(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return yl.test(t)?t:$R()}function _l(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function WR(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 KR(e){return await new Promise(t=>{Xy("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(VR(r))})})}function VR(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 zR(){return await new Promise(e=>{Xy("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 qR(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function YR(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=yl.test(r)&&r===t?"env":"random";return{current:a(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:a(()=>!1,"tryUpgrade"),adopt:a(s=>{yl.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:a(()=>null,"activityAtMs")}}var Jy,Zy,FR,jR,UR,HR,GR,yl,Vs,bl=_(()=>{"use strict";Jn();Jy=45e3,Zy=3e4,FR=5,jR=120,UR=3e4,HR=15*6e4,GR=1500,yl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(BR,"resolveClientSessionId");a(_l,"autoAnnounceDisabled");a(WR,"autoWorkingPathsEnabled");Vs=class{static{a(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??Fe)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??zR,this.gitBranchObject=t.gitBranchObject??KR,this.log=t.log??(i=>process.stderr.write(i+`
|
|
165
|
-
`)),this.machineLabel=qR(r?.machine_label),this.enabled=this.projectKey!==null&&!_l(n,r),this.workingPathsEnabled=WR(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??YR(n,BR(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<Jy||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<Jy||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<FR||(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,GR).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(UR*2**(this.consecutiveFailures-1),HR);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let s=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${s} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:jR,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let s=await this.gitBranch();if(s&&(r.branch=s),this.lastBranch=s,s)try{let o=await this.gitBranchObject(s);o!==null&&o!==this.lastSentObjectId&&(r.object_ids=[o],this.lastSentObjectId=o)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let o=await this.sessionMeta();o?.model&&(r.model=o.model),o?.title&&(r.title=o.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let o=await this.deriveWorkingPaths();o&&o.length>0&&(r.working_paths=o)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let s=i;if(s.ok===!0&&typeof s.session_id=="string")try{this.identity.adopt(s.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let s={sessionId:this.sessionId,branch:this.lastBranch},o=typeof i=="object"?i:null;if(o!==null&&o.ok===!0)this.snapshot.write(i,s);else if(this.snapshot.markFailed){let c=o!==null&&typeof o.error=="string"?o.error:"announce_failed";this.snapshot.markFailed(c,s)}}}catch{}}};a(KR,"defaultGitBranchObject");a(VR,"normalizeObjectId");a(zR,"defaultGitBranch");a(qR,"normalizeMachineLabel");a(YR,"staticIdentity")});import{mkdirSync as Qy,readdirSync as r_,readFileSync as JR,renameSync as e_,statSync as XR,unlinkSync as wl,writeFileSync as t_}from"node:fs";import{homedir as ZR}from"node:os";import{join as nr}from"node:path";function i_(){return nr(ZR(),".maind","presence")}function s_(e,t){return nr(e,t)}function o_(e){let t=e.baseDir??i_(),n=s_(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,s=e.cwd??process.cwd(),o=e.now??Date.now,c=null,l=a(d=>{if(c!==null&&c!==d)try{wl(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 h={v:1,written_at:new Date(o()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[]};Qy(n,{recursive:!0,mode:448});let m=nr(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;t_(g,JSON.stringify(h),{mode:384}),e_(g,m),l(m),n_(n,o(),m)}catch{}},endSession(){try{c&&wl(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(o()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};Qy(n,{recursive:!0,mode:448});let h=nr(n,`${u.sessionId}.json`),m=`${h}.tmp-${r}`;t_(m,JSON.stringify(p),{mode:384}),e_(m,h),l(h),n_(n,o(),h)}catch{}}}}function n_(e,t,n){try{for(let r of r_(e)){if(!r.endsWith(".json"))continue;let i=nr(e,r);if(i!==n)try{t-XR(i).mtimeMs>QR&&wl(i)}catch{}}}catch{}}function rr(e,t=i_()){try{let n=s_(t,e),r=[];for(let i of r_(n))if(i.endsWith(".json"))try{let s=JSON.parse(JR(nr(n,i),"utf8")),o=eI(s);o&&r.push(o)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function eI(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}:{}}}var QR,zs=_(()=>{"use strict";QR=120*6e4;a(i_,"presenceSnapshotBaseDir");a(s_,"projectDir");a(o_,"createSnapshotStore");a(n_,"pruneStale");a(rr,"readSnapshots");a(eI,"parseSnapshot")});import{execFileSync as tI}from"node:child_process";import{createHash as nI,randomUUID as rI}from"node:crypto";import{existsSync as iI,mkdirSync as sI,readdirSync as oI,readFileSync as c_,renameSync as aI,statSync as vl,unlinkSync as l_,writeFileSync as cI}from"node:fs";import{homedir as lI}from"node:os";import{basename as dI,join as kt}from"node:path";function ir(e){return kt(e??kt(lI(),".maind","presence"),"identity")}function ri(e,t){if(e){let n=dI(e).replace(/\.jsonl$/i,"");if(ni.test(n))return n.toLowerCase()}return t&&ni.test(t)?t.toLowerCase():null}function d_(e){let t=e.nowMs??Date.now();sI(e.dir,{recursive:!0,mode:448});let n=kt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(c_(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=e.transcriptPath??i.transcript_path,o=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...s?{transcript_path:s}:{},...o?{model:o}:{}};cI(r,JSON.stringify(c,null,2)+`
|
|
166
|
-
`,{mode:384}),aI(r,n),hI(e.dir,t)}function u_(e,t,n,r=Date.now()){try{let i=vl(kt(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function p_(e,t){try{l_(kt(e,`${t}.json`))}catch{}}function hI(e,t){try{for(let n of oI(e))if(n.endsWith(".json"))try{let r=vl(kt(e,n));t-r.mtimeMs>pI&&l_(kt(e,n))}catch{}}catch{}}function gI(e){return f_(e)?.file??null}function f_(e){let t=kt(e.dir,`${e.agentPid}.json`);try{if(!iI(t))return null;let n=vl(t);if(n.mtimeMs<e.bridgeStartMs-fI)return null;let r=JSON.parse(c_(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!ni.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!yI(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function a_(e){return e.replace(/\/+$/,"")}function yI(e,t){let n=a_(e),r=a_(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function _I(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=nI("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=i.toString("hex");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function bI(e){if(process.platform==="win32")return null;try{let t=tI("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function wI(){try{return Z()}catch{return null}}var ni,uI,pI,fI,mI,qs,Ys=_(()=>{"use strict";oe();ni=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,uI=8,pI=48*60*6e4,fI=6e4,mI="9f3c72da-2f10-4b8f-9c31-ad291c0de291";a(ir,"identityDirPath");a(ri,"transcriptStemOf");a(d_,"writeAgentIdentityFile");a(u_,"identityFileStale");a(p_,"deleteAgentIdentityFile");a(hI,"pruneIdentityDir");a(gI,"readAgentIdentityFile");a(f_,"readAgentIdentityEntry");a(a_,"normDir");a(yI,"sameSessionTree");a(_I,"uuidV5");a(bI,"processStartTime");qs=class{static{a(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??ir(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=ni.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??wI)(),s=(t.ppidStart??bI)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=_I(`${i}|${this.agentPid}|${s}|${t.projectKey}`,mI),this.source="derived";return}this.id=rI(),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(!ni.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>uI&&this.aliases.shift())}activityAtMs(){return f_({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 gI({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};a(wI,"defaultDeviceId")});function kl(){return{ultracode:!1,planMode:!1,autoMode:!1}}var xl=_(()=>{"use strict";a(kl,"newModeState")});import{createReadStream as vI,existsSync as kI}from"node:fs";import{stat as xI}from"node:fs/promises";import{createInterface as SI}from"node:readline";async function Sl(e){if(!e||!kI(e))return null;let t;try{t=await xI(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(o=>{let c=vI(e,{encoding:"utf-8"}),l=SI({input:c});l.on("line",d=>{let u=d.trim();if(u){s++;try{let p=JSON.parse(u),h=p.message?.usage;if(!h)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 h.input_tokens=="number"&&(r+=h.input_tokens),typeof h.output_tokens=="number"&&(i+=h.output_tokens)}catch{}}}),l.on("close",()=>{o({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:s,last_modified_ms:t.mtimeMs})}),l.on("error",()=>o(null)),c.on("error",()=>o(null))})}var m_=_(()=>{"use strict";a(Sl,"summariseTranscript")});var h_=_(()=>{"use strict"});function ii(e){if(!e)return null;let t=null;for(let n of e.matchAll(TI)){let r=n[1].toLowerCase();EI.has(r)&&(t=r)}return t}var EI,TI,Js=_(()=>{"use strict";EI=new Set(["low","medium","high","xhigh","max"]),TI=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;a(ii,"detectEffortLevel")});import{createReadStream as AI,existsSync as RI,readdirSync as II}from"node:fs";import{basename as __,dirname as NI,join as g_}from"node:path";import{createInterface as CI}from"node:readline";function sr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function PI(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=DI[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&t.push(s)}return t}function Xs(e){let t=__(e).replace(/\.jsonl$/,""),n=g_(NI(e),t,"subagents"),r;try{r=II(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>g_(n,i))}async function y_(e,t,n,r,i){RI(e)&&await new Promise(s=>{let o=AI(e,{encoding:"utf-8"}),c=CI({input:o}),l=0;c.on("line",d=>{l++;let u=d.trim();if(!u)return;let p;try{p=JSON.parse(u)}catch{return}if(p.message?.role!=="assistant")return;let h=typeof p.message.id=="string"&&p.message.id?p.message.id:null,m=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=h??m??`${e}#${l}`,y=PI(p.message.content),v=r.get(g);if(v){for(let R of y)v.edited_paths.includes(R)||v.edited_paths.push(R);return}if(n.has(g))return;n.add(g);let w=p.message.usage??{},b=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,k=typeof p.message.model=="string"&&p.message.model?p.message.model:"",S={ts:Number.isFinite(b)?b:0,model:k||"<unknown>",synthetic:k===OI,input_tokens:sr(w.input_tokens),output_tokens:sr(w.output_tokens),cache_read_tokens:sr(w.cache_read_input_tokens),cache_creation_tokens:sr(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(sr(w.cache_creation?.ephemeral_1h_input_tokens),sr(w.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:y,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(g,S),i.push(S)}),c.on("close",()=>s()),c.on("error",()=>s()),o.on("error",()=>s())})}function El(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 si(e){let t=new Set,n=new Map,r=[],i=e?Xs(e):[];if(!e)return{turns:r,subagent_files:i};let s=[];await y_(e,an,t,n,s),El(s),r.push(...s);for(let o of i){let c=[],l=__(o).replace(/\.jsonl$/,"");await y_(o,l,t,n,c),El(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var an,OI,DI,Zs=_(()=>{"use strict";an="main",OI="<synthetic>",DI={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};a(sr,"num");a(PI,"editedPathsOf");a(Xs,"subagentFilesOf");a(y_,"readStream");a(El,"fillTimestamps");a(si,"collectTurns")});import{createReadStream as b_,existsSync as MI}from"node:fs";import{createInterface as w_}from"node:readline";function GI(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,o=e.get(s);if(!o){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}o.turns++,o.output_tokens+=r,i>0&&((o.first_ts===0||i<o.first_ts)&&(o.first_ts=i),i>o.last_ts&&(o.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 BI(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
167
|
-
`)}function WI(e,t){let n=a(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,o]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)o.has(l)&&c++;return c/s.size>=.8}function KI(e,t,n){return LI.test(e)?{polarity:-1,magnitude:or.rework,kind:"rework"}:n&&$I.test(e)?{polarity:-1,magnitude:or.correction,kind:"correction"}:FI.test(e)?{polarity:1,magnitude:or.acceptance,kind:"acceptance"}:t!==null&&WI(t,e)?{polarity:-1,magnitude:or.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function VI(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:v_,behaviour_measured:!0}}async function zI(e,t){for(let n of Xs(e))await new Promise(r=>{let i=w_({input:b_(n,{encoding:"utf-8"})});i.on("line",s=>{let o=s.trim();if(!o)return;let c;try{c=JSON.parse(o)}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(eo))continue;let d=l.name.slice(eo.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 Tl(e,t={}){let n=VI("");if(!e||!MI(e))return n;let r=t.turns??(await si(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=[],s=new Map,o=null,c=!1,l=null;await new Promise(m=>{let g=b_(e,{encoding:"utf-8"}),y=w_({input:g}),v=a(w=>{let b=w.trim();if(!b)return;let k;try{k=JSON.parse(b)}catch{return}if(n.lines_seen++,!n.session_id){let j=k.sessionId??k.session_id;typeof j=="string"&&j&&(n.session_id=j)}k.type==="ai-title"&&typeof k.aiTitle=="string"&&k.aiTitle&&(n.ai_title=k.aiTitle),typeof k.slug=="string"&&k.slug&&(n.session_slug=k.slug);let S=k.message?.role,R=k.isSidechain===!0;if(S==="assistant")for(let j of Qs(k.message?.content)){if(j.type!=="tool_use"||typeof j.name!="string"||!j.name.startsWith(eo))continue;let he=j.name.slice(eo.length);he&&(n.maind_tool_calls??={},n.maind_tool_calls[he]=(n.maind_tool_calls[he]??0)+1)}if(R)return;if(S==="assistant"){let j=Qs(k.message?.content),he=!1;for(let _n of j)_n.type==="tool_use"&&(n.tool_calls++,he=!0,_n.name==="AskUserQuestion"&&n.agent_questions++);c=he;return}if(S!=="user")return;let D=Qs(k.message?.content),F=BI(D);if(F.includes(jI)){n.interrupts++,i.push({polarity:-1,magnitude:or.interrupt,kind:"interrupt"});return}if(D.some(j=>j.type==="tool_result"&&j.is_error===!0&&typeof j.content=="string"&&j.content.includes(UI))){n.tool_denials++,i.push({polarity:-1,magnitude:or.denial,kind:"denial"});return}if(D.some(j=>j.type==="tool_result")||!F.trim())return;n.user_turns++,n.user_chars+=F.length;let U=ii(F);U&&(o=U);let N=KI(F,l,c);l=F,N.kind==="correction"?n.corrections++:N.kind==="rework"?n.reworks++:N.kind==="repeat"?n.repeated_instructions++:N.kind==="acceptance"&&n.acceptances++,N.polarity!==0&&i.push(N),c=!1},"processLine");y.on("line",w=>{try{v(w)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await zI(e,n),n.effort_at_end=o;for(let m of r)m.synthetic||m.model==="<unknown>"||GI(s,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...s.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,h=[];return i.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*HI+m.polarity*m.magnitude;let y=Number(u.toFixed(3));h.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=h,n.momentum_final=h.length?h[h.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 eo,v_,LI,$I,FI,jI,UI,HI,or,k_=_(()=>{"use strict";Js();Zs();eo="mcp__maind__",v_="2026-10-01",LI=/(\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,$I=/(\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,FI=/(\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,jI="[Request interrupted by user",UI="The user doesn't want to proceed with this tool use",HI=.7,or={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};a(GI,"bumpModel");a(Qs,"asBlocks");a(BI,"textOf");a(WI,"isRepeat");a(KI,"classifyGenuine");a(VI,"emptyAnalysis");a(zI,"tallySubagentMaindCalls");a(Tl,"analyzeSession")});function Al(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 Rl(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 Il(e,t,n,r="unknown",i){let s={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(s.session_span=n?{...t,...n}:t),s}var x_=_(()=>{"use strict";a(Al,"parseIngestResponse");a(Rl,"describeSliceVerdict");a(Il,"ingestBody")});import{homedir as qI}from"node:os";import{join as YI}from"node:path";var JI,Nl=_(()=>{"use strict";JI=YI(qI(),".codex","sessions")});var S_=_(()=>{"use strict";Nl()});import{isAbsolute as Dl,relative as ZI,resolve as E_,sep as Pl}from"node:path";function T_(e){return e>no[1]?"above_272k":e>no[0]?"band_200k_272k":"standard"}function A_(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function to(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Ml(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=a(o=>{if(!Array.isArray(o))return[];let c=[];for(let l of o){if(!l||typeof l!="object")continue;let d=l,u=to(d.from);typeof d.object_id!="string"||!Cl.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:to(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let o of n.claims){if(!o||typeof o!="object")continue;let c=o,l=to(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:to(c.to)})}let s=[];if(Array.isArray(n.anchors))for(let o of n.anchors){if(!o||typeof o!="object")continue;let c=o;typeof c.object_id!="string"||!Cl.test(c.object_id)||typeof c.path_prefix=="string"&&s.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Cl.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:s}}function R_(e,t){if(!Dl(e))return null;let n=ZI(E_(t),E_(e));return!n||n==="."||n.startsWith("..")||Dl(n)?null:Pl==="/"?n:n.split(Pl).join("/")}function eN(e,t){return t===""||e===t||e.startsWith(t+"/")}function Ll(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function I_(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function $l(e,t){for(let n of I_(t))if(eN(e,n.path_prefix))return n.object_id;return null}function tN(e,t){for(let n of I_(t))if(Ll(e,n.path_prefix))return n.object_id;return null}function Ol(e,t){return e>=t.from&&(t.to===null||e<t.to)}function N_(e,t,n,r){let i=e.ts,s=r?.anchors??[],o=t.map(c=>$l(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Ol(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=>Ol(i,u));if(l.length)return{object_id:(l.find(p=>o.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,h)=>p.object_id.localeCompare(h.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>Ol(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(h=>Ll(h.path_prefix,u))).sort((h,m)=>m.path_prefix.length-h.path_prefix.length);for(let h of p){let m=tN(h.path_prefix,s);if(m)return{object_id:m,source:"claim"}}}}return o.length?{object_id:o[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function Fl(e,t,n){let r=t?.anchors??[],i=a(g=>{if(!n.repoRoot)return[];let y=[];for(let v of g.edited_paths){let w=R_(v,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),s=a(g=>{for(let y of g){let v=$l(y,r);if(v)return{object_id:v,rel:y}}return null},"firstAnchoredEdit"),o=new Map;for(let g of e){let y=o.get(g.stream)??[];y.push(g),o.set(g.stream,y)}let c=[...o.entries()].sort(([g],[y])=>g===an?-1:y===an?1:0),l=[],d=a(g=>{let y=null;for(let v of l){if(v.ts>g&&g>0)break;y=v.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let v=y.map((b,k)=>({t:b,i:k,rels:i(b)})).sort((b,k)=>b.t.ts-k.t.ts||b.i-k.i),w=null;for(let b of v){let k=s(b.rels);if(k){w=k;break}}!w&&g!==an&&v.length&&(w=d(v[0].t.ts));for(let b of v){let k=s(b.rels);k&&(w=k),g===an&&l.push({ts:b.t.ts,seg:w});let S=b.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let D=N_(S,b.rels,w,t),F=T_(S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens),H=A_(S.model),U=`${D.object_id??""}|${D.source}|${H}|${F}`,N=u.get(U);N||(N={object_id:D.object_id,attribution_source:D.source,model:H,context_tier:F,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},u.set(U,N)),N.input_tokens+=S.input_tokens,N.output_tokens+=S.output_tokens,N.cache_read_tokens+=S.cache_read_tokens,N.cache_creation_tokens+=S.cache_creation_tokens,N.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,N.turns+=1,S.ts>0&&((N.firstMs===0||S.ts<N.firstMs)&&(N.firstMs=S.ts),S.ts>N.lastMs&&(N.lastMs=S.ts))}}let p=n.nowMs??Date.now(),h=[];for(let g of u.values()){let{firstMs:y,lastMs:v,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(v>0?v:p).toISOString(),h.push(w)}let m={lease:0,binding:1,claim:2,path:3,none:4};return h.sort((g,y)=>m[g.attribution_source]-m[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),h}function jl(e,t){let n=new Map;for(let s of e){let o=new Set;for(let c of s.edited_paths){if(!Dl(c))continue;let l=t(nN(c));l&&o.add(l)}for(let c of o)n.set(c,(n.get(c)??0)+1)}let r=null,i=0;for(let[s,o]of n)(o>i||o===i&&r!==null&&s.length>r.length)&&(r=s,i=o);return r}function nN(e){let t=e.split(Pl).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var no,QI,Cl,C_=_(()=>{"use strict";Zs();no=[2e5,272e3];a(T_,"contextTierOf");a(A_,"normalizeModelId");QI=no[0],Cl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(to,"msOf");a(Ml,"parseCostContext");a(R_,"toRepoRelative");a(eN,"underPrefix");a(Ll,"prefixesOverlap");a(I_,"sortedAnchors");a($l,"anchorFor");a(tN,"bestAnchorOverlapping");a(Ol,"inWindow");a(N_,"assignTurn");a(Fl,"sliceSession");a(jl,"dominantCheckoutRoot");a(nN,"dirOf")});import{createReadStream as rN,existsSync as iN}from"node:fs";import{createInterface as sN}from"node:readline";function O_(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function cN(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
168
|
-
`)}function M_(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 lN(e){let t=e.message?.role;if(t==="assistant")return{holder:O_(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=O_(e.message?.content),r=cN(n);return r.includes(oN)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(aN))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Ul(e){let t=M_("");if(!e||!iN(e))return t;let n=null,r=0,i=0,s=null,o="human",c=[];return await new Promise(l=>{let d=rN(e,{encoding:"utf-8"}),u=sN({input:d}),p=a(h=>{let m=h.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let w=g.sessionId??g.session_id;typeof w=="string"&&w&&(t.session_id=w)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||s!==null&&y<s)return;let v=lN(g);if(v!==null){if(t.event_count++,v.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let w=y-s;o==="agent"?i+=w:w>=D_*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(w/1e3),c.length<P_&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(w/1e3)}))}s=y,o=v.holder}},"processLine");u.on("line",h=>{try{p(h)}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 oN,aN,D_,P_,L_=_(()=>{"use strict";oN="[Request interrupted by user",aN="The user doesn't want to proceed with this tool use",D_=60,P_=200;a(O_,"asBlocks");a(cN,"textOf");a(M_,"emptySpan");a(lN,"classify");a(Ul,"analyzeSpan")});import{createReadStream as dN,existsSync as uN}from"node:fs";import{createInterface as pN}from"node:readline";function mN(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function ro(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function hN(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(`
|
|
169
|
-
`)}return""}async function Hl(e,t={}){if(!e||!uN(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:kl(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:kl(),o=t.start??0;return await new Promise(c=>{let l=dN(e,{encoding:"utf-8",start:t.start??0}),d=pN({input:l});d.on("line",p=>{o+=Buffer.byteLength(p,"utf-8")+1;let h=p.trim();if(!h)return;let m;try{m=JSON.parse(h)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),v=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 w=fN[m.attachment.type];w&&(s[mN(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(v==="user"){let w=hN(m.message?.content),b=ii(w);b&&(i=b);let k={session_id:g,ts:y,text:w,effort_directive:b};n.push({kind:"user",...k});return}if(v==="assistant"){let w=m.message?.usage,b=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,k=typeof m.requestId=="string"&&m.requestId?m.requestId:null,S=b??k,R=S!==null&&r.has(S);S!==null&&!R&&r.add(S);let D={session_id:g,ts:y,model:m.message?.model??null,input_tokens:R?0:ro(w?.input_tokens),output_tokens:R?0:ro(w?.output_tokens),cache_read_input_tokens:R?0:ro(w?.cache_read_input_tokens),cache_creation_input_tokens:R?0:ro(w?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...s.ultracode?{ultracode:!0}:{},...s.planMode?{planMode:!0}:{},...s.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...D})}});let u=a(()=>({events:n,bytesRead:o,effortAtEnd:i,modesAtEnd:{...s},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var fN,$_=_(()=>{"use strict";Js();xl();fN={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}};a(mN,"modeFlagKey");a(ro,"num");a(hN,"extractUserText");a(Hl,"streamTranscript")});var F_=_(()=>{"use strict"});import{homedir as gN}from"node:os";import{join as yN}from"node:path";function Bl(e){return e.replace(/[/.]/g,"-")}var _N,Gl,j_=_(()=>{"use strict";_N=gN(),Gl=yN(_N,".claude","projects");a(Bl,"projectPathFromCwd")});var ar=_(()=>{"use strict";xl();m_();h_();k_();x_();Zs();Nl();S_();C_();L_();$_();Js();F_();j_()});import{parse as AN}from"jsonc-parser";function Wl(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 IN(e){if(e.raw===null)return null;if(e.kind==="toml"){let s=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!s)return null;let o=/^\s*command\s*=\s*"([^"]*)"/m.exec(s[1]),c=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(s[1]);return o?{command:o[1],args:c?[...c[1].matchAll(/"([^"]*)"/g)].map(l=>l[1]):[]}:null}let t=[],n=AN(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;return!i||typeof i.command!="string"?null:{command:i.command,args:Array.isArray(i.args)?i.args.filter(s=>typeof s=="string"):[]}}function cr(e,t){let n=`npm i -g ${oi}@${e}`;return t?`nvm use ${t} && ${n}`:n}function so(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(u=>u.bridgeVersion).filter(u=>u!==null)],r=e.latestVersion??n.sort(Wl).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(u=>u.bridgeVersion!==null);if(e.nodeTrees.length>0){let u=e.pathWinner?.node??null,p=e.nodeTrees.find(m=>m.node===u);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):p&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${p.node} tree (${p.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let m=e.nodeTrees.find(g=>g.node===e.nvmDefault);m&&m.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${m.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:cr(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(g=>Wl(g.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${m.node} carries bridge ${m.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:cr(r,m.node)})}let s=!1,o=new Map,c=a((u,p)=>{let h=o.get(u)??{version:e.installVersionOf(u),clients:[]};h.clients.push(p),o.set(u,h)},"noteInstall");for(let u of e.clientConfigs){let p=IN(u);if(p===null)continue;if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(g=>g.includes(oi))){t.push({check:"client-config",level:"warn",message:`${u.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${cr(r)}, then set "command": "maind-mcp-bridge" (no args) in ${u.path}`});continue}let m=/(^|[\\/])node(\.exe)?$/.test(p.command);if(m&&p.args.length>0){let g=p.args[0];if(!e.fileExists(g)){t.push({check:"client-config",level:"error",message:`${u.label} runs ${g}, which does not exist.`,fix:`re-run \`npx -y ${oi}@${r} install\` to rewrite the entry`});continue}c(g,u.label)}else if(p.command.includes("/")||p.command.includes("\\")){if(!e.fileExists(p.command)){t.push({check:"client-config",level:"error",message:`${u.label} points at ${p.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${u.path} (after ${cr(r)})`});continue}}else if(p.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${u.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:cr(r,e.nvmDefault)});continue}m||(p.command.includes("/")||p.command.includes("\\")?c(p.command,u.label):p.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,u.label)),t.push({check:"client-config",level:"ok",message:`${u.label}: ${[p.command,...p.args].join(" ")}`})}if(s||t.push({check:"client-config",level:"warn",message:"no MCP client config names a `maind` server.",fix:`npx -y ${oi} install`}),e.latestVersion!==null)for(let[u,p]of o){let h=p.clients.join(", ");if(p.version===null)t.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${u} is.`});else if(Wl(p.version,e.latestVersion)<0){let m=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(u)?.[1]??null;t.push({check:"version",level:"warn",message:`${h} run bridge ${p.version} (${u}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:m?cr(e.latestVersion,m):`npx -y ${oi}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${h} run bridge ${p.version} (published: ${e.latestVersion}).`})}for(let{dir:u,maind:p}of e.npxStaleDirs)t.push({check:"npx-cache",level:p?"error":"info",message:p?`a half-built better-sqlite3 was left in ${u} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${u} (another tool's npx entry, not maind's).`,fix:`rm -rf '${u.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!G_.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"}):RN.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&G_.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 u=en(e.claudeSettings,{fileExists:a(h=>e.fileExists(h),"fileExists")}),p=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let h of u){if(h.status==="missing")continue;if(h.status!=="ok"){t.push({check:"hooks",level:h.status==="broken"?"error":"warn",message:h.detail});continue}let m=h.command?/(\S+\/build\/index\.js)/.exec(h.command)?.[1]??null:null,g=m?e.installVersionOf(m):null;g!==null&&p!==null&&g!==p&&t.push({check:"hooks",level:"warn",message:`${h.event}/${h.subcommand} runs bridge ${g}, the MCP server runs ${p} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${h.subcommand}`})}t.some(h=>h.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}return t}function B_(e){let t=e.filter(i=>i.level==="error"&&Kl.includes(i.check)).sort((i,s)=>Kl.indexOf(i.check)-Kl.indexOf(s.check)),n=t[0];if(n===void 0)return null;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 W_(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((o,c)=>n[o.level]-n[c.level]).flatMap(o=>[`${t[o.level]} [${o.check}] ${o.message}`,...o.fix?[` fix: ${o.fix}`]:[]]),i=e.filter(o=>o.level==="error").length,s=e.filter(o=>o.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
170
|
-
`)+`
|
|
171
|
-
`}var oi,RN,G_,Kl,Vl=_(()=>{"use strict";Yn();oi="@maind-dev/mcp-bridge",RN=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,G_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Wl,"compareVersions");a(IN,"maindEntry");a(cr,"installFix");a(so,"diagnose");Kl=["connection","client-config","npx-cache","hooks"];a(B_,"sessionStartLine");a(W_,"renderFindings")});var q_={};ne(q_,{realProbe:()=>ao,resolveNvmAlias:()=>z_,runDoctor:()=>UN});import{execFileSync as NN}from"node:child_process";import{existsSync as Yl,readFileSync as CN,readdirSync as zl,realpathSync as ON}from"node:fs";import{homedir as ai,platform as oo}from"node:os";import{delimiter as DN,dirname as K_,join as le}from"node:path";function cn(e){try{return Yl(e)?CN(e,"utf8"):null}catch{return null}}function PN(){try{let e=NN(oo()==="win32"?"npm.cmd":"npm",["view",V_,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function ql(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:le(ai(),".nvm")}function MN(){let e=le(ql(),"versions","node"),t=[];try{t=zl(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=cn(le(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 z_(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(d[p]!==u[p])return(d[p]??0)-(u[p]??0);return 0});if(r==="node"||r==="stable")return i.at(-1)??null;let s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return s;let o=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(o)).at(-1)??null}function LN(e){let t=cn(le(ql(),"alias","default"));return t===null?null:z_(t,e.map(n=>n.node),n=>{let r=cn(le(ql(),"alias",n));return r===null?null:r})}function $N(){let e=oo()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(DN))if(t)for(let n of e){let r=le(t,n);if(Yl(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function FN(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:oo()==="win32"?le(process.env.LOCALAPPDATA??le(ai(),"AppData","Local"),"npm-cache"):le(ai(),".npm"),t=le(e,"_npx"),n=[],r=[];try{r=zl(t)}catch{return[]}for(let i of r)try{let s=zl(le(t,i,"node_modules"));s.some(o=>o.startsWith(".better-sqlite3-"))&&n.push({dir:le(t,i),maind:s.includes("@maind-dev")})}catch{}return n}function jN(e){let t;try{t=K_(ON(e))}catch{return null}for(let n=0;n<6;n++){let r=cn(le(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===V_)return s.version??null}catch{}let i=K_(t);if(i===t)break;t=i}return null}function ao(e=process.cwd(),t={}){let n=MN(),r=cn(le(Ee(),"device-id")),i=xs({projectRoot:e,homeDir:ai(),platform:oo(),env:process.env}),s=null;try{s=K()}catch{s=null}let o=(process.env.MAIND_API_KEY??"").trim();return{runningVersion:G,latestVersion:t.offline===!0?null:PN(),nodeTrees:n,nvmDefault:LN(n),pathWinner:$N(),clientConfigs:Vr(i).map(c=>({label:c.label,path:c.path,kind:c.kind,raw:cn(c.path)})),npxStaleDirs:FN(),connection:qh(),claudeSettings:cn(le(ai(),".claude","settings.json")),fileExists:a(c=>Yl(c),"fileExists"),installVersionOf:jN,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:o.length>0?o:null}}async function UN(e){let t=so(ao());return e.includes("--json")?process.stdout.write(JSON.stringify({version:G,findings:t},null,2)+`
|
|
172
|
-
`):process.stdout.write(W_(t)),t.some(n=>n.level==="error")?1:0}var V_,Jl=_(()=>{"use strict";Gc();oe();qr();Xe();Vl();V_="@maind-dev/mcp-bridge";a(cn,"readOrNull");a(PN,"latestVersion");a(ql,"nvmDir");a(MN,"nodeTrees");a(z_,"resolveNvmAlias");a(LN,"nvmDefault");a($N,"pathWinner");a(FN,"npxStaleDirs");a(jN,"installVersionOf");a(ao,"realProbe");a(UN,"runDoctor")});async function J_(e){return et("get_session_briefing",{tools:["claude-code"]},e)}async function et(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??ci,i=new AbortController,s=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let o={"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&&(o["x-maind-device-id"]=n.deviceId),n.projectKey&&(o["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:o,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:HN,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 Y_(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let v=null;try{let w=JSON.parse(d);typeof w.result?.instructions=="string"&&(v=w.result.instructions)}catch{v=null}n.onInitialize(v)}if(!c.ok||!l)return null;let u={...o,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(v=>v.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 Y_(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(v=>v.type==="text"&&typeof v.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(s)}}async function Y_(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",o=a(()=>{if(i.length===0)return;let c=i.join(`
|
|
173
|
-
`).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
174
|
-
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){o();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return o(),s}var ci,HN,lr=_(()=>{"use strict";ci="https://mcp.maind.dev/mcp",HN="2025-06-18";a(J_,"fetchSessionBriefing");a(et,"fetchToolText");a(Y_,"readSseMessage")});function GN(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":Z()}}async function X_(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:GN(t),body:JSON.stringify({metrics:n})});if(!r.ok){let s=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:s.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var co,Xl=_(()=>{"use strict";oe();Bn();co=process.env.MAIND_ENDPOINT??Gn("mcp-client-metrics-ingest");a(GN,"ingestHeaders");a(X_,"postMetrics")});function Z_(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function eb(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,s=Array.isArray(i.active_claims)?i.active_claims:[],o=[];for(let c of s){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||o.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:o,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function dr(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 li(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function tb(e,t,n){let r=n.maxAgeMs??Q_,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,o=eb(e,s),c=[];for(let l of o)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)Z_(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 ${li(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${li(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Z_(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${li(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${li(s)} ago, advisory \u2014 never a lock):
|
|
175
|
-
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
176
|
-
`)+`
|
|
177
|
-
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 nb(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 rb(e,t,n,r=Q_,i=null){if(!e)return null;let s=n-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let o=s/1e3,c=eb(e,o),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",h=u>0?`, ${u} presence-only`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${h}) as of ${li(o)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
178
|
-
${m}`:m}var Q_,Zl=_(()=>{"use strict";a(Z_,"prefixConflict");Q_=10*6e4;a(eb,"parsePeers");a(dr,"selectOwnSnapshot");a(li,"ageDisplay");a(tb,"adviseOnPath");a(nb,"claimedIdentity");a(rb,"sessionStartSummary")});async function W(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=a(s=>{n||(n=!0,clearTimeout(i),t(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>e.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(e).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function ur(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 we=_(()=>{"use strict";a(W,"readHookInput");a(ur,"transcriptPathOf");a(je,"toolFilePathOf")});function sb(e){let t=[];for(let n of ob(e)){let r=YN(n);r&&!t.includes(r)&&t.push(r)}return t}function ob(e){let t=[],n="",r=null,i=0,s=[],o=a(()=>{n.trim()&&t.push(n),n=""},"flush");for(;i<e.length;){let c=e[i];if(r){if(c==="\\"&&r==='"'){n+=c+(e[i+1]??""),i+=2;continue}c===r&&(r=null),n+=c,i+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,i+=1;continue}if(c==="<"&&e[i+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(i));if(l){s.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
|
|
179
|
-
`){if(s.length>0){let d=e.slice(i+1).split(`
|
|
180
|
-
`),u=0;for(;s.length>0&&u<d.length;)d[u].trim()===s[0]&&s.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,h)=>p+h.length+1,0),s=[],o();continue}o(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){o(),i+=2;continue}if(c===";"||c==="|"){o(),i+=1;continue}n+=c,i+=1}return o(),t}function YN(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let o=t[n];if(o===void 0)return null;if(WN.test(o)){n+=1;continue}if(VN.has(o)){n+=1;continue}if(zN.has(o))return null;let c=o.split("/").pop()??o;if(KN.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!ib.test(i))return null;if(!BN.test(i))return Ql;if(!qN.has(i))return i;let s=t[n+1];return s&&ib.test(s)?`${i} ${s}`:i}function ed(e){let t=sb(e).filter(n=>n!==Ql&&!ab.has(n));return t.length>0?t[t.length-1]:null}var ib,BN,Ql,WN,KN,VN,zN,qN,ab,td=_(()=>{"use strict";ib=/^[A-Za-z][A-Za-z0-9._-]*$/,BN=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,Ql="?",WN=/^[A-Za-z_][A-Za-z0-9_]*=/,KN=new Set(["sudo","env","time","nohup","nice","command","exec"]),VN=new Set(["do","then","else","elif","if","while","until","!","{","("]),zN=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),qN=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"]);a(sb,"shellPrograms");a(ob,"commandSegments");a(YN,"programOf");ab=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"]);a(ed,"primaryVerb")});function cb(e){let t=e.length>nd?e.slice(-nd):e;return JN.some(n=>n.test(t))}function rd(e){return e.includes("maind")?XN.some(t=>e.includes(t)):!1}function lb(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function db(e,t){if(!lb(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?ed(n):null}function id(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=db(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&cb(e.output)?"fail":"ok",verb:t}}var nd,JN,XN,ub=_(()=>{"use strict";td();nd=8192,JN=[/\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];a(cb,"outputShowsFailure");XN=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];a(rd,"isConsultationTool");a(lb,"isCountedTool");a(db,"verbOfCall");a(id,"observe")});function pb(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 sd(e,t=-1/0){let n=e.filter(s=>s.k==="fail"&&s.t>t).slice().sort((s,o)=>s.t-o.t),r=[],i=[];for(let s of n)i.length>0&&s.t-i[i.length-1].t>6e5&&(r.push(pb(i)),i=[]),i.push(s);return i.length>0&&r.push(pb(i)),r}function od(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 fb(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function pr(e,t,n){let r=fb(e,t),i=sd(e,r),s=i.length>0?i[i.length-1]:null,o=s!==null&&n-s.end<=6e5?s:null;if(o===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=od(e,o.lastVerb,o.end)!==null,l=e.some(d=>d.k==="nudge"&&d.t>=o.start);return{open:o.failures.length>=4&&!c,chain:o,nudged:l,resolved:c}}function ad(e){return e.open&&!e.nudged}function cd(e,t){let n=-1/0;for(let s of e)s.k==="prompt"&&s.t>n&&(n=s.t);let r=Math.max(t,n),i=sd(e,r);for(let s=i.length-1;s>=0;s--){let o=i[s];if(o.failures.length<5||o.end-o.start<3e5)continue;let c=od(e,o.lastVerb,o.end);if(c!==null)return{...o,resolvedAt:c}}return null}function di(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 ld=_(()=>{"use strict";a(pb,"chainOf");a(sd,"failureChains");a(od,"succeededAfter");a(fb,"resetPoint");a(pr,"difficultyStatus");a(ad,"shouldNudge");a(cd,"captureCandidate");a(di,"verbSummary")});function QN(e){let t=e.id;if(typeof t!="string")return null;let n=e.version,r=typeof n=="number"&&Number.isInteger(n)&&n>=1?n:1,i=e.severity,s=typeof i=="string"&&ZN.has(i)?i:"recommended",o=e.enabled!==!1;return{id:t,version:r,severity:s,enabled:o}}function uo(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return pi;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let s=QN(i);s!==null&&(s.id===ui?n=s:s.id===lo&&(r=s))}return{difficulty:n,capture:r}}function fr(e){return e!==null&&e.enabled}function dd(e){return fr(e)&&e.severity==="required"}var ui,lo,pi,ZN,ud=_(()=>{"use strict";ui="conv_consult_on_difficulty",lo="conv_learning_capture_offer",pi={difficulty:null,capture:null},ZN=new Set(["required","recommended","info"]);a(QN,"ruleOf");a(uo,"extractTriggerPolicy");a(fr,"isActive");a(dd,"isDenyCapable")});function eC(e){return Math.max(1,Math.round(e/6e4))}function fi(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${di(e)}) and no maind consultation since they started (${ui}). 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 pd(e){return`difficulty episode (${e.failures.length} failed attempts: ${di(e)}) without a maind consultation since it started (${ui}, required)`}function fd(e,t="guard"){let n=eC(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${lo}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${di(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 mb=_(()=>{"use strict";ld();ud();a(eC,"minutes");a(fi,"nudgeText");a(pd,"difficultyDenyHead");a(fd,"captureText")});var mr=_(()=>{"use strict";td();ub();ld();ud();mb()});import{mkdir as tC,readFile as nC,writeFile as rC,rename as iC}from"node:fs/promises";import{existsSync as yb}from"node:fs";import{homedir as sC}from"node:os";import{join as _b}from"node:path";function gb(){return{config:null,sessions:{},pending_metrics:[]}}async function q(){if(!yb(po))return gb();try{let e=await nC(po,"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)}
|
|
181
|
-
`),gb()}}async function Ue(e){yb(ln)||await tC(ln,{recursive:!0,mode:448});let t=`${po}.tmp`;await rC(t,JSON.stringify(e,null,2),{mode:384}),await iC(t,po)}function md(e){return e.thresholds??e.config?.thresholds??oC}var ln,po,oC,tt=_(()=>{"use strict";ln=_b(sC(),".maind"),po=_b(ln,"state.json"),oC={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};a(gb,"emptyState");a(q,"loadState");a(Ue,"saveState");a(md,"resolveThresholds")});import{existsSync as wb}from"node:fs";import{mkdir as aC,readFile as cC,readdir as lC,rename as dC,stat as uC,unlink as pC,writeFile as fC}from"node:fs/promises";import{join as mi}from"node:path";function vb(e){return mi(hd,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function rt(e){try{let t=vb(e);if(!wb(t))return{};let n=JSON.parse(await cC(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function me(e,t){await aC(hd,{recursive:!0,mode:448});let n=vb(e),r=`${n}.tmp`;await fC(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await dC(r,n)}async function kb(e=7*24*60*60*1e3,t=Date.now()){await bb(hd,".json",e,t),await bb(gd,".jsonl",e,t)}async function bb(e,t,n,r){try{if(!wb(e))return;for(let i of await lC(e)){if(!i.endsWith(t))continue;let s=mi(e,i);try{let o=await uC(s);r-o.mtimeMs>n&&await pC(s)}catch{}}}catch{}}var nt,hd,gd,xt=_(()=>{"use strict";tt();nt=mi(ln,"guard"),hd=mi(nt,"sessions"),gd=mi(nt,"triggers");a(vb,"sessionFile");a(rt,"loadGuardSession");a(me,"saveGuardSession");a(kb,"sweepOldGuardSessions");a(bb,"sweepDir")});import{existsSync as mC}from"node:fs";import{appendFile as hC,mkdir as gC,open as yC}from"node:fs/promises";import{join as _C}from"node:path";async function V(e){try{await gC(nt,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
182
|
-
`;await hC(dn,t,{mode:384})}catch{}}async function xb(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(!mC(dn))return t;let n=await yC(dn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
|
|
183
|
-
`);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 dn,it=_(()=>{"use strict";xt();dn=_C(nt,"events.jsonl");a(V,"appendGuardEvent");a(xb,"readGuardEventCounts")});function un(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function st(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function fo(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function Sb(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}var pn=_(()=>{"use strict";a(un,"denyPayload");a(st,"advisoryPayload");a(fo,"postAdvisoryPayload");a(Sb,"postFailureAdvisoryPayload")});import{realpathSync as bC}from"node:fs";import{basename as Eb,dirname as Tb,join as wC}from"node:path";function fn(e){let t=Tb(e),n=[Eb(e)];for(;;)try{let r=bC(t);return wC(r,...n.reverse())}catch{let r=Tb(t);if(r===t)return e;n.push(Eb(t)),t=r}}var mo=_(()=>{"use strict";a(fn,"realpathOfUnwritten")});import{existsSync as vC,realpathSync as kC,statSync as xC}from"node:fs";import{dirname as Ab,isAbsolute as SC,join as EC}from"node:path";function RC(e,t){let n=e.filter(i=>Rb.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
|
|
184
|
-
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
185
|
-
${i.detail}${s}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
186
|
-
|
|
187
|
-
`+r.join(`
|
|
188
|
-
|
|
189
|
-
`)+`
|
|
190
|
-
|
|
191
|
-
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 IC(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function NC(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},s=i[t]??{};s[n]=new Date(r).toISOString(),i[t]=s,e.repo_health_seen=i}function yd(e){let t=Ab(e);for(;;){try{if(xC(t).isDirectory())return t}catch{}let n=Ab(t);if(n===t)return t;t=n}}async function CC(e,t,n){let r=await n.load();if(IC(r,e,t))return null;NC(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let s=i.filter(c=>Rb.includes(c.id)).length,o=await n.load();return o.pending_metrics.push({session_id:e,metric_key:TC,metric_value:1},{session_id:e,metric_key:AC,metric_value:s}),await n.save(o),RC(i,t)}async function Ib(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=je(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=SC(r)?r:EC(i,r),o=vC(s)?kC(s):fn(s),c=Je(yd(o)),l=await CC(n,c,{load:q,save:Ue,check:a(async d=>(await Cr(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(st(l)),0}catch{return 0}}var Rb,TC,AC,_d=_(()=>{"use strict";qt();Yt();pn();we();mo();tt();Rb=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],TC="repo_health_hook_runs",AC="repo_health_hook_findings";a(RC,"formatRepoHealth");a(IC,"alreadySeen");a(NC,"markSeen");a(yd,"nearestExistingDir");a(CC,"repoHealthForEdit");a(Ib,"runOnRepoHealth")});import{existsSync as OC,readFileSync as DC,realpathSync as PC}from"node:fs";import{isAbsolute as Cb,join as Ob,posix as MC,relative as LC,sep as $C}from"node:path";function Nb(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function GC(e,t){return{contracts:t.filter(r=>Nb(r.spec)===e||Nb(r.impl)===e).map(r=>r.id),theme:UC.test(e),acl:HC.test(e)}}function BC(e){return e.contracts.length===0&&!e.theme&&!e.acl}function WC(e,t,n,r,i=Date.now()){let s=e.write_health_seen??{},o=s[t]??{},c=new Set(o[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);o[n]={at:new Date(i).toISOString(),keys:[...c]},s[t]=o,e.write_health_seen=s}return l}function KC(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:
|
|
192
|
-
|
|
193
|
-
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
194
|
-
`)+`
|
|
195
|
-
|
|
196
|
-
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 VC(e,t){let n=LC(e,t);return!n||n.startsWith("..")||Cb(n)?null:n.split($C).join(MC.sep)}function zC(e){try{let t=DC(Ob(e,Xi),"utf8"),{manifest:n}=ts(t);return n?.contracts??[]}catch{return[]}}async function Db(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=je(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=Cb(r)?r:Ob(i,r),o=OC(s)?PC(s):fn(s),c=Je(yd(o)),l=VC(c,o);if(l===null)return 0;let d=GC(l,zC(c));if(BC(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await Wt(c,{contracts:d.contracts});for(let y of g.findings)y.status==="open"&&u.push({key:`spec:${y.id}`,line:`spec-drift (${y.contract}): ${y.detail}`})}catch{}if(d.theme)try{let g=Vt(c);for(let y of g.findings)y.status==="open"&&u.push({key:`theme:${y.file}:${y.klass}`,line:`theme-class-drift: \`${y.klass}\` in ${y.file} \u2014 no token \`--color-${y.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=Kt(c);for(let y of g.findings)y.status==="open"&&u.push({key:`acl:${y.id}`,line:`table-acl-lint: \`${y.table}\` (created in ${y.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await q(),h=WC(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:FC,metric_value:1},{session_id:n,metric_key:jC,metric_value:h.length}),await Ue(p);let m=KC(h,l);return m!==null&&process.stdout.write(fo(m)),0}catch{return 0}}var FC,jC,UC,HC,Pb=_(()=>{"use strict";qt();Yt();pn();we();_d();mo();tt();FC="write_health_hook_runs",jC="write_health_hook_findings",UC=/\.(tsx?|jsx?|css)$/,HC=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;a(Nb,"declPath");a(GC,"routesForPath");a(BC,"routesAreEmpty");a(WC,"takeUnreported");a(KC,"formatWriteHealth");a(VC,"repoRelative");a(zC,"readContracts");a(Db,"runOnWriteHealth")});var Vb={};ne(Vb,{agentHostPidCandidates:()=>ot,closeTrackedSession:()=>Hb,effectiveConfig:()=>mn,grandparentPid:()=>Bb,isCaptureTool:()=>bd,recordGuardSignals:()=>Ub,runFlush:()=>lO,runHookStatus:()=>dO,runOnFileEdit:()=>oO,runOnFileWrite:()=>sO,runOnRepoHealth:()=>Ib,runOnSessionStart:()=>eO,runOnToolUse:()=>rO,runOnWriteHealth:()=>Db,runSessionEndMetrics:()=>vd,runSyncConfig:()=>pO,writeIdentitySideChannel:()=>wd});import{execFileSync as Lb}from"node:child_process";import{existsSync as yo,readFileSync as $b,realpathSync as qC}from"node:fs";import{writeFile as YC}from"node:fs/promises";import{homedir as Fb}from"node:os";import{isAbsolute as go,join as hi,relative as jb}from"node:path";function Ub(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=rd(n),s=n.includes("review_changes")||n.includes("review_verdict"),o=bd(n);if(!i&&!s&&!o)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),s&&(l.reviewed_at=d),o&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function bd(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 Hb(e,t,n=Date.now()){QC(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 QC(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>ho&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));t-i>ho&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));t-i>ho&&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>ho&&delete e.sessions[n]}}function mn(e){if(e.config)return e.config;let t=K();return t===null?null:{api_key:t,endpoint:co}}function Gb(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function eO(){try{let r=B_(so(ao(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
|
|
197
|
-
`)}catch{}let e=await q();if(mn(e)===null)return 0;let t=await W(),n=Kb(t);if(n===null)return 0;Gb(e,n),await Ue(e);try{wd(t,n)}catch{}try{let r=z();if(r!==null){let i=rr(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),o=dr(i,{hostPids:ot(),cwd:s}),c=nb(o?.snap??null,ri(ur(t)||null,n)),l=rb(o?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
|
|
198
|
-
`)}}catch{}try{let r=en(tO());if(qc(r)&&Rs(r)){let i=r.filter(s=>s.remedy==="run-install").map(s=>s.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
199
|
-
`)}}catch{}return 0}function tO(){try{let e=hi(Fb(),".claude","settings.json");return yo(e)?$b(e,"utf8"):null}catch{return null}}function wd(e,t,n,r=ir()){let i=n??ot();if(i.length===0)return;let s=ri(ur(e)||null,t);if(s===null)return;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=ur(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)d_({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:o,transcriptPath:c,model:l})}function Bb(){try{if(process.platform==="win32")return null;let e=Lb("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 ot(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Bb();return n!==null&&n>1&&n!==t&&e.push(n),e}async function rO(){let e=await q();if(mn(e)===null)return 0;let t=await W(),n=Kb(t)??"unknown",r=Gb(e,n);r.tool_call_count+=1;try{let o=ot().filter(c=>u_(ir(),c,nO));n!=="unknown"&&o.length>0&&wd(t,n,o)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Ub(e,n,i),bd(i)&&n!=="unknown"&&await V({event:"capture_taken",session_id:n,detail:i});let s=t.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let o=await Sl(r.transcript_path);o&&(r.token_count=o.total_tokens,await cO(e,r))}return await Ue(e),0}function iO(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
200
|
-
`);return`${t.prefix}${e.number} is already taken:
|
|
201
|
-
${n}
|
|
202
|
-
|
|
203
|
-
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
204
|
-
|
|
205
|
-
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 sO(){try{let e=await W();if((e.tool_name??"")!=="Write")return 0;let t=je(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=go(t)?t:hi(n,t);if(yo(r))return 0;let i=Je(n),s=jb(i,fn(r));if(s.length===0||s.startsWith("..")||go(s))return 0;let o=await Bt(i,s);return!o.taken||o.namespace===null||process.stdout.write(un(iO(o,o.namespace))),0}catch{return 0}}async function oO(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")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=go(n)?n:hi(r,n),s=z();if(s===null)return 0;let o=rr(s);if(o.length===0)return 0;let c=dr(o,{hostPids:ot(),cwd:r});if(c===null)return 0;let l=Je(r),d=yo(i)?qC(i):fn(i),u=jb(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||go(u))return 0;let p=tb(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?aO(r):null,nowMs:Date.now()});return p===null||process.stdout.write(st(p)),0}catch{return 0}}function aO(e){try{let n=Lb("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 cO(e,t){let n=md(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,s="ok";if(i>=n.handoff_at_pct/100?s="handoff_recommended":i>=n.warn_at_pct/100&&(s="warn"),t.last_advisory_status===s||(t.last_advisory_status=s,s==="ok"))return;let o=Math.round(i*100),c={session_id:t.session_id,status:s,tokens:r,ratio:Number(i.toFixed(3)),pct:o,thresholds:n,suggested_next:s==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await YC(hi(ln,`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)}
|
|
206
|
-
`)}s==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${o}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
207
|
-
`):process.stderr.write(`[maind] \u26D4 Token usage at ~${o}% (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.
|
|
208
|
-
`)}async function vd(e){try{let t=await q(),n=mn(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Hb(t,r),await Ue(t)),await Wb(n,XC)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
209
|
-
`)}}async function lO(){let e=await q(),t=mn(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 Wb(t,ZC);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
210
|
-
`),n.ok?0:1}async function Wb(e,t){let n=await q();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=X_(e.endpoint,e.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),o=await Promise.race([i,s]);if(o.ok){let c=await q();return c.pending_metrics=c.pending_metrics.slice(r.length),await Ue(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:o.error}}async function dO(){let e=await q(),t=mn(e),n=uO(),r=qc(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:md(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})),...Rs(n.findings)?{remedy:Mb}:{}}},null,2)+`
|
|
211
|
-
`),r){process.stderr.write(`
|
|
212
|
-
[maind] Claude Code hook wiring is incomplete:
|
|
213
|
-
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
214
|
-
`);Rs(n.findings)&&process.stderr.write(` ${Mb}
|
|
215
|
-
`)}return 0}function uO(){let e=hi(Fb(),".claude","settings.json"),t=null;try{yo(e)&&(t=$b(e,"utf8"))}catch{}return{settingsPath:e,findings:en(t)}}async function pO(){let e=await q(),t=mn(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??JC,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(o){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${o instanceof Error?o.message:String(o)}
|
|
216
|
-
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
217
|
-
`);let o=await r.text().catch(()=>"");return o&&process.stderr.write(o.slice(0,500)+`
|
|
218
|
-
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
219
|
-
`),1}let s=i;return typeof s.warn_at_pct!="number"||typeof s.handoff_at_pct!="number"||typeof s.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
220
|
-
`),1):(e.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await Ue(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
221
|
-
`),0)}function Kb(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var JC,XC,ZC,ho,nO,Mb,kd=_(()=>{"use strict";ar();mr();qt();Yt();it();oe();Yn();zs();Pe();Xl();Zl();Ys();we();pn();mo();tt();Bn();Vl();Jl();_d();Pb();JC=process.env.MAIND_THRESHOLDS_ENDPOINT??Gn("get-context-thresholds"),XC=1500,ZC=1e4,ho=7*24*60*60*1e3;a(Ub,"recordGuardSignals");a(bd,"isCaptureTool");a(Hb,"closeTrackedSession");a(QC,"gcState");a(mn,"effectiveConfig");a(Gb,"getOrCreateSession");a(eO,"runOnSessionStart");a(tO,"readSettingsRaw");a(wd,"writeIdentitySideChannel");nO=6e4;a(Bb,"grandparentPid");a(ot,"agentHostPidCandidates");a(rO,"runOnToolUse");a(iO,"denyReason");a(sO,"runOnFileWrite");a(oO,"runOnFileEdit");a(aO,"currentGitBranch");a(cO,"maybeEmitAdvisory");a(vd,"runSessionEndMetrics");a(lO,"runFlush");a(Wb,"flushPending");a(dO,"runHookStatus");Mb="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";a(uO,"readHookWiring");a(pO,"runSyncConfig");a(Kb,"sessionIdOf")});function zb(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var qb=_(()=>{"use strict";a(zb,"resolveConnection")});function Jb(e,t,n,r=Date.now()){let i=t===null?null:Ml(t),s=Fl(e,i,{repoRoot:n,nowMs:r});return s.length===0?null:{slices:s,context_ok:i!==null}}var Yb,xd=_(()=>{"use strict";ar();Yb=2e3;a(Jb,"buildCostPayload")});function Zb(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!Xb.test(n))return null;let r=n.toLowerCase();return t!==null&&Xb.test(t)&&r!==t.toLowerCase()?null:r}var Xb,Qb=_(()=>{"use strict";Xb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Zb,"snapshotSessionId")});async function ew(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await si(e.transcriptPath),i=e.resolveRoot?jl(r,e.resolveRoot):null,s=i&&e.projectKeyOf?e.projectKeyOf(i):null,o=i!==null&&s!==null&&s!==e.projectKey;o&&n.catch(()=>{});let[c,l,d]=await Promise.all([Tl(e.transcriptPath,{turns:r}),Ul(e.transcriptPath),o?e.fetchContext(s):n]),u=i??e.repoRoot;if(e.sessionId&&(c.session_id=e.sessionId,l.session_id=e.sessionId),c.maind_connected=e.connection(c.maind_connected==="connected",t()),!c.session_id)return{posted:!1,contextOk:d!==null,sentSlices:!1};let p=Jb(r,d,u,t()),h=Il(c,l,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",p);return await e.post(h,p!==null),{posted:!0,contextOk:p?.context_ok??d!==null,sentSlices:p!==null}}var tw=_(()=>{"use strict";ar();xd();a(ew,"ingestSessionEnd")});var iw={};ne(iw,{runOnSessionEnd:()=>vO});import{execFileSync as Sd}from"node:child_process";function mO(e,t){try{let n=z(),r=n!==null&&!_l(process.env,Fe()),i=null;if(n!==null){let s=dr(rr(n),{hostPids:ot(),cwd:process.cwd()});if(s){let o=Date.parse(s.snap.written_at);i=Number.isFinite(o)?Math.max(0,t-o):null}}return zb({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function hO(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let r=z();if(r!==null){let i=dr(rr(r),{hostPids:ot(),cwd:process.cwd()}),s=Zb(i?.snap,e);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function gO(){try{let e=Sd("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function yO(e){let t=nw.get(e);if(t!==void 0)return t;let n=null;try{let r=Sd("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return nw.set(e,n),n}function _O(e){let t=rw.get(e);if(t!==void 0)return t;let n=null;try{let r=Sd("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=ws(r))}catch{n=null}return rw.set(e,n),n}async function bO(e,t,n,r){if(n===null)return null;try{return await et("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:G,timeoutMs:Yb})}catch{return null}}async function wO(e,t,n,r,i){let s=fetch(fO,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":G},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=Rl(Al(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
|
|
222
|
-
`)}).catch(()=>{}),o=new Promise(c=>setTimeout(c,r));await Promise.race([s,o])}async function vO(){try{for(let i of ot())p_(ir(),i)}catch{}let e=K();if(!e)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=ur(t);if(r)try{let i=Z(),s=hO(ri(r,n)),o=z();await ew({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:o,coordSessionId:s,repoRoot:gO(),resolveRoot:yO,projectKeyOf:_O,fetchContext:a(c=>bO(e,i,c,s),"fetchContext"),post:a((c,l)=>wO(e,i,c,1500,l),"post"),connection:mO})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
223
|
-
`)}return await vd(n),0}var fO,nw,rw,sw=_(()=>{"use strict";ar();Jn();oe();lr();Xl();Zl();we();kd();bl();zs();Pe();Ys();Xe();qb();xd();Qb();tw();fO=co;a(mO,"connectionVerdict");a(hO,"presenceSessionId");a(gO,"sessionRepoRoot");nw=new Map;a(yO,"gitRootOf");rw=new Map;a(_O,"projectKeyOfRoot");a(bO,"fetchCostContext");a(wO,"postWithTimeout");a(vO,"runOnSessionEnd")});function ow(e){return e==="on"?!0:e==="off"?!1:null}function de(e=process.env,t=Fe()){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:ow(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:ow(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function hn(e,t=Qe()){let n={};try{let i=await ce(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await ee(t,JSON.stringify(r,null,2)+`
|
|
224
|
-
`,384)}var at=_(()=>{"use strict";Jn();$e();a(ow,"envSwitch");a(de,"resolveGuardConfig");a(hn,"writeGuardConfig")});function kO(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 aw(e,t,n=process.stdout){let r=kO(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
225
|
-
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of As)s.push(await Zc(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
226
|
-
`);let o=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
227
|
-
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
228
|
-
`),0):(await hn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
229
|
-
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
230
|
-
flip: maind-mcp-bridge guard mode <warn|block>
|
|
231
|
-
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
232
|
-
check: maind-mcp-bridge guard status
|
|
233
|
-
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
234
|
-
`),o&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
235
|
-
`),c?1:0)}var cw=_(()=>{"use strict";Yn();Qc();at();a(kO,"parseGuardInstallFlags");a(aw,"runGuardInstall")});import{existsSync as lw}from"node:fs";import{appendFile as xO,mkdir as SO,readFile as EO}from"node:fs/promises";import{join as TO}from"node:path";function Ed(e,t=_o){return TO(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function hr(e,t=_o){return lw(Ed(e,t))}async function St(e,t,n=_o){try{await SO(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await xO(Ed(e,n),r+`
|
|
236
|
-
`,{mode:384})}catch{}}async function gn(e,t=_o){try{let n=Ed(e,t);if(!lw(n))return[];let r=[];for(let i of(await EO(n,"utf8")).split(`
|
|
237
|
-
`))if(i.trim())try{let s=JSON.parse(i),o=s.t,c=s.k,l=s.v;if(typeof o!="number"||!Number.isFinite(o)||typeof c!="string"||!AO.has(c))continue;r.push(typeof l=="string"?{t:o,k:c,v:l}:{t:o,k:c})}catch{}return r}catch{return[]}}var _o,AO,gi=_(()=>{"use strict";xt();_o=gd,AO=new Set(["fail","ok","nudge","skip","prompt"]);a(Ed,"triggerLogPath");a(hr,"hasTriggerLog");a(St,"appendTriggerEvent");a(gn,"loadTriggerEvents")});import{existsSync as RO}from"node:fs";import{mkdir as IO,readFile as NO,rename as CO,writeFile as OO}from"node:fs/promises";import{dirname as DO,join as PO}from"node:path";function Td(e=process.env){let t=K();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??ci,keyFp:Hn(t)}}async function Ad(e,t=Date.now(),n=bo){try{if(!RO(n))return null;let r=JSON.parse(await NO(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let i=Date.parse(r.fetched_at);if(Number.isNaN(i))return null;let s=r.policy;return{policy:uo([s?.difficulty,s?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<MO}}catch{return null}}async function $O(e,t,n,r){try{await IO(DO(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},s=`${r}.tmp`;await OO(s,JSON.stringify(i,null,2),{mode:384}),await CO(s,r)}catch{}}async function FO(){let e=K();if(e===null)return null;let t=null;try{t=z()}catch{t=null}let n=await et("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:jO(),projectKey:t,bridgeVersion:G,timeoutMs:LO});if(n===null)return null;try{return uo(JSON.parse(n))}catch{return null}}async function gr(e,t={}){let n=t.nowMs??Date.now(),r=t.file??bo,i=t.identity===void 0?Td():t.identity;if(i===null)return pi;let s=await Ad(i,n,r);if(s?.fresh)return s.policy;if(e){let o=await(t.fetcher??FO)();if(o!==null)return await $O(i,o,n,r),o}return s?.policy??pi}function jO(){try{return Z()}catch{return null}}var bo,MO,LO,yi=_(()=>{"use strict";mr();Yt();oe();Pe();Xe();lr();xt();bo=PO(nt,"trigger-policy.json"),MO=12*60*60*1e3,LO=3e3;a(Td,"currentIdentity");a(Ad,"readCachedPolicy");a($O,"writeCachedPolicy");a(FO,"fetchTriggerPolicy");a(gr,"resolveTriggerPolicy");a(jO,"safeDeviceId")});var uw={};ne(uw,{runGuard:()=>WO});import{existsSync as UO,readFileSync as HO}from"node:fs";import{homedir as dw}from"node:os";import{join as GO}from"node:path";async function WO(e){let t=e[0],n=e.slice(1);switch(t){case"install":return aw(n,dw());case"status":return VO();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
238
|
-
`),1):(await hn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
239
|
-
`),0)}case"off":return await hn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
240
|
-
`),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>
|
|
241
|
-
`),1):(await hn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
242
|
-
`),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>
|
|
243
|
-
`),1):(await hn(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.
|
|
244
|
-
`:`${t} trigger disabled on this machine (your convention prefs are unchanged).
|
|
245
|
-
`),0)}case"skip":return KO(n);default:return process.stdout.write(BO),t===void 0||t==="--help"||t==="-h"?0:1}}async function KO(e){let t=null,n=null,r="consult";for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"?n=e[++o]??null:e[o]==="--kind"&&(r=e[++o]??"");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]
|
|
246
|
-
`),1;let i=n.trim().slice(0,500);if(r!=="consult")return await St(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await V({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
|
|
247
|
-
logged (auditable) in ${dn}
|
|
248
|
-
`),0;let s=await rt(t);return await me(t,{...s,override_reason:i}),await V({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.
|
|
249
|
-
logged (auditable) in ${dn}
|
|
250
|
-
`),0}async function VO(){let e=de(),t=GO(dw(),".claude","settings.json"),n=null;try{UO(t)&&(n=HO(t,"utf8"))}catch{}let r=en(n,{},As),i=await xb(),s=Td(),o=s?await Ad(s):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,policy:o?{difficulty:o.policy.difficulty,capture:o.policy.capture,fetched_at:o.fetchedAt,fresh:o.fresh}:null,policy_file:bo},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:dn},null,2)+`
|
|
251
|
-
`);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(`
|
|
252
|
-
[maind] guard hook wiring is incomplete:
|
|
253
|
-
`);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
|
|
254
|
-
`);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 BO,pw=_(()=>{"use strict";Yn();at();cw();it();xt();gi();yi();BO=["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(`
|
|
255
|
-
`);a(WO,"runGuard");a(KO,"runGuardSkip");a(VO,"runGuardStatus")});function fw(e){if(!e)return null;let t=e.split(`
|
|
256
|
-
`),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(`
|
|
257
|
-
`):null}function zO(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(`
|
|
258
|
-
`),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=a((s,o)=>(s??[]).map(o).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,s=>s.title?`- ${s.title}${s.id?` (${s.id})`:""}${s.summary?` \u2014 ${s.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,s=>s.id?`- ${s.id}${s.summary?`: ${s.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,s=>s.title?`- ${s.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,s=>s.id?`- ${s.id}${s.title?`: ${s.title}`:""}`:null),more:"search_lessons"}),r.filter(s=>s.lines.length>0)}function mw(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
|
|
259
|
-
`);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...zO(n));let o=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
|
|
260
|
-
|
|
261
|
-
${d.title}`;if(wo(c+u)>o){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let h=`
|
|
262
|
-
${d.lines[p]}`;if(wo(c+h)<=o){c+=h;continue}l=!1;let m=`
|
|
263
|
-
(+${d.lines.length-p} more \u2014 via ${d.more})`;wo(c+m)<=r&&(c+=m);break}if(!l)break}if(!l){let d=`
|
|
264
|
-
\u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;wo(c+d)<=r&&(c+=d)}return{text:c+`
|
|
265
|
-
`,complete:l}}var wo,hw=_(()=>{"use strict";wo=a(e=>Buffer.byteLength(e,"utf8"),"bytes");a(fw,"extractConventionsBlock");a(zO,"briefingSections");a(mw,"composeInjection")});var ww={};ne(ww,{BRIEFING_CACHE_FILE:()=>yw,formatInjection:()=>bw,resolveBriefingInjection:()=>_w,runGuardInject:()=>rD});import{existsSync as qO}from"node:fs";import{mkdir as YO,readFile as JO,rename as XO,writeFile as ZO}from"node:fs/promises";import{dirname as QO,join as eD}from"node:path";async function _w(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??yw,s=n.fetcher??J_,o=await iD(i),c=o!==null&&o.format===gw&&r-Date.parse(o.fetched_at)<tD&&o.project_key===e,l=a(p=>p.conventions?{conventions:p.conventions}:{},"withConventions");if(c)return{text:o.text,via:"cache",...l(o)};let d=null,u=await s({onInitialize:a(p=>{d=fw(p)},"onInitialize"),apiKey:t,deviceId:oD(),projectKey:e,bridgeVersion:G,timeoutMs:nD});if(u!==null){let p=d;return await sD(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:gw,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return o!==null?{text:o.text,via:"stale-cache",...l(o)}:{text:null,via:"none"}}async function rD(){try{if(de().mode==="off")return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await kb();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await rt(n);return await me(n,{...u,carryover:!0}),0}let i=K();if(i===null)return 0;let s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),o=z(),c=await _w(o,i),l=await rt(n);if(c.text===null)return await me(n,{...l,inject_failed:!0}),await V({event:"inject_fail",session_id:n,cwd:s,project_key:o??void 0}),process.stderr.write(`[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.
|
|
266
|
-
`),0;let d=bw(c.text,c.via,c.conventions??null);return process.stdout.write(d.text),await me(n,{...l,injected:!0}),await V({event:"inject_ok",session_id:n,cwd:s,project_key:o??void 0,detail:d.complete?c.via:`${c.via}+budget`}),0}catch{return 0}}function bw(e,t,n=null){return mw(`[maind guard] Session briefing${n?" + project conventions":""}, injected deterministically (ADR-284)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`,n,e)}async function iD(e){try{if(!qO(e))return null;let t=JSON.parse(await JO(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 sD(e,t){try{await YO(QO(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await ZO(n,JSON.stringify(t,null,2),{mode:384}),await XO(n,e)}catch{}}function oD(){try{return Z()}catch{return null}}var yw,tD,gw,nD,vw=_(()=>{"use strict";oe();we();Pe();Xe();at();hw();it();xt();lr();yw=eD(nt,"briefing-cache.json"),tD=12*60*60*1e3,gw=2,nD=3e3;a(_w,"resolveBriefingInjection");a(rD,"runGuardInject");a(bw,"formatInjection");a(iD,"readCache");a(sD,"writeCache");a(oD,"safeDeviceId")});var Sw={};ne(Sw,{bashOutputOf:()=>kw,consultedAtOf:()=>vo,outcomeFromHook:()=>xw,runGuardDifficulty:()=>cD});function kw(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(`
|
|
267
|
-
`):null,interrupted:t.interrupted===!0}}function xw(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"?kw(e.tool_response):{output:null,interrupted:!1},s=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:i.output,isInterrupt:e.is_interrupt===!0||i.interrupted,isSubagent:typeof s=="string"&&s.length>0}}}function vo(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 aD(e,t,n){if(!hr(e))return;let r=await gn(e);if(!r.some(o=>o.k==="fail"&&o.v===t))return;let i=pr(r,null,n);await St(e,{t:n,k:"ok",v:t});let s=i.chain;s!==null&&s.failures.length>=4&&!i.resolved&&s.lastVerb===t&&await V({event:"difficulty_resolved",session_id:e,detail:String(s.failures.length)})}async function cD(){try{let e=de();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=xw(t);if(r===null)return 0;let i=id(r.outcome);if(i===null)return 0;let s=Date.now();if(i.kind==="ok")return await aD(n,i.verb,s),0;await St(n,{t:s,k:"fail",v:i.verb});let o=await gn(n),c=pr(o,vo(await q(),n),s);if(!ad(c)||c.chain===null)return 0;let l=await gr(!0);if(!e.difficulty||!fr(l.difficulty))return 0;await St(n,{t:s,k:"nudge"});let d=fi(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?Sb(d):fo(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await V({event:"difficulty_nudge",session_id:n,cwd:u,project_key:z()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Rd=_(()=>{"use strict";mr();we();pn();tt();Pe();at();it();gi();yi();a(kw,"bashOutputOf");a(xw,"outcomeFromHook");a(vo,"consultedAtOf");a(aD,"recordSuccess");a(cD,"runGuardDifficulty")});var Rw={};ne(Rw,{decideDifficultyGate:()=>Aw,decideGate:()=>Tw,runGuardGate:()=>uD});function Tw(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:Ew(n)}:(n.deny_count??0)>=ko?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. "+Ew(n)}:{kind:"deny",reason:lD(e.sessionId,n)}}function Ew(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 lD(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:
|
|
268
|
-
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
269
|
-
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
270
|
-
After ${ko} denies this gate downgrades itself to warn.`}function Aw(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)>=ko?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. "+fi(n.chain)}:{kind:"deny",reason:dD(n,e.sessionId)}}function dD(e,t){return`[maind guard | block] Edit denied \u2014 ${pd(e.chain)}. Two exits:
|
|
271
|
-
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.
|
|
272
|
-
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
|
|
273
|
-
After ${ko} denies this gate downgrades itself to warn.`}async function uD(){try{let e=de();if(e.mode==="off")return 0;let t=await W(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await rt(r),s=vo(await q(),r),o=s!==null,c=Tw({mode:e.mode,session:i,consulted:o,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=z()??void 0;if(c.kind==="deny")return process.stdout.write(un(c.reason)),await me(r,{...i,deny_count:(i.deny_count??0)+1}),await V({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(st(c.context)),await me(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await V({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&hr(r)){let u=pr(await gn(r),s,Date.now()),p=u.open?Aw({mode:e.mode,enabled:e.difficulty,denyCapable:dd((await gr(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(un(p.reason)),await me(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await V({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(st(p.context)),await me(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await me(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var ko,Iw=_(()=>{"use strict";mr();we();pn();tt();Pe();at();Rd();it();xt();gi();yi();ko=3;a(Tw,"decideGate");a(Ew,"warnText");a(lD,"denyText");a(Aw,"decideDifficultyGate");a(dD,"difficultyDenyText");a(uD,"runGuardGate")});var Cw={};ne(Cw,{decideStopGate:()=>Nw,runGuardStop:()=>fD});function Nw(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function fD(){try{let e=de();if(e.mode==="off"||!e.stopGate)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await rt(n),i=(await q()).guard_signals?.[n]?.reviewed_at!==void 0;return Nw({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:pD})),await me(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var pD,Ow=_(()=>{"use strict";we();tt();at();it();xt();a(Nw,"decideStopGate");pD="[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.";a(fD,"runGuardStop")});var Mw={};ne(Mw,{capturedAtOf:()=>Dw,decideCapture:()=>Pw,runGuardCapture:()=>mD});function Dw(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 Pw(e){if(e.stopHookActive||!fr(e.policy.capture))return null;let t=cd(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:fd(t)}}async function mD(){try{let e=de();if(e.mode==="off"||!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!hr(n))return 0;let r=Pw({events:await gn(n),capturedAtMs:Dw(await q(),n),policy:await gr(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await St(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await V({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var Lw=_(()=>{"use strict";mr();we();tt();at();it();gi();yi();a(Dw,"capturedAtOf");a(Pw,"decideCapture");a(mD,"runGuardCapture")});import{appendFile as hD,mkdir as gD,readFile as Fw,rename as jw,writeFile as Uw}from"node:fs/promises";import{homedir as Hw}from"node:os";import{join as Gw}from"node:path";function Bw(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},s=new Map,o=1/0,c=-1/0;for(let d of e){d.at<o&&(o=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=s.get(d.convention_id);(p===void 0||d.convention_version>p)&&s.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(o).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function yn(){return Gw(Hw(),".maind","gateway","attest-spool.jsonl")}async function Id(e){let t=K();if(t===null)return!1;let n=await et("gateway_attest",{...e},{apiKey:t,deviceId:Z(),projectKey:e.project_key??null,bridgeVersion:G,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function Ww(e){try{await gD(Gw(Hw(),".maind","gateway"),{recursive:!0}),await hD(yn(),JSON.stringify(e)+`
|
|
274
|
-
`,{mode:384}),await yD()}catch{}}async function yD(){try{let t=(await Fw(yn(),"utf8")).split(`
|
|
275
|
-
`).filter(r=>r.trim());if(t.length<=$w)return;let n=`${yn()}.${process.pid}.tmp`;await Uw(n,t.slice(-$w).join(`
|
|
276
|
-
`)+`
|
|
277
|
-
`,{mode:384}),await jw(n,yn())}catch{}}async function Kw(){let e;try{e=(await Fw(yn(),"utf8")).split(`
|
|
278
|
-
`).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 Id(i)||(n=!0,t.push(r))}try{let r=`${yn()}.${process.pid}.tmp`;await Uw(r,t.length>0?t.join(`
|
|
279
|
-
`)+`
|
|
280
|
-
`:"",{mode:384}),await jw(r,yn())}catch{}}var $w,Vw=_(()=>{"use strict";oe();lr();Xe();$w=256;a(Bw,"aggregateWindow");a(yn,"attestSpoolPath");a(Id,"postAttestation");a(Ww,"spoolAttestation");a(yD,"capSpool");a(Kw,"flushAttestSpool")});function _i(e=process.env,t=Fe()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function xo(e=process.env,t=Fe()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function zw(e,t=Qe()){let n={};try{let i=await ce(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await ee(t,JSON.stringify(r,null,2)+`
|
|
281
|
-
`,384)}async function qw(e,t=Qe()){await zw({gateway_mode:e},t)}async function Yw(e,t=Qe()){await zw({gateway_attest:e},t)}function Jw(e=process.env,t=Fe()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Nd=_(()=>{"use strict";Jn();$e();a(_i,"resolveGatewayMode");a(xo,"resolveGatewayAttest");a(zw,"writeGatewayConfigPatch");a(qw,"writeGatewayMode");a(Yw,"writeGatewayAttest");a(Jw,"resolveShaProofMode")});function Zw(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,s=i.gateway_gate;if(typeof s!="object"||s===null)continue;let o=s;if(o.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"&&_D.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(o.servers)?o.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let h=Array.isArray(o.deny_tools)?o.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of h){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function bD(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Qw(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)bD(s,e,t)&&(i===null||Xw[s.severity]>Xw[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function ev(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 _D,Xw,Cd=_(()=>{"use strict";_D=new Set(["required","recommended","info"]);a(Zw,"extractGatewayRules");Xw={required:2,recommended:1,info:0};a(bD,"ruleMatches");a(Qw,"decideToolCall");a(ev,"policyDenyText")});import{mkdirSync as wD,readFileSync as vD,renameSync as kD,writeFileSync as xD}from"node:fs";import{homedir as SD}from"node:os";import{dirname as ED,join as TD}from"node:path";function tv(){return TD(SD(),".maind","gateway","policy-cache.json")}function So(e,t,n=new Date().toISOString()){try{let r={version:Od,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=tv();wD(ED(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;xD(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),kD(s,i)}catch{}}function Eo(e){try{let t=vD(tv(),"utf8"),n=JSON.parse(t);return n.version!==Od||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Od,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Od,Dd=_(()=>{"use strict";Od=1;a(tv,"policyCachePath");a(So,"writePolicyCache");a(Eo,"readPolicyCache")});function bi(e=process.env){let t=e.MAIND_MCP_URL??ci,n=K();return{mcpUrl:t,keyFp:n?Hn(n):"anon"}}async function To(e=6e3){let t=K();if(t===null)return null;let n=null;try{n=z()}catch{n=null}let r=await et("get_conventions",{},{apiKey:t,deviceId:Z(),projectKey:n,bridgeVersion:G,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Zw(i)}var Pd=_(()=>{"use strict";Yt();oe();lr();Pe();Xe();Cd();a(bi,"policyIdentity");a(To,"fetchGatewayRules")});function wi(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 AD(e){if(wi(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 RD(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:wi(e)?{action:"skip",reason:"already-wrapped"}:AD(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function nv(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],s=typeof e.env=="object"&&e.env!==null?e.env:void 0,o=s||t.env?{...s??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return o&&(c.env=o),c}function rv(e){if(!wi(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 iv(e){return Object.entries(e).map(([t,n])=>{let r=RD(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var sv=_(()=>{"use strict";a(wi,"isGatewayWrapped");a(AD,"isMaindProxyEntry");a(RD,"classifyServer");a(nv,"wrapServerEntry");a(rv,"unwrapServerEntry");a(iv,"planRewrites")});var uv={};ne(uv,{runGatewayInstall:()=>PD,runGatewayUninstall:()=>MD});import{existsSync as ID,readFileSync as ND}from"node:fs";import{homedir as CD}from"node:os";import{join as ov}from"node:path";import{createInterface as OD}from"node:readline";function av(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 cv(){return[{label:"Claude Code (project .mcp.json)",path:ov(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:ov(CD(),".claude.json")}]}async function lv(e){let t=OD({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 dv(e){let t=DD(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 DD(e){try{return ID(e)?ND(e,"utf8"):null}catch{return null}}async function PD(e){let t=av(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
282
|
-
`),2;let n=Me({entryPath:Le(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of cv()){let s=dv(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
283
|
-
`);continue}let o=iv(s.servers);for(let c of o){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
284
|
-
`);continue}if(!(t.yes||await lv(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
285
|
-
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
286
|
-
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
287
|
-
`);continue}s.servers[c.key]=nv(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
288
|
-
`)}!t.dryRun&&o.some(c=>c.action==="wrap")&&await ee(i.path,JSON.stringify(s.raw,null,2)+`
|
|
289
|
-
`,384)}return process.stderr.write(r>0?`
|
|
290
|
-
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
291
|
-
`:`
|
|
292
|
-
Nothing to wrap.
|
|
293
|
-
`),0}async function MD(e){let t=av(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
294
|
-
`),2;let n=0;for(let r of cv()){let i=dv(r.path);if(i===null)continue;let s=!1;for(let[o,c]of Object.entries(i.servers)){if(!wi(c)||!(t.yes||await lv(`Unwrap MCP server '${o}' in ${r.label}?`)))continue;let d=rv(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${o} \u2014 wrapped shape unrecognized, left untouched
|
|
295
|
-
`);continue}i.servers[o]=d,s=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${o}
|
|
296
|
-
`)}!t.dryRun&&s&&await ee(r.path,JSON.stringify(i.raw,null,2)+`
|
|
297
|
-
`,384)}return process.stderr.write(n>0?`
|
|
298
|
-
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
299
|
-
`:`
|
|
300
|
-
Nothing wrapped \u2014 nothing to restore.
|
|
301
|
-
`),0}var pv=_(()=>{"use strict";$e();Vn();sv();a(av,"parseFlags");a(cv,"targets");a(lv,"confirm");a(dv,"loadConfig");a(DD,"readFileSafeSync");a(PD,"runGatewayInstall");a(MD,"runGatewayUninstall")});var fv={};ne(fv,{runGatewayAttest:()=>$D,runGatewayMode:()=>LD,runGatewayPolicy:()=>UD});async function LD(e){let t=e[0];if(t===void 0){let n=_i(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
302
|
-
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
303
|
-
`),2):(await qw(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
304
|
-
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
305
|
-
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
306
|
-
`)),0)}async function $D(e){let t=e[0];if(t===void 0){let n=xo(),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)":""}.
|
|
307
|
-
`+(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.
|
|
308
|
-
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
309
|
-
`),2):(await Yw(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.
|
|
310
|
-
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
311
|
-
`),0)}function FD(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
312
|
-
`;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})
|
|
313
|
-
`}return t}function jD(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 UD(e){let t=e.includes("--refresh"),n=_i(),r=bi();if(t){let s=await To();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
314
|
-
`):(So(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
|
|
315
|
-
`))}let i=Eo(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
316
|
-
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
317
|
-
`),0):(process.stdout.write(`maind: policy from cache (${jD(i)}, ${r.mcpUrl}):
|
|
318
|
-
`),process.stdout.write(FD(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.
|
|
319
|
-
`),0)}var mv=_(()=>{"use strict";Nd();Dd();Pd();a(LD,"runGatewayMode");a($D,"runGatewayAttest");a(FD,"renderRules");a(jD,"cacheAge");a(UD,"runGatewayPolicy")});var bv={};ne(bv,{gatewayEventsFile:()=>yv,parseGatewayArgs:()=>_v,runGateway:()=>zD});import{spawn as HD}from"node:child_process";import{appendFile as GD,mkdir as BD}from"node:fs/promises";import{homedir as hv}from"node:os";import{basename as WD,join as gv}from"node:path";import{createInterface as KD}from"node:readline";function yv(){return gv(hv(),".maind","gateway","events.jsonl")}async function VD(e){try{let t=yv();await BD(gv(hv(),".maind","gateway"),{recursive:!0}),await GD(t,JSON.stringify(e)+`
|
|
320
|
-
`,{mode:384})}catch{}}function _v(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let s=e[r+1];if(!s)return null;t.add(s),r+=2;continue}if(i==="--label"){let s=e[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=e[r+1];return s?{denyTools:t,label:n,command:s,args:e.slice(r+2)}:null}return null}return null}async function zD(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:R}=await Promise.resolve().then(()=>(pv(),uv));return e[0]==="install"?S(e.slice(1)):R(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:S,runGatewayMode:R,runGatewayPolicy:D}=await Promise.resolve().then(()=>(mv(),fv));return e[0]==="mode"?R(e.slice(1)):e[0]==="attest"?S(e.slice(1)):D(e.slice(1))}let t=_v(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
321
|
-
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
322
|
-
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
323
|
-
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
324
|
-
maind-mcp-bridge gateway policy [--refresh]
|
|
325
|
-
maind-mcp-bridge gateway attest [on|off]
|
|
326
|
-
EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
327
|
-
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
328
|
-
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
329
|
-
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
330
|
-
`),2;let{denyTools:n,label:r,command:i,args:s}=t,o=r??WD(i),c=_i(),l=Jw(),d=l==="off"?null:ki(),u=c==="off"?[]:Eo(bi())?.rules??[];c!=="off"&&To().then(S=>{S!==null&&(u=S,So(bi(),S))}).catch(()=>{});let p=[],h=xo()&&K()!==null&&c!=="off",m=null;try{m=z()}catch{m=null}let g=a(S=>{VD(S),h&&p.push(S)},"record"),y=a(async()=>{if(!h)return;let S=Bw(p.splice(0),c,o,m);S!==null&&(await Id(S)||await Ww(S))},"attestAndReset");h&&Kw().catch(()=>{});let v=setInterval(()=>{y()},30*6e4);v.unref();let w=HD(i,s,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(S)}
|
|
331
|
-
`),process.exitCode=1});let b=KD({input:process.stdin,terminal:!1});b.on("line",S=>{let R=Jd(S);if(R.kind==="request"&&R.method==="tools/call"&&R.toolName){if(n.has(R.toolName)&&R.id!==void 0){process.stdout.write(bn(R.id,R.toolName)+`
|
|
332
|
-
`),g(Io("deny",o,R.toolName,Date.now()));return}let D=Qw(R.toolName,o,u,c);if(D.kind==="deny"&&R.id!==void 0){process.stdout.write(bn(R.id,R.toolName,ev(R.toolName,D.rule))+`
|
|
333
|
-
`),g(No("policy_deny",o,R.toolName,Date.now(),D.rule.conventionId,D.rule.conventionVersion));return}(D.kind==="warn"||D.kind==="deny")&&g(No("policy_warn",o,R.toolName,Date.now(),D.rule.conventionId,D.rule.conventionVersion));let F=xi(S,d);if(F.length>0){let H=F.find(j=>j.verdict==="fabricated");if(H!==void 0&&l==="enforce"&&c==="enforce"&&R.id!==void 0&&H!==void 0&&R.id!==void 0){process.stdout.write(bn(R.id,R.toolName,wn(H,!0))+`
|
|
334
|
-
`),g(Co("sha_deny",o,R.toolName,Date.now()));return}let N=H??F[0];process.stderr.write(`[maind gateway] ${wn(N,!1)}
|
|
335
|
-
`),g(Co("sha_warn",o,R.toolName,Date.now()))}g(Io("tool_call",o,R.toolName,Date.now()))}w.stdin.write(S+`
|
|
336
|
-
`)}),b.on("close",()=>{w.stdin.end()});let k=await new Promise(S=>{w.on("exit",(R,D)=>{S(R??(D?1:0))})});return clearInterval(v),await y(),k}var wv=_(()=>{"use strict";Oo();Vw();Nd();Cd();Do();Dd();Pd();oe();Pe();a(yv,"gatewayEventsFile");a(VD,"logEvent");a(_v,"parseGatewayArgs");a(zD,"runGateway")});var Hd={};ne(Hd,{MAX_ENTRIES:()=>Md,TTL_MS:()=>Fd,crossSessionDir:()=>jd,decideCrossSession:()=>xv,parseSessionDb:()=>kv,pruneDb:()=>Ud,runGuardCrossCheck:()=>nP,runGuardCrossObserve:()=>tP,staleReason:()=>Ld});import{mkdir as qD,readFile as YD,readdir as JD,stat as vv,unlink as XD,writeFile as ZD}from"node:fs/promises";import{homedir as QD}from"node:os";import{join as $d}from"node:path";function jd(){return $d(QD(),".maind","cross-session")}function kv(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[s,o]of Object.entries(n.files)){if(typeof o!="object"||o===null)continue;let c=o;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[s]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[s,o]of Object.entries(n.warned))typeof o=="number"&&Number.isFinite(o)&&(i[s]=o);return{files:r,warned:i}}function Ud(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Fd);return n.length>Md&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-Md)),{files:Object.fromEntries(n),warned:e.warned}}function xv(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Ld(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 Sv(e){let t=jd();return await qD(t,{recursive:!0}),$d(t,`${e}.json`)}async function Ev(e,t){try{let n=await YD(await Sv(e),"utf8");return Ud(kv(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function Tv(e,t){try{await ZD(await Sv(e),JSON.stringify(t),{mode:384})}catch{}}async function eP(e){try{let t=jd();for(let n of await JD(t)){if(!n.endsWith(".json"))continue;let r=$d(t,n),i=await vv(r).catch(()=>null);i&&e-i.mtimeMs>Fd&&await XD(r).catch(()=>{})}}catch{}}async function Av(e){try{return(await vv(e)).mtimeMs}catch{return}}async function tP(e,t=Date.now()){try{if(de().mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=je(r);if(!i||!s)return 0;let o=await Av(s);if(o===void 0)return 0;let c=await Ev(i,t);return c.files[s]={m:o,t},delete c.warned[s],await Tv(i,Ud(c,t)),await eP(t),0}catch{return 0}}async function nP(e,t=Date.now()){try{let n=de();if(n.mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=je(r);if(!i||!s)return 0;let o=await Ev(i,t),c=xv(o.files[s]?.m,await Av(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(un(Ld(s,c))+`
|
|
337
|
-
`),await V({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(o.warned[s]===c.current||(process.stdout.write(st(Ld(s,c))+`
|
|
338
|
-
`),o.warned[s]=c.current,await Tv(i,o),await V({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var Fd,Md,Gd=_(()=>{"use strict";we();pn();at();it();Fd=48*3600*1e3,Md=500;a(jd,"crossSessionDir");a(kv,"parseSessionDb");a(Ud,"pruneDb");a(xv,"decideCrossSession");a(Ld,"staleReason");a(Sv,"dbPath");a(Ev,"loadDb");a(Tv,"saveDb");a(eP,"sweepStaleSessionFiles");a(Av,"fileMtime");a(tP,"runGuardCrossObserve");a(nP,"runGuardCrossCheck")});var Bd={};ne(Bd,{INDEX_REFRESH_WORKER:()=>Rv,acquireLock:()=>Gs,releaseLock:()=>ti,runIndexRefreshWorker:()=>cP,runOnIndexRefresh:()=>aP});import{spawn as rP}from"node:child_process";import{existsSync as iP}from"node:fs";import{join as sP}from"node:path";function oP(e){return sP(e,".maind","code-index.sqlite")}async function aP(){try{let e=await W(),t=fe(typeof e.cwd=="string"?e.cwd:process.cwd());if(!iP(oP(t))||!Gs(t))return 0;let n=process.argv[1];if(n===void 0)return ti(t),0;rP(process.execPath,[n,Rv,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function cP(){let e=process.argv[3]??fe();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(dl(),uy)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{ti(e)}return 0}var Rv,Wd=_(()=>{"use strict";we();rn();ul();Rv="index-refresh-run";a(oP,"indexDbPath");a(aP,"runOnIndexRefresh");a(cP,"runIndexRefreshWorker")});import{randomUUID as lP}from"node:crypto";import{createInterface as J0}from"node:readline";var Nv=[["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"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function Cv(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of Nv)if(t.includes(n))return r;return null}a(Cv,"mapClientInfoNameToFamily");function Yd(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ro(t)||t.method!=="initialize")return null;let n=t.params;if(!Ro(n))return null;let r=n.clientInfo;if(!Ro(r))return null;let i=r.name,s=Cv(typeof i=="string"?i:null);if(s===null)return null;let o=r.version,c=typeof o=="string"&&o.length>0?o.slice(0,64):null;return{family:s,version:c}}a(Yd,"tryExtractInitializeClient");function Ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ro,"isRecord");Oo();Do();function Po(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let s=JSON.parse(t);return Array.isArray(s)?s:[s]}catch{return[]}let n=[],r=[],i=a(()=>{if(r.length===0)return;let s=r.join(`
|
|
339
|
-
`).trim();if(r=[],s.length!==0)try{n.push(JSON.parse(s))}catch{}},"flush");for(let s of t.split(`
|
|
340
|
-
`)){let o=s.endsWith("\r")?s.slice(0,-1):s;if(o===""){i();continue}o.startsWith("data:")&&r.push(o.slice(5).replace(/^\s/,""))}return i(),n}a(Po,"rpcMessagesOf");function nu(e,t){for(let n of Po(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:{},o=(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:o?.text??""}}return null}a(nu,"parseCloudToolResponse");Yt();var X0="https://mcp.maind.dev/mcp",Br=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{a(this,"BridgeReauthNeeded")}},ys=class{static{a(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;pendingFrame=null;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=Hn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=Z0(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=Q0(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;let s=t.carry??null;s!==null&&(this.initFrame=s.initFrame,this.clientFamily===null&&(this.clientFamily=s.clientFamily),this.clientVersion===null&&(this.clientVersion=s.clientVersion),this.replayFrame=s.pendingFrame),this.shaRepoRoot=ki(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??X0}async run(t=Fc()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r)return;let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let u=Yd(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Gr(t)&&(this.initFrame=t);let r=nT(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=xi(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),h=p??u[0];if(p!==void 0&&eu(p)&&r.id!==null){let m=wn(p,!0);process.stderr.write(`[maind] ${m}
|
|
341
|
-
`);let g=r.params?.name;process.stdout.write(bn(r.id,typeof g=="string"?g:"unknown",m)+`
|
|
342
|
-
`);return}i=wn(h,!1),process.stderr.write(`[maind] ${i}
|
|
343
|
-
`)}}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+`
|
|
344
|
-
`);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Gr(t)&&await this.recoverSession();let o=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:o,body:t})}catch(u){let p=hs(t);if(this.serveInitializeFromCache(t,p))return;gs(p,-32603,`bridge network error: ${Hh(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&&!Gr(t)){let u=await c.text().catch(()=>"");if(Uh(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=hs(t);gs(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=hs(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;gs(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(s&&this.localRouter){let u=d.startsWith("text/event-stream")?await Lc(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
345
|
-
`);return}if(Gr(t)){let u=d.startsWith("text/event-stream")?await Lc(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
346
|
-
`);return}if(i!==null){let u=d.startsWith("text/event-stream")?await Lc(c):await c.text(),p=tT(u,i);p.trim().length>0&&process.stdout.write(p+`
|
|
347
|
-
`);return}if(d.startsWith("text/event-stream"))await eT(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
348
|
-
`)}}}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 Br(iT(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let o=hs(n);gs(o,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(t,n){try{this.onConnectionOutcome?.(t,n)}catch{}}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),s=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return sT(s)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,s=await this.postCloudToolCall(t,n,i);if(s.kind!=="session_lost")return s;if(!await this.recoverSession())return{kind:"http_error",status:404,body:s.body.slice(0,500)};let o=await this.postCloudToolCall(t,n,i);return o.kind==="session_lost"?{kind:"http_error",status:404,body:o.body.slice(0,500)}:o}async postCloudToolCall(t,n,r){this.cloudFrameId+=1;let i=`maind-bridge-${this.cloudFrameId}`,s=JSON.stringify({jsonrpc:"2.0",id:i,method:"tools/call",params:{name:t,arguments:n}});try{let o=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:s,signal:AbortSignal.timeout(r)}),c=o.headers.get("mcp-session-id");c&&c!==this.sessionId&&(this.sessionId=c);let l=await o.text();return o.status===404&&Uh(l)?{kind:"session_lost",body:l}:o.ok?nu(l,i)??{kind:"transport_error",message:`the response carried no answer to ${i}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:o.status,body:l.slice(0,500)}}catch(o){return{kind:"transport_error",message:Hh(o),timedOut:rT(o)}}}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=Je()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&$h(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Gr(t))return!1;let r=Fh(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(jh(n,r)+`
|
|
349
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ms(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Fc(){return J0({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}a(Fc,"stdinLines");function Z0(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}a(Z0,"normalizeClientFamily");function Q0(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}a(Q0,"normalizeClientVersion");async function eT(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=a(()=>{if(i.length===0)return;let o=i.join(`
|
|
350
|
-
`).trim();i=[],o.length>0&&process.stdout.write(o+`
|
|
351
|
-
`)},"flushEvent");try{for(;;){let{value:o,done:c}=await t.read();if(c)break;r+=n.decode(o,{stream:!0});let l;for(;(l=r.indexOf(`
|
|
352
|
-
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){s();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{s()}}a(eT,"pipeSseToStdout");function tT(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}}a(tT,"appendNoteToToolResult");function nT(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}a(nT,"parseRpc");async function Lc(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=[],o=a(()=>{if(s.length===0)return;let c=s.join(`
|
|
353
|
-
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
354
|
-
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){o();continue}p.startsWith(":")||p.startsWith("data:")&&s.push(p.slice(5).replace(/^\s/,""))}}}finally{o()}return i.join(`
|
|
355
|
-
`)}a(Lc,"collectSseText");function hs(e){try{return JSON.parse(e).id??null}catch{return null}}a(hs,"tryExtractId");function Gr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}a(Gr,"isInitializeRequest");function Uh(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")}a(Uh,"isSessionLossBody");function Hh(e){return e instanceof Error?e.message:String(e)}a(Hh,"stringifyErr");function rT(e){return e?.name==="TimeoutError"}a(rT,"isTimeoutError");function gs(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
356
|
-
`)}a(gs,"emitJsonRpcError");function iT(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}a(iT,"extractHint");function sT(e){try{let t=Po(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}}a(sT,"parsePresenceToolResult");oe();oe();Bn();import{spawn as gT}from"node:child_process";import{platform as yT}from"node:os";async function Wn(e,t=process.stderr){let n=Kr(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=bs(e),o=`mcp-bridge-${s.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:o,meta:s})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await vT(l.verification_uri_complete).catch(()=>{}),wT(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await bT(u);let p=await _T(i,l.device_code).catch(h=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(h)}
|
|
357
|
-
`),null));if(p){if(p.status==="approved")return Xt(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
358
|
-
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
359
|
-
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
360
|
-
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
361
|
-
`),null}a(Wn,"runDeviceFlow");async function _T(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()}a(_T,"pollOnce");function bT(e){return new Promise(t=>setTimeout(t,e))}a(bT,"sleep");function wT(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: ${Vh(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Vh(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(`
|
|
362
|
-
`)+`
|
|
363
|
-
`)}a(wT,"printAuthInstructions");function Vh(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}a(Vh,"pad");async function vT(e){let t,n;switch(yT()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let s=gT(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}a(vT,"openExternalBrowser");Gc();Xe();Pe();Xe();import*as Ey from"node:os";qr();function ig(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,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"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Te("--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 Te("--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 Te("--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 Te("--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 Te(`--client requires a family argument (${zr.join(", ")})`);let s=i.trim().toLowerCase();if(!zr.includes(s))throw new Te(`--client "${i}" is not a known client family. Known: ${zr.join(", ")}`);t.client=s,n++;break}default:throw new Te(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}a(ig,"parseInstallFlags");var Te=class extends Error{static{a(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function sg(){process.stdout.write(HT())}a(sg,"printInstallHelp");function HT(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${zr.join(", ")}`," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --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(`
|
|
364
|
-
`)}a(HT,"installHelpText");var Ss=class{static{a(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_
|
|
365
|
-
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),s=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),o=a((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(s)} |`,l=[];l.push(`| ${o(t[0],n)} | ${o(t[1],r)} | ${o(t[2],i)} | ${o(t[3],s)} |`),l.push(c);for(let d of this.results)l.push(`| ${o(d.target,n)} | ${o(d.action,r)} | ${o(d.status,i)} | ${o(d.detail??"",s)} |`);return l.join(`
|
|
366
|
-
`)+`
|
|
367
|
-
`}print(t){let n=this.summary();t.write(`
|
|
368
|
-
`),t.write(this.toMarkdownTable()),t.write(`
|
|
369
|
-
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
370
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as og from"node:fs/promises";import*as _t from"node:path";import*as ag from"node:readline";var GT=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function cg(e){let t=_t.resolve(e),n=t;for(;;){if(await dg(n))return n;let r=_t.dirname(n);if(r===n)return t;n=r}}a(cg,"detectProjectRoot");async function lg(e){let n=_t.resolve(e),r=[];for(;;){await dg(n)&&r.push(n);let i=_t.dirname(n);if(i===n)break;n=i}return r}a(lg,"findAllProjectRoots");async function dg(e){for(let t of GT)try{return await og.access(_t.join(e,t)),!0}catch{}return!1}a(dg,"hasAnyMarker");async function ug(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
130
|
+
`,Hn="schema_version",Bn="last_index_commit",Rc="last_indexed_at",cs="edges_dirty",Ic="resolve_config_fp",ls="embed_recipe_version",ds="embed_model",us="embed_dim",Nc="last_synced_at",Ch="last_synced_commit"});function Cc(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 Oh(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of Cc(e.name))t.add(i);for(let i of Cc(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Dh(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 Cc(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Oc=_(()=>{"use strict";a(Cc,"splitIdentifier");a(Oh,"buildSearchText");a(Dh,"toFtsMatchQuery")});import{readFileSync as Ph}from"node:fs";import{posix as Mh}from"node:path";function Lh(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 zt(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function $h(e){return e==="added"?0:e==="modified"?1:2}function rT(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 o of n.addedRanges){let c=Math.max(o.start,e.startLine),l=Math.min(o.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(o=>o>=e.startLine-1&&o<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Gr,Dc=_(()=>{"use strict";Tr();Rf();la();Nf();Pf();ua();Hf();ce();Xf();xa();Da();Mr();Tc();jr();Ih();Br();Oc();Gr=class{static{a(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(Hn),i=await this.store.countFiles()>0;(t.full||i&&r!==Un)&&await this.wipe();let s=await this.store.getAllFiles(),o;if(t.onlyChangedSince!==void 0){if(s.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let b=ba(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(b===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");o=b}else o=Vf(this.repoRoot);let c=new Set(o.map(b=>b.path)),l=new Map(s.map(b=>[b.path,b])),d=s.length>0&&!t.full,u={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},p=!1,h=a(async()=>{p||(p=!0,await this.store.setMeta(cs,"1"))},"markEdgesDirty");for(let b of s)c.has(b.path)||(await h(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of o){m++;let k=qf(this.repoRoot,b.path);if(!k){u.filesSkipped++;continue}let E=l.get(b.path);if(E&&E.mtimeMs===k.mtimeMs&&E.size===k.size){u.filesSkipped++;continue}let w=this.readRepoFile(b.path);if(w===null){u.filesSkipped++;continue}let x=Vi(w);if(E&&E.contentHash===x){await this.store.upsertFile({...E,mtimeMs:k.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let I=await this.parser.parse(b.path,w,b.language),F=new Map;for(let H of I.nodes)F.set(H.nodeKey,Oh(H));let B={path:b.path,language:b.language,contentHash:x,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await h(),await this.store.replaceFileNodes(B,I.nodes,F,{contains:I.edges,refs:I.refs,imports:I.imports,exports:I.exports}),u.filesParsed++,t.onProgress?.({path:b.path,done:m,total:o.length})}let g=Cf(this.repoRoot),y=await this.store.getMeta(Ic)!==g.fingerprint;if(p||y||await this.store.getMeta(cs)==="1"){let b=jf(await this.store.getNameIndex()),k=new Dn(g.config,b.files),E=Uf(await this.store.getAllFacts(),b,k);await this.store.replaceCrossFileEdges(E),await this.store.setMeta(Ic,g.fingerprint),await this.store.setMeta(cs,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...ca]),k=await this.store.getEmbeddingContentHashes(),E=[];for(let x of b){let I=Af(x),F=Vi(`${this.embedder.recipeVersion}\0${I}`);k.get(x.nodeKey)!==F&&E.push({nodeKey:x.nodeKey,text:I,hash:F})}let w=64;for(let x=0;x<E.length;x+=w){let I=E.slice(x,x+w),F=await this.embedder.embedDocuments(I.map(H=>H.text));await this.store.upsertEmbeddings(I.map((H,C)=>({nodeKey:H.nodeKey,dim:this.embedder.dim,vec:F[C],contentHash:H.hash})));let B=Math.min(x+w,E.length);t.onProgress?.({path:"embedding symbols",done:B,total:E.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(ls,this.embedder.recipeVersion),await this.store.setMeta(ds,this.embedder.model),await this.store.setMeta(us,String(this.embedder.dim))}await this.store.setMeta(Hn,Un),await this.store.setMeta(Rc,String(n));let v=Nr(this.repoRoot);return v&&await this.store.setMeta(Bn,v),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(Rc);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(Bn),schemaVersion:await this.store.getMeta(Hn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=zt(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let o of i){let c=await this.store.getNode(o.nodeKey);c&&s.push({...Lh(c),score:o.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=zt(n.limit,20,100),i=await this.embedder.embedQuery(t),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:If(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of o){let d=await this.store.getNode(l.nodeKey);d&&c.push({...Lh(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=zt(n.maxDepth,3,5),s=zt(n.limit,100,1e3),o=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let h=[];for(let m of u){let g=await this.store.neighbors(m,r,o,s);for(let y of g){let v=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(v))continue;if(l.add(v),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let b=r==="out"?y.dstKey:y.srcKey;d.has(b)||(d.add(b),h.push(b))}}u=h}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=Ph(Mh.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 o of n)i[o.kind]=o.count;let s={};for(let o of r)s[o.language]=o.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(zt(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=ba(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=zt(t.limit,64,200),i=[],s=0;for(let o of n){let c=await this.store.getNodesByFile(o.path);c.length>0&&s++,i.push(...c)}return i.sort((o,c)=>o.filePath.localeCompare(c.filePath)||o.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Ki(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(Nr(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return rm(this.repoRoot,n,t)}async checkDivergence(t={}){return Dr(this.repoRoot,t)}async checkNumberCollisions(t={}){return Bt(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Gt(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Wt(this.repoRoot,t)}async reviewDetectors(t={}){return Sc(this.repoRoot,t)}async reviewDetectorScopes(t={}){return Ec(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Ki(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Jf(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",o=Rh({paths:n,hunks:i,readUntracked:a(h=>this.readRepoFileHead(h,Yf),"readUntracked")}),c=Kf(n.keys()),l=zt(t.limit,64,t.attest?mt:200),d=[],u=0,p=0;for(let h of c){let m=await this.store.getNodesByFile(h.path);if(m.length===0)continue;u++;let g=await this.store.getFile(h.path),y=this.readRepoFile(h.path),v=g!==null&&y!==null&&Vi(y)!==g.contentHash;v&&(p++,s==="full"&&(s="partial"));let b=n.get(h.path)??"modified",k=i.get(h.path);for(let E of m)d.push(rT(E,b,k,v))}return d.sort((h,m)=>$h(h.change)-$h(m.change)||(h.filePath<m.filePath?-1:h.filePath>m.filePath?1:0)||h.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:o,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:Nr(this.repoRoot),dirty:wa(this.repoRoot),baseSha:t.since?zi(this.repoRoot,t.since):null,mergeBaseSha:t.since?_a(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 Ph(Mh.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};a(Lh,"toHit");a(zt,"clampLimit");a($h,"changeRank");a(rT,"classifyReviewSymbol")});var Fh=_(()=>{"use strict";ce()});var iT,EU,jh=_(()=>{"use strict";ce();iT=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],EU=new RegExp(iT.join("|"),"g")});import{existsSync as Pc,readdirSync as sT,readFileSync as oT}from"node:fs";import{spawnSync as aT}from"node:child_process";import{dirname as cT,join as ps,posix as Mc}from"node:path";function Hh(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 ${Lc} 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 ${Lc} 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,h=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${h?`: ${h}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),s=new Set(e.fileVersions),o=e.fileVersions.filter(p=>!i.has(p)).sort(qe);o.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${o.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${o.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:o});let c=r.versions.filter(p=>!s.has(p)).sort(qe),l=new Map,d=[];for(let p of c){let h=e.siblingVersions.get(p);if(h){let m=l.get(h)??[];m.push(p),l.set(h,m)}else d.push(p)}for(let[p,h]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${h.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${h.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:h});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),h=e.fileVersions.filter(g=>!p.has(g)).sort(qe),m=e.remote.versions.filter(g=>!s.has(g)).sort(qe);h.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${h.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${h.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:h}),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 Bh(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Wh(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 Uh(e,t,n){let r=e(t,lT,n);return r.ok===!1?Wh(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
132
|
+
`).map(i=>i.trim()).filter(Boolean)}}function Kh(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 dT(e){let t=R(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=cT(t);return n===e?null:n}function uT(e,t,n){let r=Mc.dirname(t),s=[{path:ps(e,r,"config.toml"),source:"worktree"}],o=dT(e);o&&s.push({path:ps(o,r,"config.toml"),source:"main_worktree"});for(let c of s)if(Pc(c.path))try{let l=Kh(oT(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 pT(e,t){let n=new Map,r=R(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=R(e,["rev-parse","--show-toplevel"])?.trim();for(let s of r.split(`
|
|
133
|
+
`)){if(!s.startsWith("worktree "))continue;let o=s.slice(9).trim();if(!o||o===i||!Pc(o))continue;let c=ps(o,t);if(Pc(c))try{for(let l of sT(c)){let d=Mn(l);d!==null&&!n.has(d)&&n.set(d,o)}}catch{}}return n}function $c(e,t={}){let n=t.runPsql??Gh,r=t.timeoutMs??15e3,i=[],s=Ht(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let o=[],c=[],l=[];for(let p of s){let h=uT(e,p.dir,i),m=h.source==="missing"?null:Uh(n,`postgresql://postgres:postgres@127.0.0.1:${h.port}/postgres`,r),g=t.remoteDbUrl!==void 0?Uh(n,t.remoteDbUrl,r):null,y=Hh({dir:p.dir,projectRoot:ps(e,Mc.dirname(Mc.dirname(p.dir))),fileVersions:p.files.map(v=>v.version),config:h,ledger:m,siblingVersions:pT(e,p.dir),remote:g});o.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let d=Bh(l),u={open:0,warn:1,info:2};return o.sort((p,h)=>u[p.status]-u[h.status]||p.id.localeCompare(h.id)),{ok:d==="in_sync",verdict:d,findings:o,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var Lc,Gh,lT,Vh=_(()=>{"use strict";ce();Or();Lc=54322;a(Hh,"evaluateLedgerProject");a(Bh,"deriveLedgerVerdict");Gh=a((e,t,n)=>{let r=aT("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"),lT="select version from supabase_migrations.schema_migrations order by version";a(Wh,"classifyLedgerError");a(Uh,"readLedger");a(Kh,"parseDbPort");a(dT,"mainWorktreeRoot");a(uT,"resolveConfig");a(pT,"gatherSiblingVersions");a($c,"checkMigrationLedgerDrift")});var Fc,jc=_(()=>{"use strict";Fc="0.2.0"});function Uc(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:mt,attest:!0}}function Hc(e,t){let n=0,r=[];for(let s of e.symbols){let o=s.qualifiedName?s.qualifiedName:void 0;if(s.name.length===0||s.name.length>fs||o!==void 0&&o.length>ms){n+=1;continue}r.push({name:s.name,...o!==void 0?{qualified_name:o}:{},...s.kind&&s.kind.length<=qh?{kind:s.kind}:{},...s.language&&s.language.length<=Yh?{language:s.language}:{},change:s.change,changed_line_count:Math.min(Math.max(0,s.changedLineCount),Jh)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(s=>({detector_id:s.detector_id,detector_version:s.detector_version,state:s.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Fc},dropped:n}}function Bc(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 Gc(e,t,n){let r=t,i=[];r===0?i.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):i.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&i.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&i.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let s=e.changedFiles-e.indexedFiles;return s>0&&i.push(`${s} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&i.push(`Symbol list truncated at ${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 Wc(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===zh&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===zh?{kind:"invalid_params",code:n,detail:r,issues:fT(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function fT(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 Kc(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 fs,ms,qh,Yh,Jh,zh,mT,Xh=_(()=>{"use strict";Tr();jc();fs=200,ms=512,qh=64,Yh=32,Jh=1e4;a(Uc,"attestReviewOptions");a(Hc,"buildAttestPayload");a(Bc,"attestPersistDecision");a(Gc,"attestCoverageNote");zh=-32602;a(Wc,"classifyMcpErrorText");a(fT,"parseIssues");a(Kc,"isLegacyAttestRejection");mT=`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 qt=_(()=>{"use strict";bu();Dc();xa();Ac();ce();rs();cc();tc();sc();Da();Fh();jh();Aa();Mr();os();jr();Or();ss();Vh();za();Tc();Mr();jr();os();ss();Hi();la();Br();Gi();jc();Xh()});import{execFileSync as hT}from"node:child_process";import{createHash as gT}from"node:crypto";import{mkdirSync as yT,readFileSync as _T,renameSync as bT,writeFileSync as wT}from"node:fs";import{dirname as Zh,join as Qh}from"node:path";function Qe(e=process.cwd()){try{let t=hT("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 Gn(e){return gT("sha256").update(e).digest("hex").slice(0,16)}function hs(e){return Qh(e,vT)}function eg(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function tg(e,t,n,r=new Date().toISOString()){try{if(!eg(n))return;let i={version:Vc,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},s=hs(e);yT(Zh(s),{recursive:!0}),Ir(Zh(s));let o=`${s}.${process.pid}.tmp`;wT(o,JSON.stringify(i,null,2),"utf8"),bT(o,s)}catch{}}function ng(e,t){try{let n=_T(hs(e),"utf8"),r=JSON.parse(n);return r.version!==Vc||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!eg(r.result)?null:{version:Vc,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function rg(e,t,n=new Date){let r=kT(t.cached_at,n),i=t.result.instructions??"",s={...t.result,instructions:`${r}
|
|
134
|
+
|
|
135
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:s})}function kT(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${xT(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function xT(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let s=Math.floor(i/60);if(s<24)return`${s} hour${s===1?"":"s"} ago`;let o=Math.floor(s/24);return`${o} day${o===1?"":"s"} ago`}var Vc,vT,Yt=_(()=>{"use strict";qt();Vc=1,vT=Qh(".maind","conventions-cache.json");a(Qe,"resolveRepoRoot");a(Gn,"keyFingerprint");a(hs,"cachePath");a(eg,"hasInstructions");a(tg,"writeConventionsCache");a(ng,"readConventionsCache");a(rg,"buildCachedInitializeResponse");a(kT,"fallbackMarker");a(xT,"relativeAge")});import{existsSync as bs,mkdirSync as PT,readFileSync as og,writeFileSync as Xc,chmodSync as ag}from"node:fs";import{homedir as MT,hostname as LT,platform as Jc,release as $T}from"node:os";import{randomUUID as FT}from"node:crypto";import{join as Jt}from"node:path";function Ee(){let e=MT(),t=process.env;if(Jc()==="darwin")return Jt(e,"Library","Application Support","maind");if(Jc()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Jt(e,"AppData","Roaming");return Jt(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Jt(e,".config");return Jt(n,"maind")}function cg(e){bs(e)||PT(e,{recursive:!0,mode:448})}function ne(){let e=Ee();cg(e);let t=Jt(e,jT);if(bs(t)){let r=og(t,"utf8").trim();if(BT(r))return r}let n=FT();Xc(t,n+`
|
|
136
|
+
`,{encoding:"utf8",mode:384});try{ag(t,384)}catch{}return n}function BT(e){return HT.test(e)}function Zc(){return Jt(Ee(),UT)}function Xt(e){let t=Ee();cg(t);let n=Zc();Xc(n,e+`
|
|
137
|
+
`,{encoding:"utf8",mode:384});try{ag(n,384)}catch{}}function K(){let e=Zc();if(!bs(e))return null;let t=og(e,"utf8").trim();return t.length>0?t:null}function Vr(){let e=Zc();bs(e)&&Xc(e,"",{encoding:"utf8",mode:384})}function lg(){try{return`mcp-bridge-${LT()}`}catch{return"mcp-bridge"}}function ws(e){return{os:`${Jc()} ${$T()}`,ide:"mcp-bridge",ext_version:e,device_id:ne()}}var jT,UT,HT,ae=_(()=>{"use strict";a(Ee,"configDir");a(cg,"ensureDir");jT="device-id",UT="api-key";a(ne,"ensureDeviceId");HT=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;a(BT,"isUuid");a(Zc,"apiKeyPath");a(Xt,"writeApiKey");a(K,"readApiKey");a(Vr,"clearApiKey");a(lg,"bridgeLabel");a(ws,"clientMeta")});function zr(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:GT}function Wn(e){return`${zr()}/${e.replace(/^\/+/,"")}`}var GT,Kn=_(()=>{"use strict";GT="https://fn.maind.dev/functions/v1";a(zr,"functionsOrigin");a(Wn,"functionsUrl")});import{mkdirSync as JT,readFileSync as XT,renameSync as ZT,writeFileSync as QT}from"node:fs";import{join as eA}from"node:path";function ug(e=Ee()){return eA(e,nA)}function iA(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,rA)}function Zt(e,t,n){try{let r=n.dir??Ee();JT(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:iA(t),bridge_version:n.version},s=ug(r),o=`${s}.${process.pid}.tmp`;QT(o,JSON.stringify(i)+`
|
|
138
|
+
`,{encoding:"utf8",mode:384}),ZT(o,s)}catch{}}function pg(e=Ee()){try{let t=JSON.parse(XT(ug(e),"utf8"));return t.v!==1||typeof t.at!="string"||!tA.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 tA,nA,rA,Qc=_(()=>{"use strict";ae();tA=["ok","paired","auth_failed","not_paired"],nA="connection-state.json",rA=200;a(ug,"connectionStatePath");a(iA,"redactDetail");a(Zt,"writeConnectionState");a(pg,"readConnectionState")});var j,Te=_(()=>{"use strict";j="0.85.0"});import{execFileSync as fg}from"node:child_process";import{createHash as sA}from"node:crypto";function oA(e){return sA("sha256").update(e).digest("hex")}function aA(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function vs(e){let t=aA(e);return t?oA(t):null}function z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&cA.test(e))return e;let t;try{t=fg("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?vs(t):null}function ks(e){let t;try{t=fg("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?vs(t):null}var cA,Ae=_(()=>{"use strict";a(oA,"sha256Hex");a(aA,"normalizeRemoteUrl");a(vs,"projectKeyFromRemote");cA=/^[a-f0-9]{64}$/;a(z,"computeProjectKey");a(ks,"projectKeyForRepo")});import lA from"node:path";import{fileURLToPath as dA}from"node:url";function uA(e,t=lA.sep){return e.split(t).includes("_npx")}function Fe(e){let t=e.extraArgs??[],n=a(r=>({command:"npx",args:["-y",hg,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):uA(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 je(){try{let e=dA(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function zn(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${mg(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:mg(n)).join(" ")}function xs(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(hg)}function Ss(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function mg(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var hg,qn=_(()=>{"use strict";hg="@maind-dev/mcp-bridge";a(uA,"isEphemeralEntry");a(Fe,"resolveBridgeLaunch");a(je,"currentBridgeEntry");a(zn,"launchToShellCommand");a(xs,"isNpxForm");a(Ss,"isLegacyHookForm");a(mg,"shellQuote")});import*as J from"node:path";function yg(e){let t=e.launch??Fe({entryPath:je(),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 fA(e){switch(e.platform){case"darwin":return J.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??J.join(e.homeDir,"AppData","Roaming");return J.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??J.join(e.homeDir,".config");return J.join(t,"Claude","claude_desktop_config.json")}}}function _g(e){switch(e.platform){case"darwin":return J.join(e.homeDir,"Library","Application Support","Code","User");case"win32":{let t=e.appData??J.join(e.homeDir,"AppData","Roaming");return J.join(t,"Code","User")}default:{let t=e.xdgConfigHome??J.join(e.homeDir,".config");return J.join(t,"Code","User")}}}function mA(e){return J.join(_g(e),"mcp.json")}function qr(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:J.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:J.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:fA(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:J.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:{dir:J.join(e.homeDir,".cursor"),skipDetail:"Cursor not found (no ~/.cursor)"}},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:J.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json",presence:{dir:J.join(e.homeDir,".codeium","windsurf"),skipDetail:"Windsurf not found (no ~/.codeium/windsurf)"}},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:mA(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{dir:_g(e),skipDetail:"VS Code not found (no User profile dir)"}},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:J.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function bg(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function wg(e){return e.jsonShape??pA}function Es(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:gg(e.env.XDG_CONFIG_HOME),appData:gg(e.env.APPDATA)}}function gg(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}var pA,Yr,Jr=_(()=>{"use strict";qn();pA={serversKey:"mcpServers"};a(yg,"buildMaindServerEntry");a(fA,"claudeDesktopConfigPath");a(_g,"vsCodeUserDir");a(mA,"vsCodeUserMcpPath");a(qr,"getClientTargets");a(bg,"filterTargetsByFamily");a(wg,"jsonShapeOf");Yr=[...new Set(qr({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];a(Es,"makeDefaultContext");a(gg,"nonEmpty")});import*as xg from"node:fs/promises";import*as bt from"node:path";import*as Sg from"node:readline";async function Eg(e){let t=bt.resolve(e),n=t;for(;;){if(await Tg(n))return n;let r=bt.dirname(n);if(r===n)return t;n=r}}async function As(e){let n=bt.resolve(e),r=[];for(;;){await Tg(n)&&r.push(n);let i=bt.dirname(n);if(i===n)break;n=i}return r}async function Tg(e){for(let t of gA)try{return await xg.access(bt.join(e,t)),!0}catch{}return!1}async function Ag(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
371
139
|
Multiple project roots found between cwd and the filesystem root:
|
|
372
140
|
`),e.forEach((s,o)=>{process.stdout.write(` [${o+1}] ${s}
|
|
373
141
|
`)}),process.stdout.write(`
|
|
374
|
-
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=
|
|
375
|
-
`),null):e[i-1]}a(
|
|
376
|
-
`;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await ee(e.path,h)}catch(m){return Wc(e,"write",m)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}a(yg,"mergeJsonConfig");function hg(e,t,n){let r=qn(e)&&qn(e.env)?e.env:{},i={...t.env};for(let[o,c]of Object.entries(r))!(o in i)&&typeof c=="string"&&(i[o]=c);let s={command:t.command,args:[...t.args],env:i};return n.entryType===void 0?s:{type:n.entryType,...s}}a(hg,"mergeEntry");function YT(e){let t=[],n=zT(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${qT(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}a(YT,"parseJsoncStrict");function JT(e,t,n){let r=VT(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
|
|
377
|
-
`}}),i=KT(e,r);return i.endsWith(`
|
|
378
|
-
`)?i:i+`
|
|
379
|
-
`}a(JT,"editInPlace");function XT(e){return!("mcpServers"in e||!(zn in e))}a(XT,"hasRootShape");function gg(e,t,n){if(!qn(e)||n.entryType!==void 0&&e.type!==n.entryType||e.command!==t.command||!ZT(e.args,t.args)||!qn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}a(gg,"serverEntriesEqual");function ZT(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}a(ZT,"arrayEquals");function qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(qn,"isObject");function Wc(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Wc,"failed");$e();import{parse as QT,stringify as eA}from"smol-toml";async function _g(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 ce(e.path)}catch(g){return Ts(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=QT(r);if(!Qt(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return Ts(e,"parse",g)}}let o=Qt(i.mcp_servers)?i.mcp_servers:{},c=o.maind;if(Qt(c)&&tA(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Qt(c)&&Qt(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:{...o,maind:u}},h;try{h=eA(p),h.endsWith(`
|
|
380
|
-
`)||(h+=`
|
|
381
|
-
`)}catch(g){return Ts(e,"write",g)}let m=h.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:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await ee(e.path,h)}catch(g){return Ts(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}a(_g,"mergeTomlConfig");function tA(e,t){if(!Qt(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(!Qt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}a(tA,"tomlServerEntryEqual");function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Qt,"isObject");function Ts(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Ts,"failed");import*as Ze from"node:path";var nA="__STACK__";var rA="__INTENT__";var Kc="https://mcp.maind.dev/mcp",iA=`?stack=${nA}&intent=${rA}`;function sA(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}a(sA,"buildStackAwareEndpoint");var KH=sA(Kc,{stack:["nextjs","supabase"],intent:"mixed"}),Jr=`## maind MCP integration \u2014 Mandatory consultation
|
|
382
|
-
|
|
383
|
-
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
384
|
-
authoritative source for vetted coding conventions and lessons. The
|
|
385
|
-
server explicitly warns: the primary failure mode is skipping a tool
|
|
386
|
-
call when training-confidence feels sufficient \u2014 assume your training
|
|
387
|
-
memory is stale on stack-specific patterns.
|
|
388
|
-
This MCP also enforces a documentation-decision gate for non-trivial work.
|
|
389
|
-
It also enforces a documentation-path gate for non-trivial work: state
|
|
390
|
-
\`doc-path: found|missing + reason\`.
|
|
391
|
-
|
|
392
|
-
**Consultation triggers (conditional):**
|
|
393
|
-
|
|
394
|
-
1. **Session start**: call \`get_session_briefing(tools=\u2026, stack=\u2026)\`
|
|
395
|
-
even if you think you know which lessons are relevant.
|
|
396
|
-
2. **Before any plan-mode output**: call \`search_lessons\` with 2-3
|
|
397
|
-
key terms from the topic, even if you have a confident answer.
|
|
398
|
-
3. **Before non-trivial design decisions** (experiments, architecture,
|
|
399
|
-
process changes): call \`search_lessons\` with symptom keywords.
|
|
400
|
-
4. **Skip documentation**: if a trigger applies but you don't call,
|
|
401
|
-
add one line to your response: \`maind-skip: <reason>\` (e.g.
|
|
402
|
-
\`maind-skip: trivial typo fix\`). Make the decision visible.
|
|
403
|
-
|
|
404
|
-
### Roundtrip decision policy (token-aware)
|
|
405
|
-
|
|
406
|
-
Use this policy to decide *how deep* a maind roundtrip should be in a
|
|
407
|
-
given turn.
|
|
408
|
-
|
|
409
|
-
1. **Must-call (always do at least \`search_lessons\`)**
|
|
410
|
-
- Security-sensitive work (auth, secrets, RLS, permissions)
|
|
411
|
-
- Data-model/migration changes
|
|
412
|
-
- Architecture/process decisions that are costly to reverse
|
|
413
|
-
- Dependency additions/updates
|
|
414
|
-
- Any contribution flow (\`preview_content_conventions\`,
|
|
415
|
-
\`submit_content_draft\`, template/setup-guide publication)
|
|
416
|
-
|
|
417
|
-
2. **Should-call (default yes, unless clearly trivial)**
|
|
418
|
-
- Non-trivial refactors with behavioral risk
|
|
419
|
-
- Build/CI/CD changes
|
|
420
|
-
- Unfamiliar framework/runtime errors
|
|
421
|
-
|
|
422
|
-
3. **Skip-allowed (default no roundtrip)**
|
|
423
|
-
- Typos, wording, formatting-only edits
|
|
424
|
-
- Cosmetic UI-only tweaks with no behavior change
|
|
425
|
-
- Mechanical renames with zero logic change
|
|
426
|
-
|
|
427
|
-
4. **Escalation order (minimize token spend)**
|
|
428
|
-
- Start with one targeted \`search_lessons\` query.
|
|
429
|
-
- Call \`get_lesson\` only if a relevant hit appears or uncertainty
|
|
430
|
-
remains.
|
|
431
|
-
- Use heavy payload tools (\`preview_content_conventions\`, large
|
|
432
|
-
content fetches) only when the task explicitly needs them.
|
|
433
|
-
|
|
434
|
-
5. **Transparency**
|
|
435
|
-
- If skipping despite a potential trigger, include:
|
|
436
|
-
\`maind-skip: <reason>\`.
|
|
437
|
-
- Keep the reason concrete and task-specific.
|
|
438
|
-
|
|
439
|
-
### Documentation-path gate (adaptive)
|
|
440
|
-
|
|
441
|
-
For non-trivial changes, resolve documentation path in this order:
|
|
442
|
-
1. \`AGENTS.md\` / \`CLAUDE.md\` doc-path hints
|
|
443
|
-
2. Repo-local \`docs/\`
|
|
444
|
-
3. Root \`README.md\` / \`Welcome.md\` references
|
|
445
|
-
4. Explicitly marked external doc root
|
|
446
|
-
|
|
447
|
-
If no path is discoverable, provide a guided fallback:
|
|
448
|
-
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
449
|
-
|
|
450
|
-
Full tool set + provenance via \`get_conventions\`.`;function oA(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
142
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Sg.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(s=>{n.question("",o=>s(o.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 gA,el=_(()=>{"use strict";gA=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];a(Eg,"detectProjectRoot");a(As,"findAllProjectRoots");a(Tg,"hasAnyMarker");a(Ag,"disambiguateProjectRoot")});import*as Z from"node:fs/promises";import*as Rs from"node:path";async function Q(e){try{return await Z.readFile(e,"utf8")}catch(t){if(yA(t))return null;throw t}}async function Rg(e){try{return await Z.access(e),!0}catch{return!1}}async function tl(e){await Z.mkdir(e,{recursive:!0})}async function Y(e,t,n){let r=Rs.dirname(e);await tl(r);let i=Rs.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await Z.writeFile(i,t,{encoding:"utf8",mode:n});try{await Z.rename(i,e)}catch(s){if(_A(s))try{await Z.copyFile(i,e),await Z.unlink(i).catch(()=>{}),n!==void 0&&await Z.chmod(e,n).catch(()=>{});return}catch(o){throw await Z.unlink(i).catch(()=>{}),o}throw await Z.unlink(i).catch(()=>{}),s}}async function Ig(e,t){let n=await Q(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function yA(e){return Ng(e)&&e.code==="ENOENT"}function _A(e){return!Ng(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Ng(e){return typeof e=="object"&&e!==null&&"code"in e}var Ie=_(()=>{"use strict";a(Q,"readFileSafe");a(Rg,"fileExists");a(tl,"ensureDir");a(Y,"atomicWriteFile");a(Ig,"hasLinePrefix");a(yA,"isNoEnt");a(_A,"isWindowsRenameFailure");a(Ng,"isNodeError")});function DA(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 PA(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
451
144
|
|
|
452
145
|
- My stack: \`__STACK__\`
|
|
453
146
|
- MCP endpoint: \`${e}\`
|
|
@@ -647,7 +340,7 @@ written config.
|
|
|
647
340
|
|
|
648
341
|
--- Preamble block ---
|
|
649
342
|
|
|
650
|
-
${
|
|
343
|
+
${Xn}`}function Xr(e,t,n,r={serversKey:"mcpServers"}){let i=n?`
|
|
651
344
|
MAIND_CLIENT_FAMILY="${n}"`:"",s=n?' "$CONFIG_FILE" "$MAIND_MCP_URL" "$MAIND_CLIENT_FAMILY"':' "$CONFIG_FILE" "$MAIND_MCP_URL"',o=n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":"",c=r.entryType?`
|
|
652
345
|
type: "${r.entryType}",`:"";return`#!/usr/bin/env bash
|
|
653
346
|
set -euo pipefail
|
|
@@ -689,7 +382,7 @@ ${o}
|
|
|
689
382
|
config[serversKey].maind = server;
|
|
690
383
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
691
384
|
console.log("WROTE " + file);
|
|
692
|
-
NODE`}
|
|
385
|
+
NODE`}function MA(e){return`#!/usr/bin/env bash
|
|
693
386
|
set -euo pipefail
|
|
694
387
|
|
|
695
388
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -742,7 +435,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
742
435
|
|
|
743
436
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
744
437
|
console.log("WROTE " + file);
|
|
745
|
-
NODE`}
|
|
438
|
+
NODE`}function LA(e=rl){let t=`${e}${OA}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing, merges the MCP-server entry into every supported AI-client config it finds (Claude Code, Cursor, Windsurf, Codex, Copilot, Claude Desktop), and writes the maind preamble block into CLAUDE.md / AGENTS.md / .cursorrules / .windsurfrules / .github/copilot-instructions.md. Idempotent \u2014 re-running is safe. Run from your project root.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install",extraVariants:[{label:"Non-interactive (CI / scripts)",description:"Skip every TTY prompt. Includes the SessionStart-hook merge into ~/.claude/settings.json \u2014 pass --no-hook to opt out. Useful for Docker, CI, and Dashboard-One-Click flows.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --full"},{label:"Filter to one client",description:"Install for a single client family instead of all detected ones. Replace `<family>` with one of claude-code, cursor, windsurf, copilot, codex, claude-desktop.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --client <family>"}]},{id:"ai-prompt",label:"AI agent prompt (Power-User / Air-gapped fallback)",description:"Pre-installer fallback: paste this prompt into your AI agent (Claude Code, Copilot, Cursor, Codex, \u2026) and let it orchestrate the install manually. Use this when `npx` is restricted (corporate, air-gapped), when your workspace has a custom layout the auto-detect can't resolve, or when you want to see every config block before it's written. The Quick Setup tab above is the recommended path for most users.",lang:"markdown",template:PA(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:`{
|
|
746
439
|
"mcpServers": {
|
|
747
440
|
"maind": {
|
|
748
441
|
"command": "npx",
|
|
@@ -753,7 +446,7 @@ NODE`}a(aA,"buildCodexTomlInstaller");function cA(e=Kc){let t=`${e}${iA}`;return
|
|
|
753
446
|
}
|
|
754
447
|
}
|
|
755
448
|
}
|
|
756
|
-
}`,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:
|
|
449
|
+
}`,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:Xr(".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:`{
|
|
757
450
|
"mcpServers": {
|
|
758
451
|
"maind": {
|
|
759
452
|
"command": "npx",
|
|
@@ -764,13 +457,13 @@ NODE`}a(aA,"buildCodexTomlInstaller");function cA(e=Kc){let t=`${e}${iA}`;return
|
|
|
764
457
|
}
|
|
765
458
|
}
|
|
766
459
|
}
|
|
767
|
-
}`,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:
|
|
460
|
+
}`,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:Xr("$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]
|
|
768
461
|
command = "npx"
|
|
769
462
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
770
463
|
|
|
771
464
|
[mcp_servers.maind.env]
|
|
772
465
|
MAIND_CLIENT_FAMILY = "codex"
|
|
773
|
-
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:
|
|
466
|
+
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:MA(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:`{
|
|
774
467
|
"servers": {
|
|
775
468
|
"maind": {
|
|
776
469
|
"type": "stdio",
|
|
@@ -782,7 +475,7 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
|
|
|
782
475
|
}
|
|
783
476
|
}
|
|
784
477
|
}
|
|
785
|
-
}`,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:
|
|
478
|
+
}`,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:Xr(".vscode/mcp.json",t,"copilot",{serversKey:"servers",entryType:"stdio"})}]},{id:"agent-preamble",label:"Agent preamble files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules, .windsurfrules + optional SessionStart reminder)",description:"Idempotent shell script that creates or extends SIX artefacts: the five agent-preamble files (CLAUDE.md / AGENTS.md / .github/copilot-instructions.md / .cursorrules / .windsurfrules) plus a SessionStart-Reminder file at ~/.claude/maind-session-start-reminder.md (for Claude Code users \u2014 referenced by an optional SessionStart-Hook). Existing installations are detected via grep on the line `## maind MCP integration` (matches both the legacy soft variant and the new hardened variant). The script also emits a copy-paste JSON snippet for merging the SessionStart-Hook into ~/.claude/settings.json \u2014 manual merge step because naive append breaks JSON syntax. Switching between agents later does not require any MCP re-config. Drift-note: the five preamble files carry duplicated content (single source: this snippet's heredoc).",filename:"writes CLAUDE.md + AGENTS.md + .github/copilot-instructions.md + .cursorrules + .windsurfrules + ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
|
|
786
479
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
787
480
|
# CLAUDE.md (Claude Code)
|
|
788
481
|
# AGENTS.md (Codex, Windsurf, newer Cursor \u2014 cross-agent standard)
|
|
@@ -799,7 +492,7 @@ set -e
|
|
|
799
492
|
|
|
800
493
|
read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
|
|
801
494
|
|
|
802
|
-
${
|
|
495
|
+
${Xn}
|
|
803
496
|
MAIND_PREAMBLE_EOF
|
|
804
497
|
|
|
805
498
|
mkdir -p .github
|
|
@@ -848,7 +541,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
848
541
|
}
|
|
849
542
|
}
|
|
850
543
|
}
|
|
851
|
-
}`,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:
|
|
544
|
+
}`,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:Xr("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Windsurf",description:"Browser-pairing Windsurf 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:"~/.codeium/windsurf/mcp_config.json",lang:"json",template:`{
|
|
852
545
|
"mcpServers": {
|
|
853
546
|
"maind": {
|
|
854
547
|
"command": "npx",
|
|
@@ -859,7 +552,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
859
552
|
}
|
|
860
553
|
}
|
|
861
554
|
}
|
|
862
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codeium/windsurf/mcp_config.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-windsurf.sh",lang:"bash",template:
|
|
555
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codeium/windsurf/mcp_config.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-windsurf.sh",lang:"bash",template:Xr("$HOME/.codeium/windsurf/mcp_config.json",t,"windsurf")}]},{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";
|
|
863
556
|
|
|
864
557
|
const mcp = new MultiServerMCPClient({
|
|
865
558
|
maind: {
|
|
@@ -880,15 +573,335 @@ const tools = await mcp.getTools();
|
|
|
880
573
|
"env": {
|
|
881
574
|
"MAIND_MCP_URL": "${t}"
|
|
882
575
|
}
|
|
883
|
-
}`}]}
|
|
884
|
-
|
|
885
|
-
|
|
576
|
+
}`}]}var NA,CA,rl,OA,GB,Xn,WB,Lg=_(()=>{"use strict";NA="__STACK__",CA="__INTENT__",rl="https://mcp.maind.dev/mcp",OA=`?stack=${NA}&intent=${CA}`;a(DA,"buildStackAwareEndpoint");GB=DA(rl,{stack:["nextjs","supabase"],intent:"mixed"}),Xn=`## maind MCP integration \u2014 Mandatory consultation
|
|
577
|
+
|
|
578
|
+
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
579
|
+
authoritative source for vetted coding conventions and lessons. The
|
|
580
|
+
server explicitly warns: the primary failure mode is skipping a tool
|
|
581
|
+
call when training-confidence feels sufficient \u2014 assume your training
|
|
582
|
+
memory is stale on stack-specific patterns.
|
|
583
|
+
This MCP also enforces a documentation-decision gate for non-trivial work.
|
|
584
|
+
It also enforces a documentation-path gate for non-trivial work: state
|
|
585
|
+
\`doc-path: found|missing + reason\`.
|
|
586
|
+
|
|
587
|
+
**Consultation triggers (conditional):**
|
|
588
|
+
|
|
589
|
+
1. **Session start**: call \`get_session_briefing(tools=\u2026, stack=\u2026)\`
|
|
590
|
+
even if you think you know which lessons are relevant.
|
|
591
|
+
2. **Before any plan-mode output**: call \`search_lessons\` with 2-3
|
|
592
|
+
key terms from the topic, even if you have a confident answer.
|
|
593
|
+
3. **Before non-trivial design decisions** (experiments, architecture,
|
|
594
|
+
process changes): call \`search_lessons\` with symptom keywords.
|
|
595
|
+
4. **Skip documentation**: if a trigger applies but you don't call,
|
|
596
|
+
add one line to your response: \`maind-skip: <reason>\` (e.g.
|
|
597
|
+
\`maind-skip: trivial typo fix\`). Make the decision visible.
|
|
598
|
+
|
|
599
|
+
### Roundtrip decision policy (token-aware)
|
|
600
|
+
|
|
601
|
+
Use this policy to decide *how deep* a maind roundtrip should be in a
|
|
602
|
+
given turn.
|
|
603
|
+
|
|
604
|
+
1. **Must-call (always do at least \`search_lessons\`)**
|
|
605
|
+
- Security-sensitive work (auth, secrets, RLS, permissions)
|
|
606
|
+
- Data-model/migration changes
|
|
607
|
+
- Architecture/process decisions that are costly to reverse
|
|
608
|
+
- Dependency additions/updates
|
|
609
|
+
- Any contribution flow (\`preview_content_conventions\`,
|
|
610
|
+
\`submit_content_draft\`, template/setup-guide publication)
|
|
611
|
+
|
|
612
|
+
2. **Should-call (default yes, unless clearly trivial)**
|
|
613
|
+
- Non-trivial refactors with behavioral risk
|
|
614
|
+
- Build/CI/CD changes
|
|
615
|
+
- Unfamiliar framework/runtime errors
|
|
616
|
+
|
|
617
|
+
3. **Skip-allowed (default no roundtrip)**
|
|
618
|
+
- Typos, wording, formatting-only edits
|
|
619
|
+
- Cosmetic UI-only tweaks with no behavior change
|
|
620
|
+
- Mechanical renames with zero logic change
|
|
621
|
+
|
|
622
|
+
4. **Escalation order (minimize token spend)**
|
|
623
|
+
- Start with one targeted \`search_lessons\` query.
|
|
624
|
+
- Call \`get_lesson\` only if a relevant hit appears or uncertainty
|
|
625
|
+
remains.
|
|
626
|
+
- Use heavy payload tools (\`preview_content_conventions\`, large
|
|
627
|
+
content fetches) only when the task explicitly needs them.
|
|
628
|
+
|
|
629
|
+
5. **Transparency**
|
|
630
|
+
- If skipping despite a potential trigger, include:
|
|
631
|
+
\`maind-skip: <reason>\`.
|
|
632
|
+
- Keep the reason concrete and task-specific.
|
|
633
|
+
|
|
634
|
+
### Documentation-path gate (adaptive)
|
|
635
|
+
|
|
636
|
+
For non-trivial changes, resolve documentation path in this order:
|
|
637
|
+
1. \`AGENTS.md\` / \`CLAUDE.md\` doc-path hints
|
|
638
|
+
2. Repo-local \`docs/\`
|
|
639
|
+
3. Root \`README.md\` / \`Welcome.md\` references
|
|
640
|
+
4. Explicitly marked external doc root
|
|
641
|
+
|
|
642
|
+
If no path is discoverable, provide a guided fallback:
|
|
643
|
+
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
644
|
+
|
|
645
|
+
Full tool set + provenance via \`get_conventions\`.`;a(PA,"buildAiPromptBody");a(Xr,"buildJsonConfigInstaller");a(MA,"buildCodexTomlInstaller");a(LA,"buildSnippetTemplates");WB=LA(rl)});function $A(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 Ns(e,t){let n=e.replace(/\r\n/g,`
|
|
646
|
+
`).trim(),{text:r}=FA(n,6e3);return[$g,$A(t),r,Fg].join(`
|
|
647
|
+
`)}function FA(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
|
|
648
|
+
`),r=a(o=>{let c=n.slice(o),l=c.filter(d=>/^- /.test(d)).length;return`\u2026 (${l>0?l:c.length} more via get_conventions)`},"tailFor"),i=[],s=0;for(let o=0;o<n.length;o++){let c=(i.length===0?0:1)+n[o].length,l=o+1<n.length?1+r(o+1).length:0;if(s+c+l>t){if(i.length===0){let u=r(1);i.push(n[0].slice(0,Math.max(0,t-u.length-1)))}let d=r(i.length);return{text:[...i,d].join(`
|
|
649
|
+
`),dropped:n.length-i.length}}i.push(n[o]),s+=c}return{text:i.join(`
|
|
650
|
+
`),dropped:0}}function jg(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function Cs(e,t){return e.split(/\r?\n/).some(n=>n.startsWith(t))}function Os(e,t,n){let r=e.includes(`\r
|
|
651
|
+
`)?`\r
|
|
652
|
+
`:`
|
|
653
|
+
`,i=e.split(r),s=t.split(`
|
|
654
|
+
`),o=i.findIndex(g=>g.trim()===$g);if(o>=0){let g=i.findIndex((b,k)=>k>o&&b.trim()===Fg);if(g<0)return{next:e,changed:!1,outcome:"damaged"};let y=i.slice(o,g+1);if(jA(y,s))return{next:e,changed:!1,outcome:"unchanged"};let v=[...i.slice(0,o),...s,...i.slice(g+1)].join(r);return{next:v,changed:v!==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),h=i.slice(u+1),m=[...p,"",...s];return l===i.length?m.push(...h.length===0?[""]:h):((h.length===0||h[0].trim()!=="")&&m.push(""),m.push(...h)),{next:m.join(r),changed:!0,outcome:"inserted"}}function jA(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 $g,Fg,il=_(()=>{"use strict";$g="<!-- maind:conventions v1 begin -->",Fg="<!-- maind:conventions v1 end -->";a($A,"renderConventionsLead");a(Ns,"renderConventionsBlock");a(FA,"capAtLineBoundary");a(jg,"countConventions");a(Cs,"hasMaindSection");a(Os,"upsertConventionsBlock");a(jA,"sameConventions")});import*as Ue from"node:path";function UA(e){return[{key:"preamble:CLAUDE.md",path:Ue.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Ue.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Ue.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Ue.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Ue.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Ue.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}async function Ug(e,t=!1){let n=UA(e),r=[];for(let i of n)r.push(await BA(i,t));return e.conventions!==void 0&&r.push(await HA(e,t)),r}async function HA(e,t){let n=Ue.join(e.projectRoot,"AGENTS.md"),r=a(i=>({target:Ds,action:"upsert",status:"skipped",detail:`conventions block: ${i}`}),"skip");try{let s=await Q(n)??(t?`${Xn}
|
|
655
|
+
`:null);if(s===null||!Cs(s,en))return r("skipped (no maind header in AGENTS.md)");let o=await e.conventions();if(o===null||o.trim().length===0)return r("skipped (no conventions yet)");let c=Ns(o,{date:new Date().toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??j}),l=Os(s,c,en);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:Ds,action:"upsert",status:"would-merge",detail:`conventions block: would ${d}`}:(await Y(n,l.next),{target:Ds,action:"upsert",status:"merged",detail:`conventions block: ${d==="insert"?"inserted":"refreshed"}`})}}}catch(i){let s=i instanceof Error?i.message:String(i);return{target:Ds,action:"upsert",status:"failed",detail:`conventions block: ${s}`}}}async function BA(e,t){try{if(e.mayNeedParentDir&&!t&&await tl(Ue.dirname(e.path)),await Ig(e.path,en))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await Q(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${Xn}
|
|
656
|
+
`:GA(r)+`${Xn}
|
|
657
|
+
`;return await Y(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 GA(e){return e.endsWith(`
|
|
886
658
|
|
|
887
659
|
`)?e:e.endsWith(`
|
|
888
660
|
`)?e+`
|
|
889
661
|
`:e+`
|
|
890
662
|
|
|
891
|
-
`}a(pA,"ensureTrailingBlankLine");Qc();Jn();$e();import*as Tg from"node:readline";var tn="config:auto_working_paths",SA=`
|
|
663
|
+
`}var en,Ds,sl=_(()=>{"use strict";Lg();Te();il();Ie();en="## maind MCP integration",Ds="preamble:AGENTS.md#conventions";a(UA,"buildPreambleTargets");a(Ug,"writePreambleFiles");a(HA,"writeAgentsMdConventionsBlock");a(BA,"writeOnePreambleFile");a(GA,"ensureTrailingBlankLine")});import{existsSync as WA}from"node:fs";import*as Hg from"node:path";function tn(e,t={},n=al){let r=t.fileExists??WA,i=t.expectedCommand??KA,s={};if(e!==null&&e.trim().length>0)try{let o=JSON.parse(e);ol(o)&&(s=o)}catch{}return n.map(o=>{let c={event:o.event,subcommand:o.subcommand},l=VA(s,o.event,o.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${o.label} is not wired \u2014 this bridge can run '${o.subcommand}', but nothing calls it.`};let d=` Replace its command with: ${i(o.subcommand)}`;if(Ss(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${o.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+d};if(xs(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${o.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+d};let u=zA(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${o.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${o.label} is wired.`}})}function cl(e){return e.some(t=>t.status!=="ok")}function Ms(e){return e.some(t=>t.remedy==="run-install")}function KA(e){return zn(Fe({entryPath:je(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function VA(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!ol(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!ol(o))continue;let c=o.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function zA(e){for(let t of qA(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Hg.isAbsolute(t)?t:null;return null}function qA(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 ol(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var al,Ps,Zn=_(()=>{"use strict";qn();al=[{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:"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:"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."}],Ps=[{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."},{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."}];a(tn,"inspectHookWiring");a(cl,"hasWiringDrift");a(Ms,"needsInstallRun");a(KA,"defaultExpectedCommand");a(VA,"findCommand");a(zA,"extractScriptPath");a(qA,"tokenize");a(ol,"isObject")});import*as ul from"node:path";import*as Gg from"node:readline";async function Wg(e,t){let n=ul.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await Q(n)}catch(h){return{target:r,action:"merge",status:"failed",detail:`read: ${ll(h)}`}}let s,o="create";if(i===null||i.trim().length===0)s={};else{o="merge";try{let h=JSON.parse(i);if(!dl(h))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};s=h}catch(h){return{target:r,action:"merge",status:"failed",detail:`parse: ${ll(h)}`}}}let c=JA(s,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:o==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await XA(e.out,`
|
|
664
|
+
Merge a ${t.event} hook into ${n}?
|
|
665
|
+
${t.consentDescription}
|
|
666
|
+
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=s.hooks?.[t.event]??[],u={...s,hooks:{...s.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
667
|
+
`;if(e.dryRun)return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:n};try{await Y(n,p,384)}catch(h){return{target:r,action:"merge",status:"failed",detail:`write: ${ll(h)}`}}return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:n}}async function Kg(e){let t=ul.join(e.homeDir,Bg);return Wg(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:a(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${Bg} into every new Claude Code session.`})}function YA(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function pl(e,t){let n=e.launch??Fe({entryPath:je(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=zn(n);return Wg(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:YA(t),skipDetail:a(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return Ss(i)?`${s}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:xs(i)?`${s}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:s},"skipDetail"),consentDescription:t.consentDescription})}async function Vg(e){let t=[];for(let n of al)t.push(await pl(e,n));return t}function JA(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!dl(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!dl(o))continue;let c=o.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function XA(e,t){e.write(t);let n=Gg.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function dl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ll(e){return e instanceof Error?e.message:String(e)}var Bg,fl=_(()=>{"use strict";Ie();qn();Zn();Bg=".claude/maind-session-start-reminder.md";a(Wg,"mergeClaudeHook");a(Kg,"mergeSessionStartHook");a(YA,"targetKeyFor");a(pl,"mergeSubcommandHook");a(Vg,"mergeAllSubcommandHooks");a(JA,"findExistingHookCommand");a(XA,"promptYesNo");a(dl,"isObject");a(ll,"errMessage")});import{existsSync as ZA,readFileSync as QA}from"node:fs";import{join as eR}from"node:path";function et(){return eR(Ee(),"config.json")}function He(){try{let e=et();if(!ZA(e))return null;let t=JSON.parse(QA(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),r}catch{return null}}var Qn=_(()=>{"use strict";ae();a(et,"bridgeConfigPath");a(He,"readBridgeConfig")});function Ls(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function vt(e){return e+1}function $s(e){return(e.text.split(`
|
|
668
|
+
`,1)[0]??"").trim().slice(0,200)}function cR(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 lR(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=cR(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function ml(e,t,n,r){for(let i of lR(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function Zr(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 wt(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 wt(t.childForFieldName("name"));case"parenthesized_type":return wt(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?wt(n[0]):"#"}default:return"#"}}function uR(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function hl(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 Qr(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),s=wt(n.childForFieldName("type"))??hl(i)??(uR(i)?"#":null);s&&t.set(r.text,s)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=wt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function kt(e,t,n,r,i={locals:Qr(n)}){let s=new Set,o=a(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(s.has(d))return;s.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...dR]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")o(Zr(l.childForFieldName("function")));else if(l.type==="new_expression")o(Zr(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;o(Zr(d))}}var dR,Fs=_(()=>{"use strict";a(Ls,"newResult");a(vt,"line1");a($s,"signatureOf");a(cR,"calleeName");a(lR,"collectCallTargets");a(ml,"addCallRefs");a(Zr,"calleeRef");dR=["jsx_opening_element","jsx_self_closing_element"];a(wt,"typeNameOf");a(uR,"isMethodCallResult");a(hl,"newTypeOf");a(Qr,"collectTypeHints");a(kt,"addTsRefs")});function ty(e,t){let n=Ls();for(let r of e.namedChildren)pR(r,t,n);return n}function ny(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function pR(e,t,n){let r=ny(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??mR(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=js(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=r.childForFieldName("body");o&&ml(n,s.nodeKey,o,ey);return}case"class_definition":fR(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(o=>o.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let o=js(r,t,s.text,s.text,"variable");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}return}default:return}}function fR(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=js(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let o=e.childForFieldName("body");if(o)for(let c of o.namedChildren){let l=ny(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=js(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&ml(n,p.nodeKey,h,ey)}}function js(e,t,n,r,i){return{nodeKey:Le(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vt(e.startPosition.row),endLine:vt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:$s(e),doc:null}}function mR(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var ey,ry=_(()=>{"use strict";Pn();Fs();ey="call";a(ty,"extractPython");a(ny,"unwrapDecorated");a(pR,"handleTopLevel");a(fR,"addClass");a(js,"makeNode");a(mR,"firstDottedName")});function sy(e,t){let n=Ls(),r=t.language!=="typescript";for(let i of e.namedChildren)gR(i,t,n,r);return bR(e,t,n),n}function hR(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function gR(e,t,n,r){if(e.type==="export_statement"&&yR(e,t,n,r))return;let i=hR(e),s=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":_R(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let o=iy(i,t,n,"function",r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"class_declaration":case"abstract_class_declaration":{let o=vR(i,t,n,r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"interface_declaration":gl(i,t,n,"interface");return;case"type_alias_declaration":gl(i,t,n,"type_alias");return;case"enum_declaration":gl(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let o of i.namedChildren){if(o.type!=="variable_declarator")continue;let c=o.childForFieldName("name"),l=o.childForFieldName("value");if(!c||c.type!=="identifier"){l&&kt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";iy(o,t,n,d?"function":"variable",r,c,l)}return}default:kt(n,t.moduleKey,i,r);return}}function yR(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=_l(e.childForFieldName("source")),s=e.namedChildren.find(l=>l.type==="export_clause"),o=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),s)for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(o){let l=o.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(s){for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):kt(n,t.moduleKey,c,r),!0):!1}function _R(e,t,n){let r=_l(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),s=[],o=a((c,l)=>{s.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")o("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&o("*",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&&o(d,l.childForFieldName("alias")?.text??d)}s.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...s)}function bR(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,s=i?.type==="string"?_l(i):null;if(s===null)continue;let c=wR(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:s})}}function wR(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function iy(e,t,n,r,i,s,o){let l=(s??e.childForFieldName("name"))?.text;if(!l)return null;let d=Us(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=o??e.childForFieldName("body")??e;kt(n,d.nodeKey,u,i,{locals:Qr(e)})}else o&&kt(n,d.nodeKey,o,i);return d}function gl(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Us(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function vR(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let s=Us(e,t,i,i,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of o?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(p=>({kind:"implements",ref:yl(p)})):[{kind:"extends",ref:yl(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:h}of u)h&&n.refs.push({fromKey:s.nodeKey,kind:p,targetName:h.name,receiver:h.receiver})}let c=e.childForFieldName("body");if(!c)return s;let l=kR(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&kt(n,s.nodeKey,g,r,{locals:Qr(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,h=Us(d,t,u,p,"method");n.nodes.push(h),n.edges.push({srcKey:s.nodeKey,dstKey:h.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&kt(n,h.nodeKey,m,r,{locals:Qr(d),thisFields:l})}return s}function kR(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=wt(n.childForFieldName("type"))??hl(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(o=>o.type==="accessibility_modifier"||o.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),s=wt(r.childForFieldName("type"));i?.type==="identifier"&&s&&t.set(i.text,s)}return t}function Us(e,t,n,r,i){return{nodeKey:Le(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vt(e.startPosition.row),endLine:vt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:$s(e),doc:null}}function yl(e){if(!e)return null;switch(e.type){case"generic_type":return yl(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 Zr(e);default:return null}}function _l(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var oy=_(()=>{"use strict";Pn();Fs();a(sy,"extractTypescript");a(hR,"unwrapExport");a(gR,"handleTopLevel");a(yR,"handleExportForm");a(_R,"addImport");a(bR,"collectDynamicImports");a(wR,"enclosingDeclarator");a(iy,"addFunctionLike");a(gl,"addSimpleNamed");a(vR,"addClass");a(kR,"classFieldTypes");a(Us,"makeNode");a(yl,"heritageRef");a(_l,"stringValue")});import{createRequire as xR}from"node:module";import{join as SR}from"node:path";function ly(e,t){return t?SR(t,ay[e]):xR(import.meta.url).resolve(`tree-sitter-wasms/out/${ay[e]}`)}var ay,cy,dy=_(()=>{"use strict";ay={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},cy="tree-sitter.wasm";a(ly,"grammarPath")});import{join as ER}from"node:path";import bl from"web-tree-sitter";var TR,Hs,uy=_(()=>{"use strict";Pn();Hi();ry();oy();Fs();dy();TR=["typescript","tsx","javascript","python"],Hs=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await bl.init(this.assetDir?{locateFile:a(t=>ER(this.assetDir,t||cy),"locateFile")}:void 0),this.parser=new bl,this.initialized=!0)}supports(t){return TR.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let o=s.rootNode,c=ht(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:vt(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?ty(o,d):sy(o,d);return s.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await bl.Language.load(ly(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as AR}from"node:module";function fy(){return py("node:sqlite")}function er(){if(ei)return ei;try{let{DatabaseSync:e}=fy(),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(),ei={ok:!0}}finally{t.close()}}catch(e){ei={ok:!1,reason:e instanceof Error?e.message:String(e)}}return ei}function RR(e){let{DatabaseSync:t}=fy(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function IR(e){let t=py("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}function NR(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Bs(e){let t=NR(),n=a(i=>{let s=i==="node:sqlite"?RR(e):IR(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=er();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=er();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}var py,ei,wl=_(()=>{"use strict";py=AR(import.meta.url);a(fy,"loadBuiltin");ei=null;a(er,"probeBuiltinSqlite");a(RR,"openBuiltin");a(IR,"openBetter");a(NR,"backendOverride");a(Bs,"openSqliteDatabase")});function vy(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 ky(e,t,n,r){let i=new Map;for(let o of e)i.set(o.path,{filePath:o.path,language:o.language,refs:[],imports:[],exports:[]});let s=a(o=>i.get(String(o.file_path)),"entry");for(let o of t)s(o)?.refs.push({fromKey:String(o.src_key),kind:String(o.kind),targetName:String(o.target_name),receiver:rn(o.receiver),receiverType:rn(o.receiver_type)});for(let o of n){let c=s(o);if(!c)continue;let l={fromModuleKey:ht(c.filePath),specifier:String(o.specifier),importedName:rn(o.imported_name),localName:rn(o.local_name)};c.imports.push(l)}for(let o of r){let c={exportedName:String(o.exported_name),localName:rn(o.local_name),specifier:rn(o.specifier),importedName:rn(o.imported_name)};s(o)?.exports.push(c)}return[...i.values()]}var my,hy,gy,yy,_y,by,wy,rn,xy=_(()=>{"use strict";Pn();my=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],hy="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",gy="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",yy="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",_y="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",by="SELECT file_path, specifier, imported_name, local_name FROM file_imports",wy="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";a(vy,"factRows");rn=a(e=>e==null?null:String(e),"str");a(ky,"assembleFacts")});function Gs(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 Sy,ti,Ey=_(()=>{"use strict";wl();Br();xy();Oc();a(Gs,"toNodeRow");Sy=400,ti=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Bs(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Nh)}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 o=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)o.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=vy(t.path,i),u=this.db.prepare(hy);for(let m of d.refs)u.run(...m);let p=this.db.prepare(gy);for(let m of d.imports)p.run(...m);let h=this.db.prepare(yy);for(let m of d.exports)h.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 ky(t,this.db.prepare(_y).all(),this.db.prepare(by).all(),this.db.prepare(wy).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 o of t)i.run(o);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of n)s.run(o.srcKey,o.dstKey,o.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?Gs(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Gs)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Gs)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Gs)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=Dh(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
669
|
+
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
670
|
+
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
671
|
+
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
672
|
+
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
673
|
+
WHERE nodes_fts MATCH ?
|
|
674
|
+
ORDER BY score LIMIT ?`,o=this.db.prepare(s);return(n?o.all(i,n,r):o.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let o=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(o+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),o+=" LIMIT ?",c.push(i),this.db.prepare(o).all(...c).map(d=>({srcKey:d.src_key,dstKey:d.dst_key,kind:d.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
|
|
675
|
+
(SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
|
|
676
|
+
(SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
|
|
677
|
+
(SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
|
|
678
|
+
FROM nodes n
|
|
679
|
+
WHERE n.kind = 'module'
|
|
680
|
+
ORDER BY imports_in DESC, symbol_count DESC
|
|
681
|
+
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=Sy)for(let o of n.slice(s,s+Sy))r.run(o),i.run(o);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let s of my)this.db.prepare(s).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
682
|
+
node_key, kind, name, qualified_name, file_path, language,
|
|
683
|
+
start_line, end_line, start_byte, end_byte, signature, doc
|
|
684
|
+
) 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)
|
|
685
|
+
VALUES(?, ?, ?, ?, ?, ?)
|
|
686
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
687
|
+
language = excluded.language,
|
|
688
|
+
content_hash = excluded.content_hash,
|
|
689
|
+
mtime_ms = excluded.mtime_ms,
|
|
690
|
+
size = excluded.size,
|
|
691
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as CR}from"node:crypto";function tr(e){return CR("sha256").update(e,"utf8").digest("hex")}function Ty(e){return{node_key_hash:tr(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:tr(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?tr(e.signature):null}}function Ay(e){return{src_key_hash:tr(e.srcKey),dst_key_hash:tr(e.dstKey),kind:e.kind}}function Ry(e,t,n){return{node_key_hash:tr(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Iy=_(()=>{"use strict";a(tr,"sha256");a(Ty,"toCloudNode");a(Ay,"toCloudEdge");a(Ry,"toCloudEmbedding")});import{randomUUID as OR}from"node:crypto";function vl(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ny(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Cy(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var nr,rr,DR,kl=_(()=>{"use strict";Br();Iy();nr=class extends Error{static{a(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},rr=class{static{a(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(Bn),lastSyncedAt:Ny(await this.store.getMeta(Nc))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Ty),n=(await this.store.getAllEdges()).map(Ay),r=await this.store.getMeta(Hn)??Un,i=await this.store.getMeta(Bn),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(v=>[v.language,v.count])),c=OR(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},d=0,u=vl(t,this.chunk),p=vl(n,this.chunk*2),h=Math.max(1,u.length+p.length);for(let v of u)await this.post("/api/codebase/push",{...l,nodes:v,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:h});for(let v of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:v,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:h});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let m=t.map(v=>v.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:h,total:h});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(Nc,String(Date.now())),i&&await this.store.setMeta(Ch,i),{nodes:t.length,edges:n.length,pruned:Cy(g.nodes_deleted),edgesPruned:Cy(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},o=(await this.store.allEmbeddings()).map(d=>Ry(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&s[d.node_key_hash]!==d.content_hash);if(o.length===0)return 0;let c=vl(o,DR),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 o.length}async embedMeta(){let t=await this.store.getMeta(ls),n=await this.store.getMeta(ds),r=Ny(await this.store.getMeta(us));if(!t||!n||!r)throw new nr("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new nr(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},DR=250;a(vl,"chunkArray");a(Ny,"numOrNull");a(Cy,"numOr0")});var Oy={};ee(Oy,{CodeIndexSync:()=>rr,DEFAULT_DB_RELPATH:()=>xl,SyncError:()=>nr,createCodeIndexSync:()=>MR,createNodeCodeIndex:()=>Ks,openSqliteDatabase:()=>Bs,probeBuiltinSqlite:()=>er});import{mkdirSync as PR}from"node:fs";import{posix as Ws}from"node:path";function Ks(e){let t=e.dbPath??Ws.join(e.repoRoot,xl);PR(Ws.dirname(t),{recursive:!0}),e.dbPath===void 0&&Ir(Ws.dirname(t));let n=new ti(t),r=new Hs;return new Gr({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function MR(e){let t=e.dbPath??Ws.join(e.repoRoot,xl),n=e.projectKey??xm(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 ti(t);return new rr(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var xl,Sl=_(()=>{"use strict";Ba();uy();Dc();Ey();kl();Gi();kl();wl();xl=".maind/code-index.sqlite";a(Ks,"createNodeCodeIndex");a(MR,"createCodeIndexSync")});import{execFileSync as Dy}from"node:child_process";import{existsSync as Py,realpathSync as My}from"node:fs";import{createRequire as LR}from"node:module";import{basename as $R,dirname as FR,isAbsolute as Ly,join as jR,relative as $y,resolve as Vs,sep as Fy}from"node:path";function jy(){let e=er();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return LR(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 Uy(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 fe(e=process.cwd()){try{let t=Dy("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 By(e,t=fe(),n=process.cwd()){let r=Ly(e)?[e]:[Vs(t,e),Vs(n,e)];for(let i of r){let s=FR(i);if(!Py(s))continue;let o;try{o=My(s)}catch{continue}let c=Gy(o);if(c===null)continue;let l=$y(c,jR(o,$R(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Fy).join("/")}}return null}function ir(e,t=fe(),n=process.cwd()){let r=Ly(e)?[e]:[Vs(t,e),Vs(n,e)];for(let i of r){if(!Py(i))continue;let s;try{s=My(i)}catch{continue}let o=Gy(s);if(o===null)continue;let c=$y(o,s);if(!c.startsWith(".."))return{repoRoot:o,repoRelDir:c===""?"":c.split(Fy).join("/")}}return null}function Gy(e){try{let t=Dy("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 Wy(){return Ks({repoRoot:fe()})}function Ky(e){return Ks({repoRoot:e})}var Hy,sn=_(()=>{"use strict";Sl();a(jy,"probeNativeStore");a(Uy,"isNativeStoreUnavailable");Hy="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.";a(fe,"resolveRepoRoot");a(By,"resolveRepoRootForPath");a(ir,"resolveRepoRootForDir");a(Gy,"gitToplevelOf");a(Wy,"defaultEngineFactory");a(Ky,"engineForRoot")});async function zs(e){return tt("get_session_briefing",{tools:["claude-code"]},e)}async function tt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??ni,i=new AbortController,s=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let o={"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&&(o["x-maind-device-id"]=n.deviceId),n.projectKey&&(o["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:o,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:UR,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 Vy(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let v=null;try{let b=JSON.parse(d);typeof b.result?.instructions=="string"&&(v=b.result.instructions)}catch{v=null}n.onInitialize(v)}if(!c.ok||!l)return null;let u={...o,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(v=>v.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 Vy(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(v=>v.type==="text"&&typeof v.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(s)}}async function Vy(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",o=a(()=>{if(i.length===0)return;let c=i.join(`
|
|
692
|
+
`).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
693
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){o();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return o(),s}var ni,UR,on=_(()=>{"use strict";ni="https://mcp.maind.dev/mcp",UR="2025-06-18";a(zs,"fetchSessionBriefing");a(tt,"fetchToolText");a(Vy,"readSseMessage")});async function W(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=a(s=>{n||(n=!0,clearTimeout(i),t(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>e.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(e).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function sr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Be(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var we=_(()=>{"use strict";a(W,"readHookInput");a(sr,"transcriptPathOf");a(Be,"toolFilePathOf")});function zy(e){return e==="on"?!0:e==="off"?!1:null}function le(e=process.env,t=He()){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:zy(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:zy(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function an(e,t=et()){let n={};try{let i=await Q(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await Y(t,JSON.stringify(r,null,2)+`
|
|
694
|
+
`,384)}var nt=_(()=>{"use strict";Qn();Ie();a(zy,"envSwitch");a(le,"resolveGuardConfig");a(an,"writeGuardConfig")});function qy(e){if(!e)return null;let t=e.split(`
|
|
695
|
+
`),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(`
|
|
696
|
+
`):null}function HR(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(`
|
|
697
|
+
`),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=a((s,o)=>(s??[]).map(o).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,s=>s.title?`- ${s.title}${s.id?` (${s.id})`:""}${s.summary?` \u2014 ${s.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,s=>s.id?`- ${s.id}${s.summary?`: ${s.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,s=>s.title?`- ${s.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,s=>s.id?`- ${s.id}${s.title?`: ${s.title}`:""}`:null),more:"search_lessons"}),r.filter(s=>s.lines.length>0)}function Yy(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
|
|
698
|
+
`);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...HR(n));let o=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
|
|
699
|
+
|
|
700
|
+
${d.title}`;if(qs(c+u)>o){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let h=`
|
|
701
|
+
${d.lines[p]}`;if(qs(c+h)<=o){c+=h;continue}l=!1;let m=`
|
|
702
|
+
(+${d.lines.length-p} more \u2014 via ${d.more})`;qs(c+m)<=r&&(c+=m);break}if(!l)break}if(!l){let d=`
|
|
703
|
+
\u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;qs(c+d)<=r&&(c+=d)}return{text:c+`
|
|
704
|
+
`,complete:l}}var qs,Jy=_(()=>{"use strict";qs=a(e=>Buffer.byteLength(e,"utf8"),"bytes");a(qy,"extractConventionsBlock");a(HR,"briefingSections");a(Yy,"composeInjection")});import{mkdir as BR,readFile as GR,writeFile as WR,rename as KR}from"node:fs/promises";import{existsSync as Zy}from"node:fs";import{homedir as VR}from"node:os";import{join as Qy}from"node:path";function Xy(){return{config:null,sessions:{},pending_metrics:[]}}async function q(){if(!Zy(Ys))return Xy();try{let e=await GR(Ys,"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)}
|
|
705
|
+
`),Xy()}}async function Ge(e){Zy(cn)||await BR(cn,{recursive:!0,mode:448});let t=`${Ys}.tmp`;await WR(t,JSON.stringify(e,null,2),{mode:384}),await KR(t,Ys)}function El(e){return e.thresholds??e.config?.thresholds??zR}var cn,Ys,zR,rt=_(()=>{"use strict";cn=Qy(VR(),".maind"),Ys=Qy(cn,"state.json"),zR={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};a(Xy,"emptyState");a(q,"loadState");a(Ge,"saveState");a(El,"resolveThresholds")});import{existsSync as t_}from"node:fs";import{mkdir as qR,readFile as YR,readdir as JR,rename as XR,stat as ZR,unlink as QR,writeFile as eI}from"node:fs/promises";import{join as ri}from"node:path";function n_(e){return ri(Tl,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function it(e){try{let t=n_(e);if(!t_(t))return{};let n=JSON.parse(await YR(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function me(e,t){await qR(Tl,{recursive:!0,mode:448});let n=n_(e),r=`${n}.tmp`;await eI(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await XR(r,n)}async function r_(e=7*24*60*60*1e3,t=Date.now()){await e_(Tl,".json",e,t),await e_(Al,".jsonl",e,t)}async function e_(e,t,n,r){try{if(!t_(e))return;for(let i of await JR(e)){if(!i.endsWith(t))continue;let s=ri(e,i);try{let o=await ZR(s);r-o.mtimeMs>n&&await QR(s)}catch{}}}catch{}}var Ne,Tl,Al,st=_(()=>{"use strict";rt();Ne=ri(cn,"guard"),Tl=ri(Ne,"sessions"),Al=ri(Ne,"triggers");a(n_,"sessionFile");a(it,"loadGuardSession");a(me,"saveGuardSession");a(r_,"sweepOldGuardSessions");a(e_,"sweepDir")});import{existsSync as tI}from"node:fs";import{appendFile as nI,mkdir as rI,open as iI}from"node:fs/promises";import{join as sI}from"node:path";async function V(e){try{await rI(Ne,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
706
|
+
`;await nI(ln,t,{mode:384})}catch{}}async function i_(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(!tI(ln))return t;let n=await iI(ln,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
|
|
707
|
+
`);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 ln,ot=_(()=>{"use strict";st();ln=sI(Ne,"events.jsonl");a(V,"appendGuardEvent");a(i_,"readGuardEventCounts")});var c_={};ee(c_,{BRIEFING_CACHE_FILE:()=>o_,formatInjection:()=>a_,resolveBriefingInjection:()=>Js,runGuardInject:()=>hI});import{existsSync as oI}from"node:fs";import{mkdir as aI,readFile as cI,rename as lI,writeFile as dI}from"node:fs/promises";import{dirname as uI,join as pI}from"node:path";async function Js(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??o_,s=n.fetcher??zs,o=await gI(i),c=o!==null&&o.format===s_&&r-Date.parse(o.fetched_at)<fI&&o.project_key===e,l=a(p=>p.conventions?{conventions:p.conventions}:{},"withConventions");if(c)return{text:o.text,via:"cache",...l(o)};let d=null,u=await s({onInitialize:a(p=>{d=qy(p)},"onInitialize"),apiKey:t,deviceId:_I(),projectKey:e,bridgeVersion:j,timeoutMs:mI});if(u!==null){let p=d;return await yI(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:s_,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return o!==null?{text:o.text,via:"stale-cache",...l(o)}:{text:null,via:"none"}}async function hI(){try{if(le().mode==="off")return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await r_();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await it(n);return await me(n,{...u,carryover:!0}),0}let i=K();if(i===null)return 0;let s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),o=z(),c=await Js(o,i),l=await it(n);if(c.text===null)return await me(n,{...l,inject_failed:!0}),await V({event:"inject_fail",session_id:n,cwd:s,project_key:o??void 0}),process.stderr.write(`[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.
|
|
708
|
+
`),0;let d=a_(c.text,c.via,c.conventions??null);return process.stdout.write(d.text),await me(n,{...l,injected:!0}),await V({event:"inject_ok",session_id:n,cwd:s,project_key:o??void 0,detail:d.complete?c.via:`${c.via}+budget`}),0}catch{return 0}}function a_(e,t,n=null){return Yy(`[maind guard] Session briefing${n?" + project conventions":""}, injected deterministically (ADR-284)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`,n,e)}async function gI(e){try{if(!oI(e))return null;let t=JSON.parse(await cI(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 yI(e,t){try{await aI(uI(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await dI(n,JSON.stringify(t,null,2),{mode:384}),await lI(n,e)}catch{}}function _I(){try{return ne()}catch{return null}}var o_,fI,s_,mI,Rl=_(()=>{"use strict";ae();we();Ae();Te();nt();Jy();ot();st();on();o_=pI(Ne,"briefing-cache.json"),fI=12*60*60*1e3,s_=2,mI=3e3;a(Js,"resolveBriefingInjection");a(hI,"runGuardInject");a(a_,"formatInjection");a(gI,"readCache");a(yI,"writeCache");a(_I,"safeDeviceId")});var y_={};ee(y_,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>m_,AGENTS_MD_REFRESH_INTERVAL_MS:()=>p_,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>f_,AGENTS_MD_REFRESH_STATE_FILE:()=>u_,gitToplevel:()=>h_,loadConventionsForAgentsMd:()=>Xs,refreshAgentsMdConventions:()=>CI});import{execFileSync as bI}from"node:child_process";import{createHash as wI}from"node:crypto";import{mkdir as vI,readFile as kI,realpath as xI,rename as SI,writeFile as EI}from"node:fs/promises";import{dirname as TI,isAbsolute as AI,join as d_,relative as RI,resolve as II}from"node:path";async function Xs(e,t,n){if(e===null)return null;let r=await Js(t,e,{fetcher:n.allowFetch?i=>zs({...i,clientFamily:"codex"}):async()=>null});return r.text===null?null:r.conventions??null}async function CI(e,t){let n=t.err??(r=>process.stderr.write(`${r}
|
|
709
|
+
`));try{if(e!=="codex")return{status:"skipped",reason:"family"};let r=t.env??process.env;if(DI(r))return{status:"skipped",reason:"opt-out"};let i=t.cwd??process.cwd(),s=(t.gitToplevel??h_)(i);if(s===null)return{status:"skipped",reason:"no-root"};let o=await l_(s),c=[];for(let w of await(t.findRoots??As)(i)){let x=await l_(w);OI(x,o)&&!c.includes(x)&&c.push(x)}c.includes(o)||c.push(o);let l=null,d=null;for(let w of c){let x=d_(w,"AGENTS.md"),I=await Q(x);if(I!==null&&Cs(I,en)){l=x,d=I;break}}if(l===null||d===null)return PI(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 no AGENTS.md with the "${en}" header between the working directory and ${o} (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??u_,h=await LI(p),m=MI(l),g=h.roots[m]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<p_)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let v=await(t.loadConventions??((w,x)=>Xs(x,w,{allowFetch:!0})))(t.projectKey,t.apiKey);if(v===null||v.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=Ns(v,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??j}),k=Os(d,b,en);if(k.outcome==="damaged")return n(`maind: AGENTS.md conventions block not refreshed \u2014 begin marker without end marker in ${l}; remove the <!-- maind:conventions --> lines and the bridge re-inserts the block`),{status:"skipped",reason:"damaged"};if(k.outcome==="no-header")return{status:"skipped",reason:"no-agents-md-in-repo"};if(k.changed&&await Y(l,k.next),await $I(p,h,m,u),!k.changed)return{status:"unchanged",file:l};let E=jg(b);return n(`maind: AGENTS.md conventions block refreshed (${E} conventions)`),{status:"refreshed",file:l,conventions:E,inserted:k.outcome==="inserted"}}catch(r){let i=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md conventions block not refreshed \u2014 ${i}`),{status:"failed",error:i}}}function h_(e){try{let t=bI("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 OI(e,t){let n=RI(t,e);return n===""||!n.startsWith("..")&&!AI(n)}async function l_(e){try{return await xI(e)}catch{return II(e)}}function DI(e){return g_(e[f_])}function PI(e){return g_(e[m_])}function g_(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function MI(e){return wI("sha256").update(e).digest("hex")}async function LI(e){let t={version:1,roots:{}};try{let n=JSON.parse(await kI(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[i,s]of Object.entries(n.roots))s&&typeof s.checked_at=="string"&&(r[i]={checked_at:s.checked_at});return{version:1,roots:r}}catch{return t}}async function $I(e,t,n,r){let i={};for(let[o,c]of Object.entries(t.roots)){let l=Date.parse(c.checked_at);!Number.isNaN(l)&&r-l<NI&&(i[o]=c)}i[n]={checked_at:new Date(r).toISOString()},await vI(TI(e),{recursive:!0,mode:448});let s=`${e}.${process.pid}.tmp`;await EI(s,JSON.stringify({version:1,roots:i},null,2),{mode:384}),await SI(s,e)}var u_,p_,f_,m_,NI,Il=_(()=>{"use strict";on();Rl();st();il();Ie();sl();el();Te();u_=d_(Ne,"agents-md-refresh.json"),p_=12*60*60*1e3,f_="MAIND_NO_AGENTS_MD_REFRESH",m_="MAIND_DEBUG",NI=30*24*60*60*1e3;a(Xs,"loadConventionsForAgentsMd");a(CI,"refreshAgentsMdConventions");a(h_,"gitToplevel");a(OI,"isWithin");a(l_,"realpathOrResolve");a(DI,"isOptedOut");a(PI,"isDebug");a(g_,"isSet");a(MI,"fileKey");a(LI,"readState");a($I,"writeState")});import{mkdirSync as S_,rmdirSync as E_,statSync as HI}from"node:fs";import{join as T_}from"node:path";import{setTimeout as BI}from"node:timers/promises";function A_(e){return T_(e,".maind","index-refresh.lock")}function eo(e,t=Date.now()){let n=A_(e);try{if(t-HI(n).mtimeMs<GI)return!1;E_(n)}catch{}try{return S_(n,{recursive:!1}),!0}catch{return!1}}function ii(e){try{E_(A_(e))}catch{}}async function R_(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(o=>BI(o).then(()=>{})),s=r()+(n.waitMs??3e4);try{S_(T_(e,".maind"),{recursive:!0})}catch{}for(;!eo(e,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{ii(e)}}var GI,Nl=_(()=>{"use strict";GI=30*6e4;a(A_,"lockPath");a(eo,"acquireLock");a(ii,"releaseLock");a(R_,"withIndexLock")});import{execFile as W_}from"node:child_process";import{randomUUID as pN}from"node:crypto";function _N(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Ll.test(t)?t:pN()}function $l(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function bN(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 wN(e){return await new Promise(t=>{W_("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(vN(r))})})}function vN(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 kN(){return await new Promise(e=>{W_("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 xN(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function SN(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=Ll.test(r)&&r===t?"env":"random";return{current:a(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:a(()=>!1,"tryUpgrade"),adopt:a(s=>{Ll.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:a(()=>null,"activityAtMs")}}var G_,K_,fN,mN,hN,gN,yN,Ll,io,Fl=_(()=>{"use strict";Qn();G_=45e3,K_=3e4,fN=5,mN=120,hN=3e4,gN=15*6e4,yN=1500,Ll=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(_N,"resolveClientSessionId");a($l,"autoAnnounceDisabled");a(bN,"autoWorkingPathsEnabled");io=class{static{a(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??He)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??kN,this.gitBranchObject=t.gitBranchObject??wN,this.log=t.log??(i=>process.stderr.write(i+`
|
|
710
|
+
`)),this.machineLabel=xN(r?.machine_label),this.enabled=this.projectKey!==null&&!$l(n,r),this.workingPathsEnabled=bN(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??SN(n,_N(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<G_||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<G_||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<fN||(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,yN).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(hN*2**(this.consecutiveFailures-1),gN);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let s=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${s} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:mN,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let s=await this.gitBranch();if(s&&(r.branch=s),this.lastBranch=s,s)try{let o=await this.gitBranchObject(s);o!==null&&o!==this.lastSentObjectId&&(r.object_ids=[o],this.lastSentObjectId=o)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let o=await this.sessionMeta();o?.model&&(r.model=o.model),o?.title&&(r.title=o.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let o=await this.deriveWorkingPaths();o&&o.length>0&&(r.working_paths=o)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let s=i;if(s.ok===!0&&typeof s.session_id=="string")try{this.identity.adopt(s.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let s={sessionId:this.sessionId,branch:this.lastBranch},o=typeof i=="object"?i:null;if(o!==null&&o.ok===!0)this.snapshot.write(i,s);else if(this.snapshot.markFailed){let c=o!==null&&typeof o.error=="string"?o.error:"announce_failed";this.snapshot.markFailed(c,s)}}}catch{}}};a(wN,"defaultGitBranchObject");a(vN,"normalizeObjectId");a(kN,"defaultGitBranch");a(xN,"normalizeMachineLabel");a(SN,"staticIdentity")});import{mkdirSync as V_,readdirSync as J_,readFileSync as EN,renameSync as z_,statSync as TN,unlinkSync as jl,writeFileSync as q_}from"node:fs";import{homedir as AN}from"node:os";import{join as or}from"node:path";function X_(){return or(AN(),".maind","presence")}function Z_(e,t){return or(e,t)}function Q_(e){let t=e.baseDir??X_(),n=Z_(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,s=e.cwd??process.cwd(),o=e.now??Date.now,c=null,l=a(d=>{if(c!==null&&c!==d)try{jl(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 h={v:1,written_at:new Date(o()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[]};V_(n,{recursive:!0,mode:448});let m=or(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;q_(g,JSON.stringify(h),{mode:384}),z_(g,m),l(m),Y_(n,o(),m)}catch{}},endSession(){try{c&&jl(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(o()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};V_(n,{recursive:!0,mode:448});let h=or(n,`${u.sessionId}.json`),m=`${h}.tmp-${r}`;q_(m,JSON.stringify(p),{mode:384}),z_(m,h),l(h),Y_(n,o(),h)}catch{}}}}function Y_(e,t,n){try{for(let r of J_(e)){if(!r.endsWith(".json"))continue;let i=or(e,r);if(i!==n)try{t-TN(i).mtimeMs>RN&&jl(i)}catch{}}}catch{}}function ar(e,t=X_()){try{let n=Z_(t,e),r=[];for(let i of J_(n))if(i.endsWith(".json"))try{let s=JSON.parse(EN(or(n,i),"utf8")),o=IN(s);o&&r.push(o)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function IN(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}:{}}}var RN,so=_(()=>{"use strict";RN=120*6e4;a(X_,"presenceSnapshotBaseDir");a(Z_,"projectDir");a(Q_,"createSnapshotStore");a(Y_,"pruneStale");a(ar,"readSnapshots");a(IN,"parseSnapshot")});import{execFileSync as NN}from"node:child_process";import{createHash as CN,randomUUID as ON}from"node:crypto";import{existsSync as DN,mkdirSync as PN,readdirSync as MN,readFileSync as tb,renameSync as LN,statSync as Ul,unlinkSync as nb,writeFileSync as $N}from"node:fs";import{homedir as FN}from"node:os";import{basename as jN,join as xt}from"node:path";function cr(e){return xt(e??xt(FN(),".maind","presence"),"identity")}function oi(e,t){if(e){let n=jN(e).replace(/\.jsonl$/i,"");if(si.test(n))return n.toLowerCase()}return t&&si.test(t)?t.toLowerCase():null}function rb(e){let t=e.nowMs??Date.now();PN(e.dir,{recursive:!0,mode:448});let n=xt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(tb(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=e.transcriptPath??i.transcript_path,o=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...s?{transcript_path:s}:{},...o?{model:o}:{}};$N(r,JSON.stringify(c,null,2)+`
|
|
711
|
+
`,{mode:384}),LN(r,n),WN(e.dir,t)}function ib(e,t,n,r=Date.now()){try{let i=Ul(xt(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function sb(e,t){try{nb(xt(e,`${t}.json`))}catch{}}function WN(e,t){try{for(let n of MN(e))if(n.endsWith(".json"))try{let r=Ul(xt(e,n));t-r.mtimeMs>HN&&nb(xt(e,n))}catch{}}catch{}}function KN(e){return ob(e)?.file??null}function ob(e){let t=xt(e.dir,`${e.agentPid}.json`);try{if(!DN(t))return null;let n=Ul(t);if(n.mtimeMs<e.bridgeStartMs-BN)return null;let r=JSON.parse(tb(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!si.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!VN(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function eb(e){return e.replace(/\/+$/,"")}function VN(e,t){let n=eb(e),r=eb(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function zN(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=CN("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=i.toString("hex");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function qN(e){if(process.platform==="win32")return null;try{let t=NN("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function YN(){try{return ne()}catch{return null}}var si,UN,HN,BN,GN,oo,ao=_(()=>{"use strict";ae();si=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,UN=8,HN=48*60*6e4,BN=6e4,GN="9f3c72da-2f10-4b8f-9c31-ad291c0de291";a(cr,"identityDirPath");a(oi,"transcriptStemOf");a(rb,"writeAgentIdentityFile");a(ib,"identityFileStale");a(sb,"deleteAgentIdentityFile");a(WN,"pruneIdentityDir");a(KN,"readAgentIdentityFile");a(ob,"readAgentIdentityEntry");a(eb,"normDir");a(VN,"sameSessionTree");a(zN,"uuidV5");a(qN,"processStartTime");oo=class{static{a(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??cr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=si.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??YN)(),s=(t.ppidStart??qN)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=zN(`${i}|${this.agentPid}|${s}|${t.projectKey}`,GN),this.source="derived";return}this.id=ON(),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(!si.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>UN&&this.aliases.shift())}activityAtMs(){return ob({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 KN({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};a(YN,"defaultDeviceId")});function Hl(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Bl=_(()=>{"use strict";a(Hl,"newModeState")});import{createReadStream as JN,existsSync as XN}from"node:fs";import{stat as ZN}from"node:fs/promises";import{createInterface as QN}from"node:readline";async function Gl(e){if(!e||!XN(e))return null;let t;try{t=await ZN(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(o=>{let c=JN(e,{encoding:"utf-8"}),l=QN({input:c});l.on("line",d=>{let u=d.trim();if(u){s++;try{let p=JSON.parse(u),h=p.message?.usage;if(!h)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 h.input_tokens=="number"&&(r+=h.input_tokens),typeof h.output_tokens=="number"&&(i+=h.output_tokens)}catch{}}}),l.on("close",()=>{o({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:s,last_modified_ms:t.mtimeMs})}),l.on("error",()=>o(null)),c.on("error",()=>o(null))})}var ab=_(()=>{"use strict";a(Gl,"summariseTranscript")});var cb=_(()=>{"use strict"});function ai(e){if(!e)return null;let t=null;for(let n of e.matchAll(tC)){let r=n[1].toLowerCase();eC.has(r)&&(t=r)}return t}var eC,tC,co=_(()=>{"use strict";eC=new Set(["low","medium","high","xhigh","max"]),tC=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;a(ai,"detectEffortLevel")});import{createReadStream as nC,existsSync as rC,readdirSync as iC}from"node:fs";import{basename as ub,dirname as sC,join as lb}from"node:path";import{createInterface as oC}from"node:readline";function lr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function lC(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=cC[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&t.push(s)}return t}function lo(e){let t=ub(e).replace(/\.jsonl$/,""),n=lb(sC(e),t,"subagents"),r;try{r=iC(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>lb(n,i))}async function db(e,t,n,r,i){rC(e)&&await new Promise(s=>{let o=nC(e,{encoding:"utf-8"}),c=oC({input:o}),l=0;c.on("line",d=>{l++;let u=d.trim();if(!u)return;let p;try{p=JSON.parse(u)}catch{return}if(p.message?.role!=="assistant")return;let h=typeof p.message.id=="string"&&p.message.id?p.message.id:null,m=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=h??m??`${e}#${l}`,y=lC(p.message.content),v=r.get(g);if(v){for(let x of y)v.edited_paths.includes(x)||v.edited_paths.push(x);return}if(n.has(g))return;n.add(g);let b=p.message.usage??{},k=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,E=typeof p.message.model=="string"&&p.message.model?p.message.model:"",w={ts:Number.isFinite(k)?k:0,model:E||"<unknown>",synthetic:E===aC,input_tokens:lr(b.input_tokens),output_tokens:lr(b.output_tokens),cache_read_tokens:lr(b.cache_read_input_tokens),cache_creation_tokens:lr(b.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(lr(b.cache_creation?.ephemeral_1h_input_tokens),lr(b.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:y,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(g,w),i.push(w)}),c.on("close",()=>s()),c.on("error",()=>s()),o.on("error",()=>s())})}function Wl(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 ci(e){let t=new Set,n=new Map,r=[],i=e?lo(e):[];if(!e)return{turns:r,subagent_files:i};let s=[];await db(e,pn,t,n,s),Wl(s),r.push(...s);for(let o of i){let c=[],l=ub(o).replace(/\.jsonl$/,"");await db(o,l,t,n,c),Wl(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var pn,aC,cC,uo=_(()=>{"use strict";pn="main",aC="<synthetic>",cC={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};a(lr,"num");a(lC,"editedPathsOf");a(lo,"subagentFilesOf");a(db,"readStream");a(Wl,"fillTimestamps");a(ci,"collectTurns")});import{createReadStream as pb,existsSync as dC}from"node:fs";import{createInterface as fb}from"node:readline";function yC(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,o=e.get(s);if(!o){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}o.turns++,o.output_tokens+=r,i>0&&((o.first_ts===0||i<o.first_ts)&&(o.first_ts=i),i>o.last_ts&&(o.last_ts=i))}function po(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function _C(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
712
|
+
`)}function bC(e,t){let n=a(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,o]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)o.has(l)&&c++;return c/s.size>=.8}function wC(e,t,n){return uC.test(e)?{polarity:-1,magnitude:dr.rework,kind:"rework"}:n&&pC.test(e)?{polarity:-1,magnitude:dr.correction,kind:"correction"}:fC.test(e)?{polarity:1,magnitude:dr.acceptance,kind:"acceptance"}:t!==null&&bC(t,e)?{polarity:-1,magnitude:dr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function vC(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:mb,behaviour_measured:!0}}async function kC(e,t){for(let n of lo(e))await new Promise(r=>{let i=fb({input:pb(n,{encoding:"utf-8"})});i.on("line",s=>{let o=s.trim();if(!o)return;let c;try{c=JSON.parse(o)}catch{return}if(c.message?.role==="assistant")for(let l of po(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(fo))continue;let d=l.name.slice(fo.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 Kl(e,t={}){let n=vC("");if(!e||!dC(e))return n;let r=t.turns??(await ci(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=[],s=new Map,o=null,c=!1,l=null;await new Promise(m=>{let g=pb(e,{encoding:"utf-8"}),y=fb({input:g}),v=a(b=>{let k=b.trim();if(!k)return;let E;try{E=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let U=E.sessionId??E.session_id;typeof U=="string"&&U&&(n.session_id=U)}E.type==="ai-title"&&typeof E.aiTitle=="string"&&E.aiTitle&&(n.ai_title=E.aiTitle),typeof E.slug=="string"&&E.slug&&(n.session_slug=E.slug);let w=E.message?.role,x=E.isSidechain===!0;if(w==="assistant")for(let U of po(E.message?.content)){if(U.type!=="tool_use"||typeof U.name!="string"||!U.name.startsWith(fo))continue;let he=U.name.slice(fo.length);he&&(n.maind_tool_calls??={},n.maind_tool_calls[he]=(n.maind_tool_calls[he]??0)+1)}if(x)return;if(w==="assistant"){let U=po(E.message?.content),he=!1;for(let wn of U)wn.type==="tool_use"&&(n.tool_calls++,he=!0,wn.name==="AskUserQuestion"&&n.agent_questions++);c=he;return}if(w!=="user")return;let I=po(E.message?.content),F=_C(I);if(F.includes(mC)){n.interrupts++,i.push({polarity:-1,magnitude:dr.interrupt,kind:"interrupt"});return}if(I.some(U=>U.type==="tool_result"&&U.is_error===!0&&typeof U.content=="string"&&U.content.includes(hC))){n.tool_denials++,i.push({polarity:-1,magnitude:dr.denial,kind:"denial"});return}if(I.some(U=>U.type==="tool_result")||!F.trim())return;n.user_turns++,n.user_chars+=F.length;let H=ai(F);H&&(o=H);let C=wC(F,l,c);l=F,C.kind==="correction"?n.corrections++:C.kind==="rework"?n.reworks++:C.kind==="repeat"?n.repeated_instructions++:C.kind==="acceptance"&&n.acceptances++,C.polarity!==0&&i.push(C),c=!1},"processLine");y.on("line",b=>{try{v(b)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await kC(e,n),n.effort_at_end=o;for(let m of r)m.synthetic||m.model==="<unknown>"||yC(s,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...s.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,h=[];return i.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,u=u*gC+m.polarity*m.magnitude;let y=Number(u.toFixed(3));h.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=h,n.momentum_final=h.length?h[h.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 fo,mb,uC,pC,fC,mC,hC,gC,dr,hb=_(()=>{"use strict";co();uo();fo="mcp__maind__",mb="2026-10-01",uC=/(\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,pC=/(\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,fC=/(\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,mC="[Request interrupted by user",hC="The user doesn't want to proceed with this tool use",gC=.7,dr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};a(yC,"bumpModel");a(po,"asBlocks");a(_C,"textOf");a(bC,"isRepeat");a(wC,"classifyGenuine");a(vC,"emptyAnalysis");a(kC,"tallySubagentMaindCalls");a(Kl,"analyzeSession")});function Vl(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 zl(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 ql(e,t,n,r="unknown",i){let s={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(s.session_span=n?{...t,...n}:t),s}var gb=_(()=>{"use strict";a(Vl,"parseIngestResponse");a(zl,"describeSliceVerdict");a(ql,"ingestBody")});import{homedir as xC}from"node:os";import{join as SC}from"node:path";var EC,Yl=_(()=>{"use strict";EC=SC(xC(),".codex","sessions")});var yb=_(()=>{"use strict";Yl()});import{isAbsolute as Zl,relative as AC,resolve as _b,sep as Ql}from"node:path";function bb(e){return e>ho[1]?"above_272k":e>ho[0]?"band_200k_272k":"standard"}function wb(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function mo(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function ed(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=a(o=>{if(!Array.isArray(o))return[];let c=[];for(let l of o){if(!l||typeof l!="object")continue;let d=l,u=mo(d.from);typeof d.object_id!="string"||!Jl.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:mo(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let o of n.claims){if(!o||typeof o!="object")continue;let c=o,l=mo(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:mo(c.to)})}let s=[];if(Array.isArray(n.anchors))for(let o of n.anchors){if(!o||typeof o!="object")continue;let c=o;typeof c.object_id!="string"||!Jl.test(c.object_id)||typeof c.path_prefix=="string"&&s.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Jl.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:s}}function vb(e,t){if(!Zl(e))return null;let n=AC(_b(t),_b(e));return!n||n==="."||n.startsWith("..")||Zl(n)?null:Ql==="/"?n:n.split(Ql).join("/")}function IC(e,t){return t===""||e===t||e.startsWith(t+"/")}function td(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function kb(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function nd(e,t){for(let n of kb(t))if(IC(e,n.path_prefix))return n.object_id;return null}function NC(e,t){for(let n of kb(t))if(td(e,n.path_prefix))return n.object_id;return null}function Xl(e,t){return e>=t.from&&(t.to===null||e<t.to)}function xb(e,t,n,r){let i=e.ts,s=r?.anchors??[],o=t.map(c=>nd(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Xl(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=>Xl(i,u));if(l.length)return{object_id:(l.find(p=>o.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,h)=>p.object_id.localeCompare(h.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>Xl(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(h=>td(h.path_prefix,u))).sort((h,m)=>m.path_prefix.length-h.path_prefix.length);for(let h of p){let m=NC(h.path_prefix,s);if(m)return{object_id:m,source:"claim"}}}}return o.length?{object_id:o[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function rd(e,t,n){let r=t?.anchors??[],i=a(g=>{if(!n.repoRoot)return[];let y=[];for(let v of g.edited_paths){let b=vb(v,n.repoRoot);b!==null&&!y.includes(b)&&y.push(b)}return y},"relOf"),s=a(g=>{for(let y of g){let v=nd(y,r);if(v)return{object_id:v,rel:y}}return null},"firstAnchoredEdit"),o=new Map;for(let g of e){let y=o.get(g.stream)??[];y.push(g),o.set(g.stream,y)}let c=[...o.entries()].sort(([g],[y])=>g===pn?-1:y===pn?1:0),l=[],d=a(g=>{let y=null;for(let v of l){if(v.ts>g&&g>0)break;y=v.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let v=y.map((k,E)=>({t:k,i:E,rels:i(k)})).sort((k,E)=>k.t.ts-E.t.ts||k.i-E.i),b=null;for(let k of v){let E=s(k.rels);if(E){b=E;break}}!b&&g!==pn&&v.length&&(b=d(v[0].t.ts));for(let k of v){let E=s(k.rels);E&&(b=E),g===pn&&l.push({ts:k.t.ts,seg:b});let w=k.t;if(w.input_tokens+w.output_tokens+w.cache_read_tokens+w.cache_creation_tokens===0)continue;let I=xb(w,k.rels,b,t),F=bb(w.input_tokens+w.cache_read_tokens+w.cache_creation_tokens),B=wb(w.model),H=`${I.object_id??""}|${I.source}|${B}|${F}`,C=u.get(H);C||(C={object_id:I.object_id,attribution_source:I.source,model:B,context_tier:F,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},u.set(H,C)),C.input_tokens+=w.input_tokens,C.output_tokens+=w.output_tokens,C.cache_read_tokens+=w.cache_read_tokens,C.cache_creation_tokens+=w.cache_creation_tokens,C.cache_creation_1h_tokens+=w.cache_creation_1h_tokens,C.turns+=1,w.ts>0&&((C.firstMs===0||w.ts<C.firstMs)&&(C.firstMs=w.ts),w.ts>C.lastMs&&(C.lastMs=w.ts))}}let p=n.nowMs??Date.now(),h=[];for(let g of u.values()){let{firstMs:y,lastMs:v,...b}=g;b.first_ts=new Date(y>0?y:p).toISOString(),b.last_ts=new Date(v>0?v:p).toISOString(),h.push(b)}let m={lease:0,binding:1,claim:2,path:3,none:4};return h.sort((g,y)=>m[g.attribution_source]-m[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),h}function id(e,t){let n=new Map;for(let s of e){let o=new Set;for(let c of s.edited_paths){if(!Zl(c))continue;let l=t(CC(c));l&&o.add(l)}for(let c of o)n.set(c,(n.get(c)??0)+1)}let r=null,i=0;for(let[s,o]of n)(o>i||o===i&&r!==null&&s.length>r.length)&&(r=s,i=o);return r}function CC(e){let t=e.split(Ql).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var ho,RC,Jl,Sb=_(()=>{"use strict";uo();ho=[2e5,272e3];a(bb,"contextTierOf");a(wb,"normalizeModelId");RC=ho[0],Jl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(mo,"msOf");a(ed,"parseCostContext");a(vb,"toRepoRelative");a(IC,"underPrefix");a(td,"prefixesOverlap");a(kb,"sortedAnchors");a(nd,"anchorFor");a(NC,"bestAnchorOverlapping");a(Xl,"inWindow");a(xb,"assignTurn");a(rd,"sliceSession");a(id,"dominantCheckoutRoot");a(CC,"dirOf")});var Eb=_(()=>{"use strict"});import{createReadStream as OC,existsSync as DC}from"node:fs";import{createInterface as PC}from"node:readline";function Tb(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function $C(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
713
|
+
`)}function Ib(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 FC(e){let t=e.message?.role;if(t==="assistant")return{holder:Tb(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Tb(e.message?.content),r=$C(n);return r.includes(MC)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(LC))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function sd(e){let t=Ib("");if(!e||!DC(e))return t;let n=null,r=0,i=0,s=null,o="human",c=[];return await new Promise(l=>{let d=OC(e,{encoding:"utf-8"}),u=PC({input:d}),p=a(h=>{let m=h.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)||s!==null&&y<s)return;let v=FC(g);if(v!==null){if(t.event_count++,v.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let b=y-s;o==="agent"?i+=b:b>=Ab*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<Rb&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(b/1e3)}))}s=y,o=v.holder}},"processLine");u.on("line",h=>{try{p(h)}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 MC,LC,Ab,Rb,Nb=_(()=>{"use strict";MC="[Request interrupted by user",LC="The user doesn't want to proceed with this tool use",Ab=60,Rb=200;a(Tb,"asBlocks");a($C,"textOf");a(Ib,"emptySpan");a(FC,"classify");a(sd,"analyzeSpan")});import{createReadStream as jC,existsSync as UC}from"node:fs";import{createInterface as HC}from"node:readline";function GC(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function go(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function WC(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(`
|
|
714
|
+
`)}return""}async function od(e,t={}){if(!e||!UC(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Hl(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:Hl(),o=t.start??0;return await new Promise(c=>{let l=jC(e,{encoding:"utf-8",start:t.start??0}),d=HC({input:l});d.on("line",p=>{o+=Buffer.byteLength(p,"utf-8")+1;let h=p.trim();if(!h)return;let m;try{m=JSON.parse(h)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),v=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=BC[m.attachment.type];b&&(s[GC(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(v==="user"){let b=WC(m.message?.content),k=ai(b);k&&(i=k);let E={session_id:g,ts:y,text:b,effort_directive:k};n.push({kind:"user",...E});return}if(v==="assistant"){let b=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,E=typeof m.requestId=="string"&&m.requestId?m.requestId:null,w=k??E,x=w!==null&&r.has(w);w!==null&&!x&&r.add(w);let I={session_id:g,ts:y,model:m.message?.model??null,input_tokens:x?0:go(b?.input_tokens),output_tokens:x?0:go(b?.output_tokens),cache_read_input_tokens:x?0:go(b?.cache_read_input_tokens),cache_creation_input_tokens:x?0:go(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...s.ultracode?{ultracode:!0}:{},...s.planMode?{planMode:!0}:{},...s.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...I})}});let u=a(()=>({events:n,bytesRead:o,effortAtEnd:i,modesAtEnd:{...s},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var BC,Cb=_(()=>{"use strict";co();Bl();BC={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}};a(GC,"modeFlagKey");a(go,"num");a(WC,"extractUserText");a(od,"streamTranscript")});var Ob=_(()=>{"use strict"});import{homedir as KC}from"node:os";import{join as VC}from"node:path";function cd(e){return e.replace(/[/.]/g,"-")}var zC,ad,Db=_(()=>{"use strict";zC=KC(),ad=VC(zC,".claude","projects");a(cd,"projectPathFromCwd")});var ur=_(()=>{"use strict";Bl();ab();cb();hb();gb();uo();Yl();yb();Sb();Eb();Nb();Cb();co();Ob();Db()});import{parse as nO}from"jsonc-parser";function ld(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 iO(e){if(e.raw===null)return null;if(e.kind==="toml"){let s=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!s)return null;let o=/^\s*command\s*=\s*"([^"]*)"/m.exec(s[1]),c=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(s[1]);return o?{command:o[1],args:c?[...c[1].matchAll(/"([^"]*)"/g)].map(l=>l[1]):[]}:null}let t=[],n=nO(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;return!i||typeof i.command!="string"?null:{command:i.command,args:Array.isArray(i.args)?i.args.filter(s=>typeof s=="string"):[]}}function pr(e,t){let n=`npm i -g ${li}@${e}`;return t?`nvm use ${t} && ${n}`:n}function _o(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(u=>u.bridgeVersion).filter(u=>u!==null)],r=e.latestVersion??n.sort(ld).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(u=>u.bridgeVersion!==null);if(e.nodeTrees.length>0){let u=e.pathWinner?.node??null,p=e.nodeTrees.find(m=>m.node===u);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):p&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${p.node} tree (${p.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let m=e.nodeTrees.find(g=>g.node===e.nvmDefault);m&&m.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${m.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:pr(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(g=>ld(g.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${m.node} carries bridge ${m.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:pr(r,m.node)})}let s=!1,o=new Map,c=a((u,p)=>{let h=o.get(u)??{version:e.installVersionOf(u),clients:[]};h.clients.push(p),o.set(u,h)},"noteInstall");for(let u of e.clientConfigs){let p=iO(u);if(p===null)continue;if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(g=>g.includes(li))){t.push({check:"client-config",level:"warn",message:`${u.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${pr(r)}, then set "command": "maind-mcp-bridge" (no args) in ${u.path}`});continue}let m=/(^|[\\/])node(\.exe)?$/.test(p.command);if(m&&p.args.length>0){let g=p.args[0];if(!e.fileExists(g)){t.push({check:"client-config",level:"error",message:`${u.label} runs ${g}, which does not exist.`,fix:`re-run \`npx -y ${li}@${r} install\` to rewrite the entry`});continue}c(g,u.label)}else if(p.command.includes("/")||p.command.includes("\\")){if(!e.fileExists(p.command)){t.push({check:"client-config",level:"error",message:`${u.label} points at ${p.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${u.path} (after ${pr(r)})`});continue}}else if(p.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${u.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:pr(r,e.nvmDefault)});continue}m||(p.command.includes("/")||p.command.includes("\\")?c(p.command,u.label):p.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,u.label)),t.push({check:"client-config",level:"ok",message:`${u.label}: ${[p.command,...p.args].join(" ")}`})}if(s||t.push({check:"client-config",level:"warn",message:"no MCP client config names a `maind` server.",fix:`npx -y ${li} install`}),e.latestVersion!==null)for(let[u,p]of o){let h=p.clients.join(", ");if(p.version===null)t.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${u} is.`});else if(ld(p.version,e.latestVersion)<0){let m=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(u)?.[1]??null;t.push({check:"version",level:"warn",message:`${h} run bridge ${p.version} (${u}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:m?pr(e.latestVersion,m):`npx -y ${li}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${h} run bridge ${p.version} (published: ${e.latestVersion}).`})}for(let{dir:u,maind:p}of e.npxStaleDirs)t.push({check:"npx-cache",level:p?"error":"info",message:p?`a half-built better-sqlite3 was left in ${u} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${u} (another tool's npx entry, not maind's).`,fix:`rm -rf '${u.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!Lb.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"}):rO.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&Lb.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 u=tn(e.claudeSettings,{fileExists:a(h=>e.fileExists(h),"fileExists")}),p=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let h of u){if(h.status==="missing")continue;if(h.status!=="ok"){t.push({check:"hooks",level:h.status==="broken"?"error":"warn",message:h.detail});continue}let m=h.command?/(\S+\/build\/index\.js)/.exec(h.command)?.[1]??null:null,g=m?e.installVersionOf(m):null;g!==null&&p!==null&&g!==p&&t.push({check:"hooks",level:"warn",message:`${h.event}/${h.subcommand} runs bridge ${g}, the MCP server runs ${p} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${h.subcommand}`})}t.some(h=>h.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}return t}function $b(e){let t=e.filter(i=>i.level==="error"&&dd.includes(i.check)).sort((i,s)=>dd.indexOf(i.check)-dd.indexOf(s.check)),n=t[0];if(n===void 0)return null;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 Fb(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((o,c)=>n[o.level]-n[c.level]).flatMap(o=>[`${t[o.level]} [${o.check}] ${o.message}`,...o.fix?[` fix: ${o.fix}`]:[]]),i=e.filter(o=>o.level==="error").length,s=e.filter(o=>o.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
715
|
+
`)+`
|
|
716
|
+
`}var li,rO,Lb,dd,ud=_(()=>{"use strict";Zn();li="@maind-dev/mcp-bridge",rO=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,Lb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(ld,"compareVersions");a(iO,"maindEntry");a(pr,"installFix");a(_o,"diagnose");dd=["connection","client-config","npx-cache","hooks"];a($b,"sessionStartLine");a(Fb,"renderFindings")});var Bb={};ee(Bb,{realProbe:()=>wo,resolveNvmAlias:()=>Hb,runDoctor:()=>hO});import{execFileSync as sO}from"node:child_process";import{existsSync as md,readFileSync as oO,readdirSync as pd,realpathSync as aO}from"node:fs";import{homedir as di,platform as bo}from"node:os";import{delimiter as cO,dirname as jb,join as de}from"node:path";function fn(e){try{return md(e)?oO(e,"utf8"):null}catch{return null}}function lO(){try{let e=sO(bo()==="win32"?"npm.cmd":"npm",["view",Ub,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function fd(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:de(di(),".nvm")}function dO(){let e=de(fd(),"versions","node"),t=[];try{t=pd(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=fn(de(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 Hb(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(d[p]!==u[p])return(d[p]??0)-(u[p]??0);return 0});if(r==="node"||r==="stable")return i.at(-1)??null;let s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return s;let o=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(o)).at(-1)??null}function uO(e){let t=fn(de(fd(),"alias","default"));return t===null?null:Hb(t,e.map(n=>n.node),n=>{let r=fn(de(fd(),"alias",n));return r===null?null:r})}function pO(){let e=bo()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(cO))if(t)for(let n of e){let r=de(t,n);if(md(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function fO(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:bo()==="win32"?de(process.env.LOCALAPPDATA??de(di(),"AppData","Local"),"npm-cache"):de(di(),".npm"),t=de(e,"_npx"),n=[],r=[];try{r=pd(t)}catch{return[]}for(let i of r)try{let s=pd(de(t,i,"node_modules"));s.some(o=>o.startsWith(".better-sqlite3-"))&&n.push({dir:de(t,i),maind:s.includes("@maind-dev")})}catch{}return n}function mO(e){let t;try{t=jb(aO(e))}catch{return null}for(let n=0;n<6;n++){let r=fn(de(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===Ub)return s.version??null}catch{}let i=jb(t);if(i===t)break;t=i}return null}function wo(e=process.cwd(),t={}){let n=dO(),r=fn(de(Ee(),"device-id")),i=Es({projectRoot:e,homeDir:di(),platform:bo(),env:process.env}),s=null;try{s=K()}catch{s=null}let o=(process.env.MAIND_API_KEY??"").trim();return{runningVersion:j,latestVersion:t.offline===!0?null:lO(),nodeTrees:n,nvmDefault:uO(n),pathWinner:pO(),clientConfigs:qr(i).map(c=>({label:c.label,path:c.path,kind:c.kind,raw:fn(c.path)})),npxStaleDirs:fO(),connection:pg(),claudeSettings:fn(de(di(),".claude","settings.json")),fileExists:a(c=>md(c),"fileExists"),installVersionOf:mO,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:o.length>0?o:null}}async function hO(e){let t=_o(wo());return e.includes("--json")?process.stdout.write(JSON.stringify({version:j,findings:t},null,2)+`
|
|
717
|
+
`):process.stdout.write(Fb(t)),t.some(n=>n.level==="error")?1:0}var Ub,hd=_(()=>{"use strict";Qc();ae();Jr();Te();ud();Ub="@maind-dev/mcp-bridge";a(fn,"readOrNull");a(lO,"latestVersion");a(fd,"nvmDir");a(dO,"nodeTrees");a(Hb,"resolveNvmAlias");a(uO,"nvmDefault");a(pO,"pathWinner");a(fO,"npxStaleDirs");a(mO,"installVersionOf");a(wo,"realProbe");a(hO,"runDoctor")});function gO(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":ne()}}async function Gb(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:gO(t),body:JSON.stringify({metrics:n})});if(!r.ok){let s=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:s.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var vo,gd=_(()=>{"use strict";ae();Kn();vo=process.env.MAIND_ENDPOINT??Wn("mcp-client-metrics-ingest");a(gO,"ingestHeaders");a(Gb,"postMetrics")});function Wb(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Vb(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,s=Array.isArray(i.active_claims)?i.active_claims:[],o=[];for(let c of s){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||o.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:o,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function fr(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function ui(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function zb(e,t,n){let r=n.maxAgeMs??Kb,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,o=Vb(e,s),c=[];for(let l of o)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)Wb(t,d.path_prefix)&&c.push(`'${d.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${ui(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${ui(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Wb(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${ui(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${ui(s)} ago, advisory \u2014 never a lock):
|
|
718
|
+
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
719
|
+
`)+`
|
|
720
|
+
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 qb(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 Yb(e,t,n,r=Kb,i=null){if(!e)return null;let s=n-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let o=s/1e3,c=Vb(e,o),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",h=u>0?`, ${u} presence-only`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${h}) as of ${ui(o)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
721
|
+
${m}`:m}var Kb,yd=_(()=>{"use strict";a(Wb,"prefixConflict");Kb=10*6e4;a(Vb,"parsePeers");a(fr,"selectOwnSnapshot");a(ui,"ageDisplay");a(zb,"adviseOnPath");a(qb,"claimedIdentity");a(Yb,"sessionStartSummary")});function Xb(e){let t=[];for(let n of Zb(e)){let r=xO(n);r&&!t.includes(r)&&t.push(r)}return t}function Zb(e){let t=[],n="",r=null,i=0,s=[],o=a(()=>{n.trim()&&t.push(n),n=""},"flush");for(;i<e.length;){let c=e[i];if(r){if(c==="\\"&&r==='"'){n+=c+(e[i+1]??""),i+=2;continue}c===r&&(r=null),n+=c,i+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,i+=1;continue}if(c==="<"&&e[i+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(i));if(l){s.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
|
|
722
|
+
`){if(s.length>0){let d=e.slice(i+1).split(`
|
|
723
|
+
`),u=0;for(;s.length>0&&u<d.length;)d[u].trim()===s[0]&&s.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,h)=>p+h.length+1,0),s=[],o();continue}o(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){o(),i+=2;continue}if(c===";"||c==="|"){o(),i+=1;continue}n+=c,i+=1}return o(),t}function xO(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let o=t[n];if(o===void 0)return null;if(_O.test(o)){n+=1;continue}if(wO.has(o)){n+=1;continue}if(vO.has(o))return null;let c=o.split("/").pop()??o;if(bO.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!Jb.test(i))return null;if(!yO.test(i))return _d;if(!kO.has(i))return i;let s=t[n+1];return s&&Jb.test(s)?`${i} ${s}`:i}function bd(e){let t=Xb(e).filter(n=>n!==_d&&!Qb.has(n));return t.length>0?t[t.length-1]:null}var Jb,yO,_d,_O,bO,wO,vO,kO,Qb,wd=_(()=>{"use strict";Jb=/^[A-Za-z][A-Za-z0-9._-]*$/,yO=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,_d="?",_O=/^[A-Za-z_][A-Za-z0-9_]*=/,bO=new Set(["sudo","env","time","nohup","nice","command","exec"]),wO=new Set(["do","then","else","elif","if","while","until","!","{","("]),vO=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),kO=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"]);a(Xb,"shellPrograms");a(Zb,"commandSegments");a(xO,"programOf");Qb=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"]);a(bd,"primaryVerb")});function ew(e){let t=e.length>vd?e.slice(-vd):e;return SO.some(n=>n.test(t))}function kd(e){return e.includes("maind")?EO.some(t=>e.includes(t)):!1}function tw(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function nw(e,t){if(!tw(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?bd(n):null}function xd(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=nw(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&ew(e.output)?"fail":"ok",verb:t}}var vd,SO,EO,rw=_(()=>{"use strict";wd();vd=8192,SO=[/\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];a(ew,"outputShowsFailure");EO=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];a(kd,"isConsultationTool");a(tw,"isCountedTool");a(nw,"verbOfCall");a(xd,"observe")});function iw(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 Sd(e,t=-1/0){let n=e.filter(s=>s.k==="fail"&&s.t>t).slice().sort((s,o)=>s.t-o.t),r=[],i=[];for(let s of n)i.length>0&&s.t-i[i.length-1].t>6e5&&(r.push(iw(i)),i=[]),i.push(s);return i.length>0&&r.push(iw(i)),r}function Ed(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 sw(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function mr(e,t,n){let r=sw(e,t),i=Sd(e,r),s=i.length>0?i[i.length-1]:null,o=s!==null&&n-s.end<=6e5?s:null;if(o===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=Ed(e,o.lastVerb,o.end)!==null,l=e.some(d=>d.k==="nudge"&&d.t>=o.start);return{open:o.failures.length>=4&&!c,chain:o,nudged:l,resolved:c}}function Td(e){return e.open&&!e.nudged}function Ad(e,t){let n=-1/0;for(let s of e)s.k==="prompt"&&s.t>n&&(n=s.t);let r=Math.max(t,n),i=Sd(e,r);for(let s=i.length-1;s>=0;s--){let o=i[s];if(o.failures.length<5||o.end-o.start<3e5)continue;let c=Ed(e,o.lastVerb,o.end);if(c!==null)return{...o,resolvedAt:c}}return null}function pi(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 Rd=_(()=>{"use strict";a(iw,"chainOf");a(Sd,"failureChains");a(Ed,"succeededAfter");a(sw,"resetPoint");a(mr,"difficultyStatus");a(Td,"shouldNudge");a(Ad,"captureCandidate");a(pi,"verbSummary")});function AO(e){let t=e.id;if(typeof t!="string")return null;let n=e.version,r=typeof n=="number"&&Number.isInteger(n)&&n>=1?n:1,i=e.severity,s=typeof i=="string"&&TO.has(i)?i:"recommended",o=e.enabled!==!1;return{id:t,version:r,severity:s,enabled:o}}function xo(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return mi;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let s=AO(i);s!==null&&(s.id===fi?n=s:s.id===ko&&(r=s))}return{difficulty:n,capture:r}}function hr(e){return e!==null&&e.enabled}function Id(e){return hr(e)&&e.severity==="required"}var fi,ko,mi,TO,Nd=_(()=>{"use strict";fi="conv_consult_on_difficulty",ko="conv_learning_capture_offer",mi={difficulty:null,capture:null},TO=new Set(["required","recommended","info"]);a(AO,"ruleOf");a(xo,"extractTriggerPolicy");a(hr,"isActive");a(Id,"isDenyCapable")});function RO(e){return Math.max(1,Math.round(e/6e4))}function hi(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${pi(e)}) and no maind consultation since they started (${fi}). Before the next attempt, consult maind: search_lessons with the symptom \u2014 error code, tool or library, the failing program \u2014 never paths, file contents or secrets. If a hit applies, use it; if none does, say so in one line and go on. This hint appears once per episode.`}function Cd(e){return`difficulty episode (${e.failures.length} failed attempts: ${pi(e)}) without a maind consultation since it started (${fi}, required)`}function Od(e,t="guard"){let n=RO(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${ko}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${pi(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 ow=_(()=>{"use strict";Rd();Nd();a(RO,"minutes");a(hi,"nudgeText");a(Cd,"difficultyDenyHead");a(Od,"captureText")});var gr=_(()=>{"use strict";wd();rw();Rd();Nd();ow()});function mn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function at(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function So(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function cw(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}var hn=_(()=>{"use strict";a(mn,"denyPayload");a(at,"advisoryPayload");a(So,"postAdvisoryPayload");a(cw,"postFailureAdvisoryPayload")});import{realpathSync as IO}from"node:fs";import{basename as lw,dirname as dw,join as NO}from"node:path";function gn(e){let t=dw(e),n=[lw(e)];for(;;)try{let r=IO(t);return NO(r,...n.reverse())}catch{let r=dw(t);if(r===t)return e;n.push(lw(t)),t=r}}var Eo=_(()=>{"use strict";a(gn,"realpathOfUnwritten")});import{existsSync as CO,realpathSync as OO,statSync as DO}from"node:fs";import{dirname as uw,isAbsolute as PO,join as MO}from"node:path";function FO(e,t){let n=e.filter(i=>pw.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
|
|
724
|
+
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
725
|
+
${i.detail}${s}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
726
|
+
|
|
727
|
+
`+r.join(`
|
|
728
|
+
|
|
729
|
+
`)+`
|
|
730
|
+
|
|
731
|
+
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 jO(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function UO(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},s=i[t]??{};s[n]=new Date(r).toISOString(),i[t]=s,e.repo_health_seen=i}function Dd(e){let t=uw(e);for(;;){try{if(DO(t).isDirectory())return t}catch{}let n=uw(t);if(n===t)return t;t=n}}async function HO(e,t,n){let r=await n.load();if(jO(r,e,t))return null;UO(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let s=i.filter(c=>pw.includes(c.id)).length,o=await n.load();return o.pending_metrics.push({session_id:e,metric_key:LO,metric_value:1},{session_id:e,metric_key:$O,metric_value:s}),await n.save(o),FO(i,t)}async function fw(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=Be(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=PO(r)?r:MO(i,r),o=CO(s)?OO(s):gn(s),c=Qe(Dd(o)),l=await HO(n,c,{load:q,save:Ge,check:a(async d=>(await Dr(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(at(l)),0}catch{return 0}}var pw,LO,$O,Pd=_(()=>{"use strict";qt();Yt();hn();we();Eo();rt();pw=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],LO="repo_health_hook_runs",$O="repo_health_hook_findings";a(FO,"formatRepoHealth");a(jO,"alreadySeen");a(UO,"markSeen");a(Dd,"nearestExistingDir");a(HO,"repoHealthForEdit");a(fw,"runOnRepoHealth")});import{existsSync as BO,readFileSync as GO,realpathSync as WO}from"node:fs";import{isAbsolute as hw,join as gw,posix as KO,relative as VO,sep as zO}from"node:path";function mw(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function ZO(e,t){return{contracts:t.filter(r=>mw(r.spec)===e||mw(r.impl)===e).map(r=>r.id),theme:JO.test(e),acl:XO.test(e)}}function QO(e){return e.contracts.length===0&&!e.theme&&!e.acl}function eD(e,t,n,r,i=Date.now()){let s=e.write_health_seen??{},o=s[t]??{},c=new Set(o[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);o[n]={at:new Date(i).toISOString(),keys:[...c]},s[t]=o,e.write_health_seen=s}return l}function tD(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:
|
|
732
|
+
|
|
733
|
+
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
734
|
+
`)+`
|
|
735
|
+
|
|
736
|
+
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 nD(e,t){let n=VO(e,t);return!n||n.startsWith("..")||hw(n)?null:n.split(zO).join(KO.sep)}function rD(e){try{let t=GO(gw(e,Zi),"utf8"),{manifest:n}=ns(t);return n?.contracts??[]}catch{return[]}}async function yw(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=Be(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=hw(r)?r:gw(i,r),o=BO(s)?WO(s):gn(s),c=Qe(Dd(o)),l=nD(c,o);if(l===null)return 0;let d=ZO(l,rD(c));if(QO(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await Wt(c,{contracts:d.contracts});for(let y of g.findings)y.status==="open"&&u.push({key:`spec:${y.id}`,line:`spec-drift (${y.contract}): ${y.detail}`})}catch{}if(d.theme)try{let g=Vt(c);for(let y of g.findings)y.status==="open"&&u.push({key:`theme:${y.file}:${y.klass}`,line:`theme-class-drift: \`${y.klass}\` in ${y.file} \u2014 no token \`--color-${y.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=Kt(c);for(let y of g.findings)y.status==="open"&&u.push({key:`acl:${y.id}`,line:`table-acl-lint: \`${y.table}\` (created in ${y.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await q(),h=eD(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:qO,metric_value:1},{session_id:n,metric_key:YO,metric_value:h.length}),await Ge(p);let m=tD(h,l);return m!==null&&process.stdout.write(So(m)),0}catch{return 0}}var qO,YO,JO,XO,_w=_(()=>{"use strict";qt();Yt();hn();we();Pd();Eo();rt();qO="write_health_hook_runs",YO="write_health_hook_findings",JO=/\.(tsx?|jsx?|css)$/,XO=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;a(mw,"declPath");a(ZO,"routesForPath");a(QO,"routesAreEmpty");a(eD,"takeUnreported");a(tD,"formatWriteHealth");a(nD,"repoRelative");a(rD,"readContracts");a(yw,"runOnWriteHealth")});var Nw={};ee(Nw,{agentHostPidCandidates:()=>ct,closeTrackedSession:()=>Ew,effectiveConfig:()=>yn,grandparentPid:()=>Aw,isCaptureTool:()=>Md,recordGuardSignals:()=>Sw,runFlush:()=>bD,runHookStatus:()=>wD,runOnFileEdit:()=>gD,runOnFileWrite:()=>hD,runOnRepoHealth:()=>fw,runOnSessionStart:()=>dD,runOnToolUse:()=>fD,runOnWriteHealth:()=>yw,runSessionEndMetrics:()=>$d,runSyncConfig:()=>kD,writeIdentitySideChannel:()=>Ld});import{execFileSync as ww}from"node:child_process";import{existsSync as Ro,readFileSync as vw,realpathSync as iD}from"node:fs";import{writeFile as sD}from"node:fs/promises";import{homedir as kw}from"node:os";import{isAbsolute as Ao,join as gi,relative as xw}from"node:path";function Sw(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=kd(n),s=n.includes("review_changes")||n.includes("review_verdict"),o=Md(n);if(!i&&!s&&!o)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),s&&(l.reviewed_at=d),o&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function Md(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 Ew(e,t,n=Date.now()){lD(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 lD(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>To&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));t-i>To&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));t-i>To&&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>To&&delete e.sessions[n]}}function yn(e){if(e.config)return e.config;let t=K();return t===null?null:{api_key:t,endpoint:vo}}function Tw(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function dD(){try{let r=$b(_o(wo(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
|
|
737
|
+
`)}catch{}let e=await q();if(yn(e)===null)return 0;let t=await W(),n=Iw(t);if(n===null)return 0;Tw(e,n),await Ge(e);try{Ld(t,n)}catch{}try{let r=z();if(r!==null){let i=ar(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),o=fr(i,{hostPids:ct(),cwd:s}),c=qb(o?.snap??null,oi(sr(t)||null,n)),l=Yb(o?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
|
|
738
|
+
`)}}catch{}try{let r=tn(uD());if(cl(r)&&Ms(r)){let i=r.filter(s=>s.remedy==="run-install").map(s=>s.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
739
|
+
`)}}catch{}return 0}function uD(){try{let e=gi(kw(),".claude","settings.json");return Ro(e)?vw(e,"utf8"):null}catch{return null}}function Ld(e,t,n,r=cr()){let i=n??ct();if(i.length===0)return;let s=oi(sr(e)||null,t);if(s===null)return;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=sr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)rb({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:o,transcriptPath:c,model:l})}function Aw(){try{if(process.platform==="win32")return null;let e=ww("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 ct(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Aw();return n!==null&&n>1&&n!==t&&e.push(n),e}async function fD(){let e=await q();if(yn(e)===null)return 0;let t=await W(),n=Iw(t)??"unknown",r=Tw(e,n);r.tool_call_count+=1;try{let o=ct().filter(c=>ib(cr(),c,pD));n!=="unknown"&&o.length>0&&Ld(t,n,o)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Sw(e,n,i),Md(i)&&n!=="unknown"&&await V({event:"capture_taken",session_id:n,detail:i});let s=t.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let o=await Gl(r.transcript_path);o&&(r.token_count=o.total_tokens,await _D(e,r))}return await Ge(e),0}function mD(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
740
|
+
`);return`${t.prefix}${e.number} is already taken:
|
|
741
|
+
${n}
|
|
742
|
+
|
|
743
|
+
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
744
|
+
|
|
745
|
+
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 hD(){try{let e=await W();if((e.tool_name??"")!=="Write")return 0;let t=Be(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=Ao(t)?t:gi(n,t);if(Ro(r))return 0;let i=Qe(n),s=xw(i,gn(r));if(s.length===0||s.startsWith("..")||Ao(s))return 0;let o=await Gt(i,s);return!o.taken||o.namespace===null||process.stdout.write(mn(mD(o,o.namespace))),0}catch{return 0}}async function gD(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Be(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Ao(n)?n:gi(r,n),s=z();if(s===null)return 0;let o=ar(s);if(o.length===0)return 0;let c=fr(o,{hostPids:ct(),cwd:r});if(c===null)return 0;let l=Qe(r),d=Ro(i)?iD(i):gn(i),u=xw(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||Ao(u))return 0;let p=zb(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?yD(r):null,nowMs:Date.now()});return p===null||process.stdout.write(at(p)),0}catch{return 0}}function yD(e){try{let n=ww("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 _D(e,t){let n=El(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,s="ok";if(i>=n.handoff_at_pct/100?s="handoff_recommended":i>=n.warn_at_pct/100&&(s="warn"),t.last_advisory_status===s||(t.last_advisory_status=s,s==="ok"))return;let o=Math.round(i*100),c={session_id:t.session_id,status:s,tokens:r,ratio:Number(i.toFixed(3)),pct:o,thresholds:n,suggested_next:s==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await sD(gi(cn,`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)}
|
|
746
|
+
`)}s==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${o}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
747
|
+
`):process.stderr.write(`[maind] \u26D4 Token usage at ~${o}% (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.
|
|
748
|
+
`)}async function $d(e){try{let t=await q(),n=yn(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Ew(t,r),await Ge(t)),await Rw(n,aD)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
749
|
+
`)}}async function bD(){let e=await q(),t=yn(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 Rw(t,cD);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
750
|
+
`),n.ok?0:1}async function Rw(e,t){let n=await q();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=Gb(e.endpoint,e.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),o=await Promise.race([i,s]);if(o.ok){let c=await q();return c.pending_metrics=c.pending_metrics.slice(r.length),await Ge(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:o.error}}async function wD(){let e=await q(),t=yn(e),n=vD(),r=cl(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:El(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})),...Ms(n.findings)?{remedy:bw}:{}}},null,2)+`
|
|
751
|
+
`),r){process.stderr.write(`
|
|
752
|
+
[maind] Claude Code hook wiring is incomplete:
|
|
753
|
+
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
754
|
+
`);Ms(n.findings)&&process.stderr.write(` ${bw}
|
|
755
|
+
`)}return 0}function vD(){let e=gi(kw(),".claude","settings.json"),t=null;try{Ro(e)&&(t=vw(e,"utf8"))}catch{}return{settingsPath:e,findings:tn(t)}}async function kD(){let e=await q(),t=yn(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??oD,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(o){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${o instanceof Error?o.message:String(o)}
|
|
756
|
+
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
757
|
+
`);let o=await r.text().catch(()=>"");return o&&process.stderr.write(o.slice(0,500)+`
|
|
758
|
+
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
759
|
+
`),1}let s=i;return typeof s.warn_at_pct!="number"||typeof s.handoff_at_pct!="number"||typeof s.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
760
|
+
`),1):(e.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await Ge(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
761
|
+
`),0)}function Iw(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var oD,aD,cD,To,pD,bw,Fd=_(()=>{"use strict";ur();gr();qt();Yt();ot();ae();Zn();so();Ae();gd();yd();ao();we();hn();Eo();rt();Kn();ud();hd();Pd();_w();oD=process.env.MAIND_THRESHOLDS_ENDPOINT??Wn("get-context-thresholds"),aD=1500,cD=1e4,To=7*24*60*60*1e3;a(Sw,"recordGuardSignals");a(Md,"isCaptureTool");a(Ew,"closeTrackedSession");a(lD,"gcState");a(yn,"effectiveConfig");a(Tw,"getOrCreateSession");a(dD,"runOnSessionStart");a(uD,"readSettingsRaw");a(Ld,"writeIdentitySideChannel");pD=6e4;a(Aw,"grandparentPid");a(ct,"agentHostPidCandidates");a(fD,"runOnToolUse");a(mD,"denyReason");a(hD,"runOnFileWrite");a(gD,"runOnFileEdit");a(yD,"currentGitBranch");a(_D,"maybeEmitAdvisory");a($d,"runSessionEndMetrics");a(bD,"runFlush");a(Rw,"flushPending");a(wD,"runHookStatus");bw="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";a(vD,"readHookWiring");a(kD,"runSyncConfig");a(Iw,"sessionIdOf")});function Cw(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Ow=_(()=>{"use strict";a(Cw,"resolveConnection")});function Pw(e,t,n,r=Date.now()){let i=t===null?null:ed(t),s=rd(e,i,{repoRoot:n,nowMs:r});return s.length===0?null:{slices:s,context_ok:i!==null}}var Dw,jd=_(()=>{"use strict";ur();Dw=2e3;a(Pw,"buildCostPayload")});function Lw(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!Mw.test(n))return null;let r=n.toLowerCase();return t!==null&&Mw.test(t)&&r!==t.toLowerCase()?null:r}var Mw,$w=_(()=>{"use strict";Mw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Lw,"snapshotSessionId")});async function Fw(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await ci(e.transcriptPath),i=e.resolveRoot?id(r,e.resolveRoot):null,s=i&&e.projectKeyOf?e.projectKeyOf(i):null,o=i!==null&&s!==null&&s!==e.projectKey;o&&n.catch(()=>{});let[c,l,d]=await Promise.all([Kl(e.transcriptPath,{turns:r}),sd(e.transcriptPath),o?e.fetchContext(s):n]),u=i??e.repoRoot;if(e.sessionId&&(c.session_id=e.sessionId,l.session_id=e.sessionId),c.maind_connected=e.connection(c.maind_connected==="connected",t()),!c.session_id)return{posted:!1,contextOk:d!==null,sentSlices:!1};let p=Pw(r,d,u,t()),h=ql(c,l,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",p);return await e.post(h,p!==null),{posted:!0,contextOk:p?.context_ok??d!==null,sentSlices:p!==null}}var jw=_(()=>{"use strict";ur();jd();a(Fw,"ingestSessionEnd")});var Bw={};ee(Bw,{runOnSessionEnd:()=>CD});import{execFileSync as Ud}from"node:child_process";function SD(e,t){try{let n=z(),r=n!==null&&!$l(process.env,He()),i=null;if(n!==null){let s=fr(ar(n),{hostPids:ct(),cwd:process.cwd()});if(s){let o=Date.parse(s.snap.written_at);i=Number.isFinite(o)?Math.max(0,t-o):null}}return Cw({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function ED(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let r=z();if(r!==null){let i=fr(ar(r),{hostPids:ct(),cwd:process.cwd()}),s=Lw(i?.snap,e);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function TD(){try{let e=Ud("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function AD(e){let t=Uw.get(e);if(t!==void 0)return t;let n=null;try{let r=Ud("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return Uw.set(e,n),n}function RD(e){let t=Hw.get(e);if(t!==void 0)return t;let n=null;try{let r=Ud("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=vs(r))}catch{n=null}return Hw.set(e,n),n}async function ID(e,t,n,r){if(n===null)return null;try{return await tt("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:j,timeoutMs:Dw})}catch{return null}}async function ND(e,t,n,r,i){let s=fetch(xD,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":j},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=zl(Vl(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
|
|
762
|
+
`)}).catch(()=>{}),o=new Promise(c=>setTimeout(c,r));await Promise.race([s,o])}async function CD(){try{for(let i of ct())sb(cr(),i)}catch{}let e=K();if(!e)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=sr(t);if(r)try{let i=ne(),s=ED(oi(r,n)),o=z();await Fw({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:o,coordSessionId:s,repoRoot:TD(),resolveRoot:AD,projectKeyOf:RD,fetchContext:a(c=>ID(e,i,c,s),"fetchContext"),post:a((c,l)=>ND(e,i,c,1500,l),"post"),connection:SD})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
763
|
+
`)}return await $d(n),0}var xD,Uw,Hw,Gw=_(()=>{"use strict";ur();Qn();ae();on();gd();yd();we();Fd();Fl();so();Ae();ao();Te();Ow();jd();$w();jw();xD=vo;a(SD,"connectionVerdict");a(ED,"presenceSessionId");a(TD,"sessionRepoRoot");Uw=new Map;a(AD,"gitRootOf");Hw=new Map;a(RD,"projectKeyOfRoot");a(ID,"fetchCostContext");a(ND,"postWithTimeout");a(CD,"runOnSessionEnd")});function OD(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 Ww(e,t,n=process.stdout){let r=OD(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
764
|
+
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of Ps)s.push(await pl(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
765
|
+
`);let o=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
766
|
+
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
767
|
+
`),0):(await an({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
768
|
+
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
769
|
+
flip: maind-mcp-bridge guard mode <warn|block>
|
|
770
|
+
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
771
|
+
check: maind-mcp-bridge guard status
|
|
772
|
+
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
773
|
+
`),o&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
774
|
+
`),c?1:0)}var Kw=_(()=>{"use strict";Zn();fl();nt();a(OD,"parseGuardInstallFlags");a(Ww,"runGuardInstall")});import{existsSync as Vw}from"node:fs";import{appendFile as DD,mkdir as PD,readFile as MD}from"node:fs/promises";import{join as LD}from"node:path";function Hd(e,t=Io){return LD(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function yr(e,t=Io){return Vw(Hd(e,t))}async function St(e,t,n=Io){try{await PD(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await DD(Hd(e,n),r+`
|
|
775
|
+
`,{mode:384})}catch{}}async function _n(e,t=Io){try{let n=Hd(e,t);if(!Vw(n))return[];let r=[];for(let i of(await MD(n,"utf8")).split(`
|
|
776
|
+
`))if(i.trim())try{let s=JSON.parse(i),o=s.t,c=s.k,l=s.v;if(typeof o!="number"||!Number.isFinite(o)||typeof c!="string"||!$D.has(c))continue;r.push(typeof l=="string"?{t:o,k:c,v:l}:{t:o,k:c})}catch{}return r}catch{return[]}}var Io,$D,yi=_(()=>{"use strict";st();Io=Al,$D=new Set(["fail","ok","nudge","skip","prompt"]);a(Hd,"triggerLogPath");a(yr,"hasTriggerLog");a(St,"appendTriggerEvent");a(_n,"loadTriggerEvents")});import{existsSync as FD}from"node:fs";import{mkdir as jD,readFile as UD,rename as HD,writeFile as BD}from"node:fs/promises";import{dirname as GD,join as WD}from"node:path";function Bd(e=process.env){let t=K();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??ni,keyFp:Gn(t)}}async function Gd(e,t=Date.now(),n=No){try{if(!FD(n))return null;let r=JSON.parse(await UD(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let i=Date.parse(r.fetched_at);if(Number.isNaN(i))return null;let s=r.policy;return{policy:xo([s?.difficulty,s?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<KD}}catch{return null}}async function zD(e,t,n,r){try{await jD(GD(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},s=`${r}.tmp`;await BD(s,JSON.stringify(i,null,2),{mode:384}),await HD(s,r)}catch{}}async function qD(){let e=K();if(e===null)return null;let t=null;try{t=z()}catch{t=null}let n=await tt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:YD(),projectKey:t,bridgeVersion:j,timeoutMs:VD});if(n===null)return null;try{return xo(JSON.parse(n))}catch{return null}}async function _r(e,t={}){let n=t.nowMs??Date.now(),r=t.file??No,i=t.identity===void 0?Bd():t.identity;if(i===null)return mi;let s=await Gd(i,n,r);if(s?.fresh)return s.policy;if(e){let o=await(t.fetcher??qD)();if(o!==null)return await zD(i,o,n,r),o}return s?.policy??mi}function YD(){try{return ne()}catch{return null}}var No,KD,VD,_i=_(()=>{"use strict";gr();Yt();ae();Ae();Te();on();st();No=WD(Ne,"trigger-policy.json"),KD=12*60*60*1e3,VD=3e3;a(Bd,"currentIdentity");a(Gd,"readCachedPolicy");a(zD,"writeCachedPolicy");a(qD,"fetchTriggerPolicy");a(_r,"resolveTriggerPolicy");a(YD,"safeDeviceId")});var qw={};ee(qw,{runGuard:()=>eP});import{existsSync as JD,readFileSync as XD}from"node:fs";import{homedir as zw}from"node:os";import{join as ZD}from"node:path";async function eP(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Ww(n,zw());case"status":return nP();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
777
|
+
`),1):(await an({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
778
|
+
`),0)}case"off":return await an({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
779
|
+
`),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>
|
|
780
|
+
`),1):(await an({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
781
|
+
`),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>
|
|
782
|
+
`),1):(await an(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.
|
|
783
|
+
`:`${t} trigger disabled on this machine (your convention prefs are unchanged).
|
|
784
|
+
`),0)}case"skip":return tP(n);default:return process.stdout.write(QD),t===void 0||t==="--help"||t==="-h"?0:1}}async function tP(e){let t=null,n=null,r="consult";for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"?n=e[++o]??null:e[o]==="--kind"&&(r=e[++o]??"");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]
|
|
785
|
+
`),1;let i=n.trim().slice(0,500);if(r!=="consult")return await St(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await V({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
|
|
786
|
+
logged (auditable) in ${ln}
|
|
787
|
+
`),0;let s=await it(t);return await me(t,{...s,override_reason:i}),await V({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.
|
|
788
|
+
logged (auditable) in ${ln}
|
|
789
|
+
`),0}async function nP(){let e=le(),t=ZD(zw(),".claude","settings.json"),n=null;try{JD(t)&&(n=XD(t,"utf8"))}catch{}let r=tn(n,{},Ps),i=await i_(),s=Bd(),o=s?await Gd(s):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,policy:o?{difficulty:o.policy.difficulty,capture:o.policy.capture,fetched_at:o.fetchedAt,fresh:o.fresh}:null,policy_file:No},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:ln},null,2)+`
|
|
790
|
+
`);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(`
|
|
791
|
+
[maind] guard hook wiring is incomplete:
|
|
792
|
+
`);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
|
|
793
|
+
`);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 QD,Yw=_(()=>{"use strict";Zn();nt();Kw();ot();st();yi();_i();QD=["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(`
|
|
794
|
+
`);a(eP,"runGuard");a(tP,"runGuardSkip");a(nP,"runGuardStatus")});var Zw={};ee(Zw,{bashOutputOf:()=>Jw,consultedAtOf:()=>Co,outcomeFromHook:()=>Xw,runGuardDifficulty:()=>iP});function Jw(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(`
|
|
795
|
+
`):null,interrupted:t.interrupted===!0}}function Xw(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"?Jw(e.tool_response):{output:null,interrupted:!1},s=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:i.output,isInterrupt:e.is_interrupt===!0||i.interrupted,isSubagent:typeof s=="string"&&s.length>0}}}function Co(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 rP(e,t,n){if(!yr(e))return;let r=await _n(e);if(!r.some(o=>o.k==="fail"&&o.v===t))return;let i=mr(r,null,n);await St(e,{t:n,k:"ok",v:t});let s=i.chain;s!==null&&s.failures.length>=4&&!i.resolved&&s.lastVerb===t&&await V({event:"difficulty_resolved",session_id:e,detail:String(s.failures.length)})}async function iP(){try{let e=le();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=Xw(t);if(r===null)return 0;let i=xd(r.outcome);if(i===null)return 0;let s=Date.now();if(i.kind==="ok")return await rP(n,i.verb,s),0;await St(n,{t:s,k:"fail",v:i.verb});let o=await _n(n),c=mr(o,Co(await q(),n),s);if(!Td(c)||c.chain===null)return 0;let l=await _r(!0);if(!e.difficulty||!hr(l.difficulty))return 0;await St(n,{t:s,k:"nudge"});let d=hi(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?cw(d):So(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await V({event:"difficulty_nudge",session_id:n,cwd:u,project_key:z()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Wd=_(()=>{"use strict";gr();we();hn();rt();Ae();nt();ot();yi();_i();a(Jw,"bashOutputOf");a(Xw,"outcomeFromHook");a(Co,"consultedAtOf");a(rP,"recordSuccess");a(iP,"runGuardDifficulty")});var nv={};ee(nv,{decideDifficultyGate:()=>tv,decideGate:()=>ev,runGuardGate:()=>aP});function ev(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:Qw(n)}:(n.deny_count??0)>=Oo?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. "+Qw(n)}:{kind:"deny",reason:sP(e.sessionId,n)}}function Qw(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 sP(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:
|
|
796
|
+
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
797
|
+
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
798
|
+
After ${Oo} denies this gate downgrades itself to warn.`}function tv(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)>=Oo?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. "+hi(n.chain)}:{kind:"deny",reason:oP(n,e.sessionId)}}function oP(e,t){return`[maind guard | block] Edit denied \u2014 ${Cd(e.chain)}. Two exits:
|
|
799
|
+
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.
|
|
800
|
+
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
|
|
801
|
+
After ${Oo} denies this gate downgrades itself to warn.`}async function aP(){try{let e=le();if(e.mode==="off")return 0;let t=await W(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await it(r),s=Co(await q(),r),o=s!==null,c=ev({mode:e.mode,session:i,consulted:o,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=z()??void 0;if(c.kind==="deny")return process.stdout.write(mn(c.reason)),await me(r,{...i,deny_count:(i.deny_count??0)+1}),await V({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(at(c.context)),await me(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await V({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&yr(r)){let u=mr(await _n(r),s,Date.now()),p=u.open?tv({mode:e.mode,enabled:e.difficulty,denyCapable:Id((await _r(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(mn(p.reason)),await me(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await V({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(at(p.context)),await me(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await me(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var Oo,rv=_(()=>{"use strict";gr();we();hn();rt();Ae();nt();Wd();ot();st();yi();_i();Oo=3;a(ev,"decideGate");a(Qw,"warnText");a(sP,"denyText");a(tv,"decideDifficultyGate");a(oP,"difficultyDenyText");a(aP,"runGuardGate")});var sv={};ee(sv,{decideStopGate:()=>iv,runGuardStop:()=>lP});function iv(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function lP(){try{let e=le();if(e.mode==="off"||!e.stopGate)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await it(n),i=(await q()).guard_signals?.[n]?.reviewed_at!==void 0;return iv({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:cP})),await me(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var cP,ov=_(()=>{"use strict";we();rt();nt();ot();st();a(iv,"decideStopGate");cP="[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.";a(lP,"runGuardStop")});var lv={};ee(lv,{capturedAtOf:()=>av,decideCapture:()=>cv,runGuardCapture:()=>dP});function av(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 cv(e){if(e.stopHookActive||!hr(e.policy.capture))return null;let t=Ad(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Od(t)}}async function dP(){try{let e=le();if(e.mode==="off"||!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!yr(n))return 0;let r=cv({events:await _n(n),capturedAtMs:av(await q(),n),policy:await _r(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await St(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await V({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var dv=_(()=>{"use strict";gr();we();rt();nt();ot();yi();_i();a(av,"capturedAtOf");a(cv,"decideCapture");a(dP,"runGuardCapture")});import{appendFile as uP,mkdir as pP,readFile as pv,rename as fv,writeFile as mv}from"node:fs/promises";import{homedir as hv}from"node:os";import{join as gv}from"node:path";function yv(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},s=new Map,o=1/0,c=-1/0;for(let d of e){d.at<o&&(o=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=s.get(d.convention_id);(p===void 0||d.convention_version>p)&&s.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(o).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function bn(){return gv(hv(),".maind","gateway","attest-spool.jsonl")}async function Kd(e){let t=K();if(t===null)return!1;let n=await tt("gateway_attest",{...e},{apiKey:t,deviceId:ne(),projectKey:e.project_key??null,bridgeVersion:j,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function _v(e){try{await pP(gv(hv(),".maind","gateway"),{recursive:!0}),await uP(bn(),JSON.stringify(e)+`
|
|
802
|
+
`,{mode:384}),await fP()}catch{}}async function fP(){try{let t=(await pv(bn(),"utf8")).split(`
|
|
803
|
+
`).filter(r=>r.trim());if(t.length<=uv)return;let n=`${bn()}.${process.pid}.tmp`;await mv(n,t.slice(-uv).join(`
|
|
804
|
+
`)+`
|
|
805
|
+
`,{mode:384}),await fv(n,bn())}catch{}}async function bv(){let e;try{e=(await pv(bn(),"utf8")).split(`
|
|
806
|
+
`).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 Kd(i)||(n=!0,t.push(r))}try{let r=`${bn()}.${process.pid}.tmp`;await mv(r,t.length>0?t.join(`
|
|
807
|
+
`)+`
|
|
808
|
+
`:"",{mode:384}),await fv(r,bn())}catch{}}var uv,wv=_(()=>{"use strict";ae();on();Te();uv=256;a(yv,"aggregateWindow");a(bn,"attestSpoolPath");a(Kd,"postAttestation");a(_v,"spoolAttestation");a(fP,"capSpool");a(bv,"flushAttestSpool")});function bi(e=process.env,t=He()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Do(e=process.env,t=He()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function vv(e,t=et()){let n={};try{let i=await Q(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await Y(t,JSON.stringify(r,null,2)+`
|
|
809
|
+
`,384)}async function kv(e,t=et()){await vv({gateway_mode:e},t)}async function xv(e,t=et()){await vv({gateway_attest:e},t)}function Sv(e=process.env,t=He()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Vd=_(()=>{"use strict";Qn();Ie();a(bi,"resolveGatewayMode");a(Do,"resolveGatewayAttest");a(vv,"writeGatewayConfigPatch");a(kv,"writeGatewayMode");a(xv,"writeGatewayAttest");a(Sv,"resolveShaProofMode")});function Tv(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,s=i.gateway_gate;if(typeof s!="object"||s===null)continue;let o=s;if(o.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"&&mP.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(o.servers)?o.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let h=Array.isArray(o.deny_tools)?o.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of h){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function hP(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Av(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)hP(s,e,t)&&(i===null||Ev[s.severity]>Ev[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Rv(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 mP,Ev,zd=_(()=>{"use strict";mP=new Set(["required","recommended","info"]);a(Tv,"extractGatewayRules");Ev={required:2,recommended:1,info:0};a(hP,"ruleMatches");a(Av,"decideToolCall");a(Rv,"policyDenyText")});import{mkdirSync as gP,readFileSync as yP,renameSync as _P,writeFileSync as bP}from"node:fs";import{homedir as wP}from"node:os";import{dirname as vP,join as kP}from"node:path";function Iv(){return kP(wP(),".maind","gateway","policy-cache.json")}function Po(e,t,n=new Date().toISOString()){try{let r={version:qd,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=Iv();gP(vP(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;bP(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),_P(s,i)}catch{}}function Mo(e){try{let t=yP(Iv(),"utf8"),n=JSON.parse(t);return n.version!==qd||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:qd,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var qd,Yd=_(()=>{"use strict";qd=1;a(Iv,"policyCachePath");a(Po,"writePolicyCache");a(Mo,"readPolicyCache")});function wi(e=process.env){let t=e.MAIND_MCP_URL??ni,n=K();return{mcpUrl:t,keyFp:n?Gn(n):"anon"}}async function Lo(e=6e3){let t=K();if(t===null)return null;let n=null;try{n=z()}catch{n=null}let r=await tt("get_conventions",{},{apiKey:t,deviceId:ne(),projectKey:n,bridgeVersion:j,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Tv(i)}var Jd=_(()=>{"use strict";Yt();ae();on();Ae();Te();zd();a(wi,"policyIdentity");a(Lo,"fetchGatewayRules")});function vi(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function xP(e){if(vi(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function SP(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:vi(e)?{action:"skip",reason:"already-wrapped"}:xP(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Nv(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],s=typeof e.env=="object"&&e.env!==null?e.env:void 0,o=s||t.env?{...s??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return o&&(c.env=o),c}function Cv(e){if(!vi(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function Ov(e){return Object.entries(e).map(([t,n])=>{let r=SP(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Dv=_(()=>{"use strict";a(vi,"isGatewayWrapped");a(xP,"isMaindProxyEntry");a(SP,"classifyServer");a(Nv,"wrapServerEntry");a(Cv,"unwrapServerEntry");a(Ov,"planRewrites")});var jv={};ee(jv,{runGatewayInstall:()=>NP,runGatewayUninstall:()=>CP});import{existsSync as EP,readFileSync as TP}from"node:fs";import{homedir as AP}from"node:os";import{join as Pv}from"node:path";import{createInterface as RP}from"node:readline";function Mv(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 Lv(){return[{label:"Claude Code (project .mcp.json)",path:Pv(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Pv(AP(),".claude.json")}]}async function $v(e){let t=RP({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 Fv(e){let t=IP(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 IP(e){try{return EP(e)?TP(e,"utf8"):null}catch{return null}}async function NP(e){let t=Mv(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
810
|
+
`),2;let n=Fe({entryPath:je(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of Lv()){let s=Fv(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
811
|
+
`);continue}let o=Ov(s.servers);for(let c of o){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
812
|
+
`);continue}if(!(t.yes||await $v(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
813
|
+
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
814
|
+
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
815
|
+
`);continue}s.servers[c.key]=Nv(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
816
|
+
`)}!t.dryRun&&o.some(c=>c.action==="wrap")&&await Y(i.path,JSON.stringify(s.raw,null,2)+`
|
|
817
|
+
`,384)}return process.stderr.write(r>0?`
|
|
818
|
+
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
819
|
+
`:`
|
|
820
|
+
Nothing to wrap.
|
|
821
|
+
`),0}async function CP(e){let t=Mv(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
822
|
+
`),2;let n=0;for(let r of Lv()){let i=Fv(r.path);if(i===null)continue;let s=!1;for(let[o,c]of Object.entries(i.servers)){if(!vi(c)||!(t.yes||await $v(`Unwrap MCP server '${o}' in ${r.label}?`)))continue;let d=Cv(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${o} \u2014 wrapped shape unrecognized, left untouched
|
|
823
|
+
`);continue}i.servers[o]=d,s=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${o}
|
|
824
|
+
`)}!t.dryRun&&s&&await Y(r.path,JSON.stringify(i.raw,null,2)+`
|
|
825
|
+
`,384)}return process.stderr.write(n>0?`
|
|
826
|
+
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
827
|
+
`:`
|
|
828
|
+
Nothing wrapped \u2014 nothing to restore.
|
|
829
|
+
`),0}var Uv=_(()=>{"use strict";Ie();qn();Dv();a(Mv,"parseFlags");a(Lv,"targets");a($v,"confirm");a(Fv,"loadConfig");a(IP,"readFileSafeSync");a(NP,"runGatewayInstall");a(CP,"runGatewayUninstall")});var Hv={};ee(Hv,{runGatewayAttest:()=>DP,runGatewayMode:()=>OP,runGatewayPolicy:()=>LP});async function OP(e){let t=e[0];if(t===void 0){let n=bi(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
830
|
+
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
831
|
+
`),2):(await kv(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
832
|
+
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
833
|
+
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
834
|
+
`)),0)}async function DP(e){let t=e[0];if(t===void 0){let n=Do(),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)":""}.
|
|
835
|
+
`+(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.
|
|
836
|
+
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
837
|
+
`),2):(await xv(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.
|
|
838
|
+
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
839
|
+
`),0)}function PP(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
840
|
+
`;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})
|
|
841
|
+
`}return t}function MP(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 LP(e){let t=e.includes("--refresh"),n=bi(),r=wi();if(t){let s=await Lo();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
842
|
+
`):(Po(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
|
|
843
|
+
`))}let i=Mo(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
844
|
+
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
845
|
+
`),0):(process.stdout.write(`maind: policy from cache (${MP(i)}, ${r.mcpUrl}):
|
|
846
|
+
`),process.stdout.write(PP(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.
|
|
847
|
+
`),0)}var Bv=_(()=>{"use strict";Vd();Yd();Jd();a(OP,"runGatewayMode");a(DP,"runGatewayAttest");a(PP,"renderRules");a(MP,"cacheAge");a(LP,"runGatewayPolicy")});var zv={};ee(zv,{gatewayEventsFile:()=>Kv,parseGatewayArgs:()=>Vv,runGateway:()=>GP});import{spawn as $P}from"node:child_process";import{appendFile as FP,mkdir as jP}from"node:fs/promises";import{homedir as Gv}from"node:os";import{basename as UP,join as Wv}from"node:path";import{createInterface as HP}from"node:readline";function Kv(){return Wv(Gv(),".maind","gateway","events.jsonl")}async function BP(e){try{let t=Kv();await jP(Wv(Gv(),".maind","gateway"),{recursive:!0}),await FP(t,JSON.stringify(e)+`
|
|
848
|
+
`,{mode:384})}catch{}}function Vv(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let s=e[r+1];if(!s)return null;t.add(s),r+=2;continue}if(i==="--label"){let s=e[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=e[r+1];return s?{denyTools:t,label:n,command:s,args:e.slice(r+2)}:null}return null}return null}async function GP(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:w,runGatewayUninstall:x}=await Promise.resolve().then(()=>(Uv(),jv));return e[0]==="install"?w(e.slice(1)):x(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:w,runGatewayMode:x,runGatewayPolicy:I}=await Promise.resolve().then(()=>(Bv(),Hv));return e[0]==="mode"?x(e.slice(1)):e[0]==="attest"?w(e.slice(1)):I(e.slice(1))}let t=Vv(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
849
|
+
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
850
|
+
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
851
|
+
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
852
|
+
maind-mcp-bridge gateway policy [--refresh]
|
|
853
|
+
maind-mcp-bridge gateway attest [on|off]
|
|
854
|
+
EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
855
|
+
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
856
|
+
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
857
|
+
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
858
|
+
`),2;let{denyTools:n,label:r,command:i,args:s}=t,o=r??UP(i),c=bi(),l=Sv(),d=l==="off"?null:xi(),u=c==="off"?[]:Mo(wi())?.rules??[];c!=="off"&&Lo().then(w=>{w!==null&&(u=w,Po(wi(),w))}).catch(()=>{});let p=[],h=Do()&&K()!==null&&c!=="off",m=null;try{m=z()}catch{m=null}let g=a(w=>{BP(w),h&&p.push(w)},"record"),y=a(async()=>{if(!h)return;let w=yv(p.splice(0),c,o,m);w!==null&&(await Kd(w)||await _v(w))},"attestAndReset");h&&bv().catch(()=>{});let v=setInterval(()=>{y()},30*6e4);v.unref();let b=$P(i,s,{stdio:["pipe","pipe","inherit"]});b.stdout.pipe(process.stdout),b.on("error",w=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(w)}
|
|
859
|
+
`),process.exitCode=1});let k=HP({input:process.stdin,terminal:!1});k.on("line",w=>{let x=pu(w);if(x.kind==="request"&&x.method==="tools/call"&&x.toolName){if(n.has(x.toolName)&&x.id!==void 0){process.stdout.write(vn(x.id,x.toolName)+`
|
|
860
|
+
`),g(jo("deny",o,x.toolName,Date.now()));return}let I=Av(x.toolName,o,u,c);if(I.kind==="deny"&&x.id!==void 0){process.stdout.write(vn(x.id,x.toolName,Rv(x.toolName,I.rule))+`
|
|
861
|
+
`),g(Uo("policy_deny",o,x.toolName,Date.now(),I.rule.conventionId,I.rule.conventionVersion));return}(I.kind==="warn"||I.kind==="deny")&&g(Uo("policy_warn",o,x.toolName,Date.now(),I.rule.conventionId,I.rule.conventionVersion));let F=Si(w,d);if(F.length>0){let B=F.find(U=>U.verdict==="fabricated");if(B!==void 0&&l==="enforce"&&c==="enforce"&&x.id!==void 0&&B!==void 0&&x.id!==void 0){process.stdout.write(vn(x.id,x.toolName,kn(B,!0))+`
|
|
862
|
+
`),g(Ho("sha_deny",o,x.toolName,Date.now()));return}let C=B??F[0];process.stderr.write(`[maind gateway] ${kn(C,!1)}
|
|
863
|
+
`),g(Ho("sha_warn",o,x.toolName,Date.now()))}g(jo("tool_call",o,x.toolName,Date.now()))}b.stdin.write(w+`
|
|
864
|
+
`)}),k.on("close",()=>{b.stdin.end()});let E=await new Promise(w=>{b.on("exit",(x,I)=>{w(x??(I?1:0))})});return clearInterval(v),await y(),E}var qv=_(()=>{"use strict";Bo();wv();Vd();zd();Go();Yd();Jd();ae();Ae();a(Kv,"gatewayEventsFile");a(BP,"logEvent");a(Vv,"parseGatewayArgs");a(GP,"runGateway")});var ru={};ee(ru,{MAX_ENTRIES:()=>Xd,TTL_MS:()=>eu,crossSessionDir:()=>tu,decideCrossSession:()=>Xv,parseSessionDb:()=>Jv,pruneDb:()=>nu,runGuardCrossCheck:()=>ZP,runGuardCrossObserve:()=>XP,staleReason:()=>Zd});import{mkdir as WP,readFile as KP,readdir as VP,stat as Yv,unlink as zP,writeFile as qP}from"node:fs/promises";import{homedir as YP}from"node:os";import{join as Qd}from"node:path";function tu(){return Qd(YP(),".maind","cross-session")}function Jv(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[s,o]of Object.entries(n.files)){if(typeof o!="object"||o===null)continue;let c=o;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[s]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[s,o]of Object.entries(n.warned))typeof o=="number"&&Number.isFinite(o)&&(i[s]=o);return{files:r,warned:i}}function nu(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=eu);return n.length>Xd&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-Xd)),{files:Object.fromEntries(n),warned:e.warned}}function Xv(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Zd(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 Zv(e){let t=tu();return await WP(t,{recursive:!0}),Qd(t,`${e}.json`)}async function Qv(e,t){try{let n=await KP(await Zv(e),"utf8");return nu(Jv(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function ek(e,t){try{await qP(await Zv(e),JSON.stringify(t),{mode:384})}catch{}}async function JP(e){try{let t=tu();for(let n of await VP(t)){if(!n.endsWith(".json"))continue;let r=Qd(t,n),i=await Yv(r).catch(()=>null);i&&e-i.mtimeMs>eu&&await zP(r).catch(()=>{})}}catch{}}async function tk(e){try{return(await Yv(e)).mtimeMs}catch{return}}async function XP(e,t=Date.now()){try{if(le().mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=Be(r);if(!i||!s)return 0;let o=await tk(s);if(o===void 0)return 0;let c=await Qv(i,t);return c.files[s]={m:o,t},delete c.warned[s],await ek(i,nu(c,t)),await JP(t),0}catch{return 0}}async function ZP(e,t=Date.now()){try{let n=le();if(n.mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=Be(r);if(!i||!s)return 0;let o=await Qv(i,t),c=Xv(o.files[s]?.m,await tk(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(mn(Zd(s,c))+`
|
|
865
|
+
`),await V({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(o.warned[s]===c.current||(process.stdout.write(at(Zd(s,c))+`
|
|
866
|
+
`),o.warned[s]=c.current,await ek(i,o),await V({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var eu,Xd,iu=_(()=>{"use strict";we();hn();nt();ot();eu=48*3600*1e3,Xd=500;a(tu,"crossSessionDir");a(Jv,"parseSessionDb");a(nu,"pruneDb");a(Xv,"decideCrossSession");a(Zd,"staleReason");a(Zv,"dbPath");a(Qv,"loadDb");a(ek,"saveDb");a(JP,"sweepStaleSessionFiles");a(tk,"fileMtime");a(XP,"runGuardCrossObserve");a(ZP,"runGuardCrossCheck")});var su={};ee(su,{INDEX_REFRESH_WORKER:()=>nk,acquireLock:()=>eo,releaseLock:()=>ii,runIndexRefreshWorker:()=>iM,runOnIndexRefresh:()=>rM});import{spawn as QP}from"node:child_process";import{existsSync as eM}from"node:fs";import{join as tM}from"node:path";function nM(e){return tM(e,".maind","code-index.sqlite")}async function rM(){try{let e=await W(),t=fe(typeof e.cwd=="string"?e.cwd:process.cwd());if(!eM(nM(t))||!eo(t))return 0;let n=process.argv[1];if(n===void 0)return ii(t),0;QP(process.execPath,[n,nk,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function iM(){let e=process.argv[3]??fe();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Sl(),Oy)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{ii(e)}return 0}var nk,ou=_(()=>{"use strict";we();sn();Nl();nk="index-refresh-run";a(nM,"indexDbPath");a(rM,"runOnIndexRefresh");a(iM,"runIndexRefreshWorker")});import{randomUUID as sM}from"node:crypto";import{createInterface as ST}from"node:readline";var ik=[["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"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function sk(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of ik)if(t.includes(n))return r;return null}a(sk,"mapClientInfoNameToFamily");function uu(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Fo(t)||t.method!=="initialize")return null;let n=t.params;if(!Fo(n))return null;let r=n.clientInfo;if(!Fo(r))return null;let i=r.name,s=sk(typeof i=="string"?i:null);if(s===null)return null;let o=r.version,c=typeof o=="string"&&o.length>0?o.slice(0,64):null;return{family:s,version:c}}a(uu,"tryExtractInitializeClient");function Fo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Fo,"isRecord");Bo();Go();function Wo(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let s=JSON.parse(t);return Array.isArray(s)?s:[s]}catch{return[]}let n=[],r=[],i=a(()=>{if(r.length===0)return;let s=r.join(`
|
|
867
|
+
`).trim();if(r=[],s.length!==0)try{n.push(JSON.parse(s))}catch{}},"flush");for(let s of t.split(`
|
|
868
|
+
`)){let o=s.endsWith("\r")?s.slice(0,-1):s;if(o===""){i();continue}o.startsWith("data:")&&r.push(o.slice(5).replace(/^\s/,""))}return i(),n}a(Wo,"rpcMessagesOf");function _u(e,t){for(let n of Wo(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:{},o=(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:o?.text??""}}return null}a(_u,"parseCloudToolResponse");Yt();var ET="https://mcp.maind.dev/mcp",Kr=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{a(this,"BridgeReauthNeeded")}},_s=class{static{a(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;onSessionReady;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;pendingFrame=null;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=Gn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=TT(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=AT(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;let s=t.carry??null;s!==null&&(this.initFrame=s.initFrame,this.clientFamily===null&&(this.clientFamily=s.clientFamily),this.clientVersion===null&&(this.clientVersion=s.clientVersion),this.replayFrame=s.pendingFrame),this.shaRepoRoot=xi(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??ET}async run(t=Yc()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r)return;let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let u=uu(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Wr(t)&&(this.initFrame=t);let r=NT(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=Si(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),h=p??u[0];if(p!==void 0&&gu(p)&&r.id!==null){let m=kn(p,!0);process.stderr.write(`[maind] ${m}
|
|
869
|
+
`);let g=r.params?.name;process.stdout.write(vn(r.id,typeof g=="string"?g:"unknown",m)+`
|
|
870
|
+
`);return}i=kn(h,!1),process.stderr.write(`[maind] ${i}
|
|
871
|
+
`)}}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+`
|
|
872
|
+
`);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Wr(t)&&await this.recoverSession();let o=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:o,body:t})}catch(u){let p=gs(t);if(this.serveInitializeFromCache(t,p))return;ys(p,-32603,`bridge network error: ${sg(u)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.ok&&!this.connectionOkRecorded&&(this.connectionOkRecorded=!0,this.recordOutcome("ok",null)),c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!Wr(t)){let u=await c.text().catch(()=>"");if(ig(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=gs(t);ys(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=gs(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;ys(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(s&&this.localRouter){let u=d.startsWith("text/event-stream")?await zc(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
873
|
+
`);return}if(Wr(t)){let u=d.startsWith("text/event-stream")?await zc(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
874
|
+
`);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await zc(c):await c.text(),p=IT(u,i);p.trim().length>0&&process.stdout.write(p+`
|
|
875
|
+
`);return}if(d.startsWith("text/event-stream"))await RT(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
876
|
+
`)}}}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 Kr(OT(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let o=gs(n);ys(o,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(t,n){try{this.onConnectionOutcome?.(t,n)}catch{}}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),s=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return DT(s)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,s=await this.postCloudToolCall(t,n,i);if(s.kind!=="session_lost")return s;if(!await this.recoverSession())return{kind:"http_error",status:404,body:s.body.slice(0,500)};let o=await this.postCloudToolCall(t,n,i);return o.kind==="session_lost"?{kind:"http_error",status:404,body:o.body.slice(0,500)}:o}async postCloudToolCall(t,n,r){this.cloudFrameId+=1;let i=`maind-bridge-${this.cloudFrameId}`,s=JSON.stringify({jsonrpc:"2.0",id:i,method:"tools/call",params:{name:t,arguments:n}});try{let o=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:s,signal:AbortSignal.timeout(r)}),c=o.headers.get("mcp-session-id");c&&c!==this.sessionId&&(this.sessionId=c);let l=await o.text();return o.status===404&&ig(l)?{kind:"session_lost",body:l}:o.ok?_u(l,i)??{kind:"transport_error",message:`the response carried no answer to ${i}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:o.status,body:l.slice(0,500)}}catch(o){return{kind:"transport_error",message:sg(o),timedOut:CT(o)}}}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=Qe()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&tg(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Wr(t))return!1;let r=ng(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(rg(n,r)+`
|
|
877
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${hs(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Yc(){return ST({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}a(Yc,"stdinLines");function TT(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}a(TT,"normalizeClientFamily");function AT(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}a(AT,"normalizeClientVersion");async function RT(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=a(()=>{if(i.length===0)return;let o=i.join(`
|
|
878
|
+
`).trim();i=[],o.length>0&&process.stdout.write(o+`
|
|
879
|
+
`)},"flushEvent");try{for(;;){let{value:o,done:c}=await t.read();if(c)break;r+=n.decode(o,{stream:!0});let l;for(;(l=r.indexOf(`
|
|
880
|
+
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){s();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{s()}}a(RT,"pipeSseToStdout");function IT(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}}a(IT,"appendNoteToToolResult");function NT(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}a(NT,"parseRpc");async function zc(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=[],o=a(()=>{if(s.length===0)return;let c=s.join(`
|
|
881
|
+
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
882
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){o();continue}p.startsWith(":")||p.startsWith("data:")&&s.push(p.slice(5).replace(/^\s/,""))}}}finally{o()}return i.join(`
|
|
883
|
+
`)}a(zc,"collectSseText");function gs(e){try{return JSON.parse(e).id??null}catch{return null}}a(gs,"tryExtractId");function Wr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}a(Wr,"isInitializeRequest");function ig(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")}a(ig,"isSessionLossBody");function sg(e){return e instanceof Error?e.message:String(e)}a(sg,"stringifyErr");function CT(e){return e?.name==="TimeoutError"}a(CT,"isTimeoutError");function ys(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
884
|
+
`)}a(ys,"emitJsonRpcError");function OT(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}a(OT,"extractHint");function DT(e){try{let t=Wo(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}}a(DT,"parsePresenceToolResult");ae();ae();Kn();import{spawn as WT}from"node:child_process";import{platform as KT}from"node:os";async function Vn(e,t=process.stderr){let n=zr(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=ws(e),o=`mcp-bridge-${s.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:o,meta:s})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await YT(l.verification_uri_complete).catch(()=>{}),qT(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await zT(u);let p=await VT(i,l.device_code).catch(h=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(h)}
|
|
885
|
+
`),null));if(p){if(p.status==="approved")return Xt(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
886
|
+
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
887
|
+
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
888
|
+
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
889
|
+
`),null}a(Vn,"runDeviceFlow");async function VT(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()}a(VT,"pollOnce");function zT(e){return new Promise(t=>setTimeout(t,e))}a(zT,"sleep");function qT(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: ${dg(e.verification_uri,56)} \u2502`,` \u2502 Code: ${dg(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(`
|
|
890
|
+
`)+`
|
|
891
|
+
`)}a(qT,"printAuthInstructions");function dg(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}a(dg,"pad");async function YT(e){let t,n;switch(KT()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let s=WT(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}a(YT,"openExternalBrowser");Qc();Te();Ae();Te();import*as __ from"node:os";Jr();function vg(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,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"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re(`--client requires a family argument (${Yr.join(", ")})`);let s=i.trim().toLowerCase();if(!Yr.includes(s))throw new Re(`--client "${i}" is not a known client family. Known: ${Yr.join(", ")}`);t.client=s,n++;break}default:throw new Re(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}a(vg,"parseInstallFlags");var Re=class extends Error{static{a(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function kg(){process.stdout.write(hA())}a(kg,"printInstallHelp");function hA(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${Yr.join(", ")}`," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --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(`
|
|
892
|
+
`)}a(hA,"installHelpText");var Ts=class{static{a(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_
|
|
893
|
+
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),s=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),o=a((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(s)} |`,l=[];l.push(`| ${o(t[0],n)} | ${o(t[1],r)} | ${o(t[2],i)} | ${o(t[3],s)} |`),l.push(c);for(let d of this.results)l.push(`| ${o(d.target,n)} | ${o(d.action,r)} | ${o(d.status,i)} | ${o(d.detail??"",s)} |`);return l.join(`
|
|
894
|
+
`)+`
|
|
895
|
+
`}print(t){let n=this.summary();t.write(`
|
|
896
|
+
`),t.write(this.toMarkdownTable()),t.write(`
|
|
897
|
+
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
898
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};el();Jr();qn();Ie();async function Cg(e){let{target:t,explicitFamily:n,exists:r}=e;return t.presence===void 0||n===t.clientFamilyEnv||await r(t.presence.dir)?null:{target:t.key,action:"merge",status:"skipped",detail:t.presence.skipDetail}}a(Cg,"presenceSkipRow");Ie();Jr();import{applyEdits as bA,modify as wA,parse as vA,printParseErrorCode as kA}from"jsonc-parser";var Yn="maind";async function Pg(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=wg(e),i=r.serversKey==="servers",s;try{s=await Q(e.path)}catch(m){return nl(e,"read",m)}let o,c="create";if(s===null||s.trim().length===0)o={};else{c="merge";try{o=i?xA(s):JSON.parse(s)}catch(m){return nl(e,"parse",m)}}if(!Jn(o))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let l=e.key==="claude-code-user"&&EA(o),d,u,p=!1;if(l){let m=o[Yn];p=Dg(m,t,r),u=Og(m,t,r),d={...o,[Yn]:u}}else{let m=o[r.serversKey],g=Jn(m)?m:{},y=g[Yn];p=Dg(y,t,r),u=Og(y,t,r),d={...o,[r.serversKey]:{...g,[Yn]:u}}}if(p&&s!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let h=i&&!l?SA(s??"",[r.serversKey,Yn],u):JSON.stringify(d,null,2)+`
|
|
899
|
+
`;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await Y(e.path,h)}catch(m){return nl(e,"write",m)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}a(Pg,"mergeJsonConfig");function Og(e,t,n){let r=Jn(e)&&Jn(e.env)?e.env:{},i={...t.env};for(let[o,c]of Object.entries(r))!(o in i)&&typeof c=="string"&&(i[o]=c);let s={command:t.command,args:[...t.args],env:i};return n.entryType===void 0?s:{type:n.entryType,...s}}a(Og,"mergeEntry");function xA(e){let t=[],n=vA(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${kA(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}a(xA,"parseJsoncStrict");function SA(e,t,n){let r=wA(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
|
|
900
|
+
`}}),i=bA(e,r);return i.endsWith(`
|
|
901
|
+
`)?i:i+`
|
|
902
|
+
`}a(SA,"editInPlace");function EA(e){return!("mcpServers"in e||!(Yn in e))}a(EA,"hasRootShape");function Dg(e,t,n){if(!Jn(e)||n.entryType!==void 0&&e.type!==n.entryType||e.command!==t.command||!TA(e.args,t.args)||!Jn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}a(Dg,"serverEntriesEqual");function TA(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}a(TA,"arrayEquals");function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Jn,"isObject");function nl(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(nl,"failed");Ie();import{parse as AA,stringify as RA}from"smol-toml";async function Mg(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await Q(e.path)}catch(g){return Is(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=AA(r);if(!Qt(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return Is(e,"parse",g)}}let o=Qt(i.mcp_servers)?i.mcp_servers:{},c=o.maind;if(Qt(c)&&IA(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Qt(c)&&Qt(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:{...o,maind:u}},h;try{h=RA(p),h.endsWith(`
|
|
903
|
+
`)||(h+=`
|
|
904
|
+
`)}catch(g){return Is(e,"write",g)}let m=h.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:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await Y(e.path,h)}catch(g){return Is(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}a(Mg,"mergeTomlConfig");function IA(e,t){if(!Qt(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(!Qt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}a(IA,"tomlServerEntryEqual");function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Qt,"isObject");function Is(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Is,"failed");sl();fl();Qn();Ie();import*as zg from"node:readline";var nn="config:auto_working_paths",tR=`
|
|
892
905
|
Enable presence enrichment (auto working_paths)?
|
|
893
906
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
894
907
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -897,36 +910,36 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
897
910
|
absolute paths. Server-side these paths are account-private (org members never
|
|
898
911
|
see them) and revocable any time on the dashboard consent page or via
|
|
899
912
|
{"auto_working_paths": false} in the bridge config.
|
|
900
|
-
[y/N]: `;async function
|
|
901
|
-
`;if(e.dryRun)return{target:
|
|
902
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=K();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await
|
|
903
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw
|
|
904
|
-
`),2;let o;if(n.projectRoot!==null)o=n.projectRoot;else{let
|
|
905
|
-
`);for(let
|
|
906
|
-
`);return 2}o=
|
|
913
|
+
[y/N]: `;async function qg(e){let t=e.configPath??et(),n={};try{let o=await Q(t);if(o!==null&&o.trim().length>0){let c=JSON.parse(o);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:nn,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:nn,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??nR)(e.out,tR)}else return{target:nn,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:nn,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},s=JSON.stringify(i,null,2)+`
|
|
914
|
+
`;if(e.dryRun)return{target:nn,action:"merge",status:"would-merge",detail:t};try{await Y(t,s,384)}catch(o){return{target:nn,action:"merge",status:"failed",detail:`write: ${o instanceof Error?o.message:String(o)}`}}return{target:nn,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}a(qg,"applyWorkingPathsConsent");async function nR(e,t){e.write(t);let n=zg.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}a(nR,"promptYesNoDefaultNo");ae();async function Yg(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),s={};try{s=await i.json()}catch{}return i.ok?s.status!=="exchanged"||typeof s.api_key!="string"||!s.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:s.api_key,plan:s.plan??"unknown"}:{ok:!1,reason:s.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}a(Yg,"exchangeOneClickToken");async function Zg(e){let t="browser-pair";if(e.token!==null)try{let s=rR(e.token);return e.dryRun?{apiKey:s,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(Vr(),Xt(s),{apiKey:s,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(s){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:Jg(s)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let s=ws(e.bridgeVersion),o=await Yg({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:s.device_id,label:lg(),clientMeta:{...s}});if(o.ok)return Vr(),Xt(o.apiKey),{apiKey:o.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${o.plan})`}};n=o.reason,Xg(e).write(`[maind-mcp-bridge] one-click exchange failed (${o.reason}) \u2014 falling back to browser pairing.
|
|
915
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=K();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await Vn(e.bridgeVersion,Xg(e));return s===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:s.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${s.plan})${r}`}}}catch(s){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:Jg(s)}}}}a(Zg,"pairOrUseToken");function rR(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}a(rR,"validateTokenShape");function Jg(e){return e instanceof Error?e.message:String(e)}a(Jg,"errMessage");function Xg(e){return e.out??process.stdout}a(Xg,"out");Kn();var iR="install-completed",sR=3e3;async function Qg(e){if(!e.enabled||e.apiKey===null)return;let t=Wn(iR),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:aR(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:oR(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),sR);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)}}a(Qg,"postInstallTelemetry");function oR(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}a(oR,"countStatuses");function aR(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}a(aR,"parseNodeMajor");sn();Il();Ae();var FI="https://mcp.maind.dev/mcp";async function b_(e){let t=Date.now(),n;try{n=vg(e)}catch(k){if(k instanceof Re)return process.stderr.write(`error: ${k.message}
|
|
916
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return kg(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=__.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
917
|
+
`),2;let o;if(n.projectRoot!==null)o=n.projectRoot;else{let k=await As(process.cwd());if(k.length===0)o=await Eg(process.cwd());else if(k.length===1)o=k[0];else{let E=await Ag(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.
|
|
918
|
+
`);for(let w of k)process.stderr.write(` candidate: ${w}
|
|
919
|
+
`);return 2}o=E}}let c=new Ts,l=(process.env.MAIND_MCP_URL??"").trim()||FI;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
907
920
|
`),process.stdout.write(`maind install \u2014 project root: ${o}
|
|
908
921
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
909
922
|
|
|
910
|
-
`);let d=
|
|
923
|
+
`);let d=Es({projectRoot:o,homeDir:s,platform:process.platform,env:process.env}),u=qr(d);if(u=bg(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.
|
|
911
924
|
`:`error: no client targets selected (did you skip all of them?)
|
|
912
|
-
`),c.print(process.stdout),2;let p=await
|
|
925
|
+
`),c.print(process.stdout),2;let p=await Zg({bridgeVersion:j,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(`
|
|
913
926
|
pairing failed: ${p.result.detail??"unknown"}
|
|
914
927
|
Skipping remaining steps.
|
|
915
|
-
`),c.print(process.stdout),2;for(let
|
|
928
|
+
`),c.print(process.stdout),2;for(let k of u){let E=await Cg({target:k,explicitFamily:n.client,exists:Rg});if(E!==null){c.add(E);continue}let w=yg({mcpUrl:l,clientFamily:k.clientFamilyEnv}),x;k.kind==="json"?x=await Pg(k,w,n.dryRun):x=await Mg(k,w,n.dryRun),c.add(x)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let k=await Ug({projectRoot:o,homeDir:s,conventions:a(()=>Xs(p.apiKey,ks(o),{allowFetch:!n.dryRun}),"conventions")},n.dryRun);for(let E of k)c.add(E)}let h={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await Kg(h));for(let k of await Vg(h))c.add(k);c.add(await qg({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let m=jy();m.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${m.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await Qg({enabled:n.telemetry||n.full,installerVersion:j,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let g=c.exitCode(),y=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
916
929
|
DRY RUN finished in ${y}s. No files were modified. Re-run without --dry-run to apply.
|
|
917
930
|
`):process.stdout.write(`
|
|
918
931
|
Finished in ${y}s. Restart your MCP client so it picks up the new server entry.
|
|
919
|
-
`);let v=
|
|
932
|
+
`);let v=Fe({entryPath:je(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),b=v.fallbackReason===null?`${zn(v)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${b}
|
|
920
933
|
`),g===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.
|
|
921
|
-
`),g}a(
|
|
922
|
-
`,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}a(
|
|
923
|
-
${JSON.stringify(t)}`).digest("hex")}a(TR,"payloadKey");function Ae(e,t,n){return{kind:"error",error:e,message:t,hint:n}}a(Ae,"fail");var sn="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Uy(e){let t=Dc(e);if(t!==null&&Pc(t))return Ae("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 Ae("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 Ae("cloud_unavailable",`review_verdict failed: ${Bs(t?.detail??e)||"no detail"}`,sn)}a(Uy,"fromProtocolText");function AR(e,t,n){switch(e.kind){case"no_session":return Ae("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. ${sn}`);case"transport_error":return e.timedOut?Ae("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."):Ae("cloud_unavailable",`network error: ${e.message}`,sn);case"http_error":return e.status===401?Ae("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Bs(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?Ae("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."):Ae("cloud_unavailable",`HTTP ${e.status}: ${Bs(e.body)}`,sn);case"rpc_error":return Uy(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Uy(e.text);let r;try{r=JSON.parse(e.text)}catch{return Ae("cloud_unavailable",`review_verdict returned non-JSON text: ${Bs(e.text)}`,sn)}return typeof r!="object"||r===null?Ae("cloud_unavailable","review_verdict returned no object",sn):{kind:"verdict",body:r}}}}a(AR,"interpretOutcome");var RR="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).",IR={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"},Hy=a(e=>e.map(t=>IR[t]??t).join("; "),"adviceFor");function NR(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: ${Hy(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 ${Fy(n)}, but this branch forks off ${i??"the default branch"} at ${Fy(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}}a(NR,"skipText");function CR(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=Hy(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",s=NR(i,e.detail),o=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return s!==null?`Not recorded: ${s}${o}`:`Not recorded (${i||"the server gave no reason"}).${o}`}a(CR,"recordHint");async function Gy(e,t,n){let r=n.repoRoot??fe(),i=r,s=e,o=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let Y=tr(c,r);if(Y===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(!yR(Y.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=Y.repoRoot,s=n.engineFor(i),o=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,h=n.recorded??bR,m=[],g=await wR(s,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 s.reviewChanges(Ic(l,d)),v={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(vR(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:v,warnings:m};let w;try{w=await s.reviewDetectorScopes({baseRef:l})}catch(Y){let zd=be(qe(`reviewDetectorScopes failed: ${fl(Y)}`));w={commit:zd,local:zd},m.push(`repo-health detectors unavailable (${fl(Y)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:b,dropped:k}=Nc(y,w.commit);k>0&&m.push(`${k} symbol(s) exceed the server schema (name > ${ps} or qualified name > ${fs} chars) and were left out \u2014 this run is not attestation-grade.`);let S=TR(o,b),R=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",D=SR({persistWanted:u,since:l,projectKey:o,result:y,payload:b,git:R?(n.persistFacts??ER)(i,y.headSha):null,recordedRunId:h.get(S)??null}),F={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:b.changed_symbols.length,symbols_dropped:k,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:w.commit.coverage,findings:w.commit.local.slice(0,$y),local_only:kR(w).slice(0,$y)}},H=await n.callCloudTool("review_verdict",{attest:b,persist:D.persist,...o?{project_key:o}:{}},{timeoutMs:p}),U=AR(H,p,D.persist);if(U.kind==="error")return{ok:!1,error:U.error,message:U.message,hint:U.hint,base:v,local:F,warnings:m};let N=U.body;if(N.ok!==!0){let Y=N.error==="requires_team"||N.error==="requires_enterprise";return{ok:!1,error:N.error??"unknown_error",message:N.message??"review_verdict returned no message",hint:Y?RR:N.hint??sn,base:v,local:F,warnings:m}}if(N.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:v,local:F,warnings:m};let j=N.attest,he=N.run??null,_n=he&&typeof he.id=="string"?{persisted:!0,run_id:he.id,commit_sha:he.commit_sha??null,attestation_format:he.attestation_format??null}:{persisted:!1,reason:D.skipped??N.run_note??"not_persisted",...D.detail?{detail:D.detail}:{}};_n.persisted&&h.set(S,he.id);let Kd=typeof j?.attestation_grade=="boolean"?j.attestation_grade:null,Vd=Array.isArray(j?.grade_blockers)?j.grade_blockers:[],vi=N.counts??{},Ao=Array.isArray(N.findings)?N.findings:[],Iv=`Verdict ${N.verdict??"?"}: ${vi.block??0} block, ${vi.warn??0} warn, ${vi.note??0} note`+(N.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:N.verdict??null,counts:vi,record:_n,attest:j?{attestation_grade:Kd,grade_blockers:Vd,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:`${Iv} ${CR(_n,Kd,Vd,y.headSha)}`,findings:Ao.slice(0,pl).map(Y=>({convention_id:Y.convention_id,convention_version:Y.convention_version,severity:Y.severity,action:Y.action,...Y.downgrade_reason?{downgrade_reason:Y.downgrade_reason}:{},summary:Y.summary,matched_changed_symbols:(Y.matched_changed_symbols??[]).slice(0,_R),matched_symbol_count:Y.matched_symbols?.length??0})),...Ao.length>pl?{findings_not_shown:Ao.length-pl}:{},detector_findings:N.detector_findings??[],policy_source:N.policy_source??null,coverage_note:Oc(y,j?.evaluated_convention_count,k),base:v,local:F,warnings:m}}a(Gy,"runAttestReview");var By=(()=>{let e=Object.keys(Pr),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Ws(e){return OR("sha256").update(e,"utf8").digest("hex")}a(Ws,"nodeKeyHash");var DR=["module","class","interface","function","method","type_alias","enum","variable"],ml=[{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:DR,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 "+By+" \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 "+By+", 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."}}}}],hl=new Map([["codebase_review_verdict","attest_review_changes"]]),Vy=new Set([...ml.map(e=>e.name),...hl.keys()]),gl=new Set(["attest_review_changes",...[...hl].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function zy(e,t,n,r){if(!gl.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 Gy(e,n,r),s=hl.get(t);return s?{...i,renamed:{from:t,to:s,note:`${t} is ${s} since bridge 0.79.0 \u2014 call ${s}; the old name goes in a later minor.`}}:i}a(zy,"dispatchCloudBackedTool");function te(e){return typeof e=="string"&&e.length>0?e:void 0}a(te,"str");function on(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}a(on,"num");function Wy(e){if(e===void 0)return{repoRoot:fe(),scanDirs:void 0};let t=tr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}a(Wy,"anchorRepo");function Ky(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}.`}}a(Ky,"dirNotFound");async function qy(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(o=>typeof o=="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(o=>o.status==="open").length,s=r.findings.filter(o=>o.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=te(n.for_path);if(i!==void 0){let u=vy(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 Bt(u.repoRoot,u.repoRelPath,{minFiles:r}),h=p.namespace,m=a(y=>y===null?null:`${h?.prefix??""}${y}`,"full"),g=h===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:h===null?null:{dir:h.dir,prefix:h.prefix,file_count:h.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 s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,p=[];for(let k of s){let S=tr(k);if(S===null){p.push(k);continue}let R=u.get(S.repoRoot)??new Set;R.add(S.repoRelDir),u.set(S.repoRoot,R)}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 h=[],m=[],g=[],y=[];for(let[k,S]of u){let R=[...S],D=R.includes(""),F=await Gt(k,{dirs:D?void 0:R,minFiles:r});h.push({repo_root:k,dirs:D?null:R}),m.push(...F.findings),g.push(...F.facts.namespaces.map(H=>({repo_root:k,dir:H.dir,prefix:H.prefix,file_count:H.fileCount}))),y.push(...F.facts.skipped)}let v=m.filter(k=>k.status==="open"),w=m.filter(k=>k.status==="info"),b=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:v.length===0,open_count:v.length,preexisting_count:w.length,findings:v,preexisting:w.map(k=>`${k.namespace.prefix}${k.number}`),namespaces:g,skipped:y,scanned:h,...p.length>0?{unresolved_dirs:p}:{},hint:(v.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.":`${v.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+b}}let o=fe(),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:o,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:te(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=a(p=>r.findings.filter(h=>h.status===p),"of"),s=i("open"),o=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=s.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:s.length,warn_count:o.length,preexisting_count:c.length,findings:[...s,...o],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${s.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${s.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=te(n.dir),i,s;if(r!==void 0){let u=tr(r);if(u===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=u.repoRoot,s=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=fe(),s=void 0;let o=Vt(i,{dirs:s,baseRef:te(n.base_ref),includeBaseline:n.include_baseline!==!1});if(o.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=o.findings.filter(u=>u.status==="open").length,l=o.findings.length-c;return{ok:o.ok,verdict:o.verdict,repo_root:i,token_count:o.tokenCount,namespace_count:o.namespaceCount,scanned_files:o.scannedFiles,findings:o.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.namespace})),hint:(o.findings.length===0?`All house-namespace classes are covered (${o.tokenCount} tokens, ${o.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=Wy(te(n.dir));if(r===null)return Ky("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Kt(r.repoRoot,{dirs:r.scanDirs,baseRef:te(n.base_ref),includeBaseline:n.include_baseline!==!1}),s="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let o=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:o.length,preexisting_count:c.length,findings:o,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(o.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.`:`${o.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+s}}case"check_migration_ledger_drift":{let r=Wy(te(n.dir));if(r===null)return Ky("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Tc(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:te(n.remote_db_url)}),s=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let o=a(p=>i.findings.filter(h=>h.status===p),"of"),c=o("open"),l=o("warn"),d=o("info"),u=s.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:s,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=te(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:te(n.kind),limit:on(n.limit)})).map(s=>({...s,nodeKeyHash:Ws(s.nodeKey)}))}case"codebase_trace":{let r=te(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:on(n.max_depth),limit:on(n.limit)})}case"codebase_snippet":{let r=te(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:Ws(r)}}case"codebase_map":return e.getArchitecture({topN:on(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:te(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:on(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:Ws(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:te(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:on(n.limit)}),i;if(n.include_history!==!1)try{i=pa(await e.fileHistory({since:te(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:te(n.since)})}catch(l){s=be(qe(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let o={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Ws(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:o,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:o},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await e.fileHistory({paths:r,since:te(n.since),limit:on(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(o=>({sha:o.sha,author_name:o.authorName,author_email:o.authorEmail,date_iso:o.dateIso,subject:o.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(o=>({name:o.name,email:o.email,commits:o.commits,last_date_iso:o.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}a(qy,"dispatchLocalTool");var Ks=class{constructor(t=xy,n=null,r=fe,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{a(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return ml}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Vy.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let o=gl.has(i)?await zy(this.getEngine(),i,s,this.ctx??void 0):await qy(this.getEngine(),i,s),c=JSON.stringify(o,null,2);return this.recordSavings(i,o,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(o){let c=o instanceof Error?o.message:String(o),l=by(o)?`${wy} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(s=>s&&typeof s=="object"?s.name:void 0).filter(s=>typeof s=="string")),i=this.descriptors().filter(s=>!r.has(s.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Ny(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Bn();var PR="/mcp-client-metrics-ingest",MR=4e3,LR="codebase_search_tokens_saved";async function Yy(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Kr()}${PR}`,n=new AbortController,r=setTimeout(()=>n.abort(),MR);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:LR,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)}
|
|
924
|
-
`),!1}finally{clearTimeout(r)}}a(
|
|
925
|
-
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,
|
|
926
|
-
`),process.exit(1)),Zt("paired",null,{version:
|
|
927
|
-
`),process.exit(1)),Zt("paired",null,{version:
|
|
928
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
929
|
-
`),process.exit(0));let t=
|
|
930
|
-
`),n=await
|
|
931
|
-
`))}a(
|
|
934
|
+
`),g}a(b_,"runInstall");sn();sn();import{readFileSync as jI}from"node:fs";import{join as w_}from"node:path";function Zs(e){return e?Math.ceil(e.length/4):0}a(Zs,"estimateTokens");var v_=1e6,Qs=class{static{a(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 k_(e){try{let t=jI(e,"utf8");return t.length>v_?t.slice(0,v_):t}catch{return""}}a(k_,"readFileCapped");function UI(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]}a(UI,"distinctFilePaths");function x_(e,t,n,r){try{let i=Zs(n);if(e==="codebase_search"){let s=UI(t);if(s.length===0)return 0;let o=0;for(let c of s)o+=Zs(k_(w_(r,c)));return Math.max(0,o-i)}if(e==="codebase_snippet"){let s=t?.filePath;if(typeof s!="string"||s.length===0)return 0;let o=Zs(k_(w_(r,s)));return Math.max(0,o-i)}return 0}catch{return 0}}a(x_,"measureLocalToolSaved");qt();sn();import{createHash as aN}from"node:crypto";qt();import{execFileSync as WI}from"node:child_process";import{createHash as KI}from"node:crypto";sn();Nl();import{realpathSync as I_}from"node:fs";function VI(e,t){try{return I_(e)===I_(t)}catch{return e===t}}a(VI,"samePath");var Cl=30,zI=10,N_=20,qI=new Map;function Ol(e){return e instanceof Error?e.message:String(e)}a(Ol,"msg");function to(e){let t=e.split(`
|
|
935
|
+
`,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}a(to,"firstLine");var C_=a(e=>e?e.slice(0,12):"?","short");async function YI(e,t,n,r){let i=await e.status(),s=!i.indexed||i.fileCount===0,o=await R_(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:Ol(c)}}},n);return o.locked?o.value.ok?s?(r.push(`no local index found \u2014 built it now (${o.value.stats.filesParsed} file(s), ${Math.round(o.value.stats.durationMs/1e3)} s).`),{action:"built",files_parsed:o.value.stats.filesParsed,missing:!1}):{action:"refreshed",files_parsed:o.value.stats.filesParsed,missing:!1}:(s||r.push(`index refresh failed \u2014 continuing with the existing index: ${o.value.error}`),{action:"kept",note:"refresh_failed",missing:s}):(s||r.push("another process holds the index lock (the Stop hook's refresh?) \u2014 reviewing with the existing index; stale files degrade to co_located and keep the run from being attestation-grade."),{action:"kept",note:"lock_busy",missing:s})}a(YI,"refreshIndex");function JI(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}a(JI,"isEmptyRange");function XI(e){let t=a(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)))}a(XI,"localOnly");function ZI(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}a(ZI,"localGradeBlockers");function QI(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=Bc(!1,e.projectKey,e.result);if(!t.persist)return t;let n=ZI(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"}}a(QI,"bridgePersistDecision");function O_(e,t){try{return WI("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}a(O_,"git");function eN(e,t){let n=Cr(e),r=n&&O_(e,["merge-base",t,`origin/${n}`])||null,i=O_(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}a(eN,"gitPersistFacts");function tN(e,t){return KI("sha256").update(`${e??""}
|
|
936
|
+
${JSON.stringify(t)}`).digest("hex")}a(tN,"payloadKey");function Ce(e,t,n){return{kind:"error",error:e,message:t,hint:n}}a(Ce,"fail");var dn="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function D_(e){let t=Wc(e);if(t!==null&&Kc(t))return Ce("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 Ce("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 Ce("cloud_unavailable",`review_verdict failed: ${to(t?.detail??e)||"no detail"}`,dn)}a(D_,"fromProtocolText");function nN(e,t,n){switch(e.kind){case"no_session":return Ce("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. ${dn}`);case"transport_error":return e.timedOut?Ce("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."):Ce("cloud_unavailable",`network error: ${e.message}`,dn);case"http_error":return e.status===401?Ce("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${to(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?Ce("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."):Ce("cloud_unavailable",`HTTP ${e.status}: ${to(e.body)}`,dn);case"rpc_error":return D_(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return D_(e.text);let r;try{r=JSON.parse(e.text)}catch{return Ce("cloud_unavailable",`review_verdict returned non-JSON text: ${to(e.text)}`,dn)}return typeof r!="object"||r===null?Ce("cloud_unavailable","review_verdict returned no object",dn):{kind:"verdict",body:r}}}}a(nN,"interpretOutcome");var rN="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).",iN={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"},P_=a(e=>e.map(t=>iN[t]??t).join("; "),"adviceFor");function sN(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: ${P_(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 ${C_(n)}, but this branch forks off ${i??"the default branch"} at ${C_(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}}a(sN,"skipText");function oN(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=P_(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",s=sN(i,e.detail),o=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return s!==null?`Not recorded: ${s}${o}`:`Not recorded (${i||"the server gave no reason"}).${o}`}a(oN,"recordHint");async function M_(e,t,n){let r=n.repoRoot??fe(),i=r,s=e,o=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let X=ir(c,r);if(X===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(!VI(X.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=X.repoRoot,s=n.engineFor(i),o=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,h=n.recorded??qI,m=[],g=await YI(s,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 s.reviewChanges(Uc(l,d)),v={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(JI(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:v,warnings:m};let b;try{b=await s.reviewDetectorScopes({baseRef:l})}catch(X){let lu=be(Xe(`reviewDetectorScopes failed: ${Ol(X)}`));b={commit:lu,local:lu},m.push(`repo-health detectors unavailable (${Ol(X)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:E}=Hc(y,b.commit);E>0&&m.push(`${E} symbol(s) exceed the server schema (name > ${fs} or qualified name > ${ms} chars) and were left out \u2014 this run is not attestation-grade.`);let w=tN(o,k),x=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",I=QI({persistWanted:u,since:l,projectKey:o,result:y,payload:k,git:x?(n.persistFacts??eN)(i,y.headSha):null,recordedRunId:h.get(w)??null}),F={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:E,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,N_),local_only:XI(b).slice(0,N_)}},B=await n.callCloudTool("review_verdict",{attest:k,persist:I.persist,...o?{project_key:o}:{}},{timeoutMs:p}),H=nN(B,p,I.persist);if(H.kind==="error")return{ok:!1,error:H.error,message:H.message,hint:H.hint,base:v,local:F,warnings:m};let C=H.body;if(C.ok!==!0){let X=C.error==="requires_team"||C.error==="requires_enterprise";return{ok:!1,error:C.error??"unknown_error",message:C.message??"review_verdict returned no message",hint:X?rN:C.hint??dn,base:v,local:F,warnings:m}}if(C.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:v,local:F,warnings:m};let U=C.attest,he=C.run??null,wn=he&&typeof he.id=="string"?{persisted:!0,run_id:he.id,commit_sha:he.commit_sha??null,attestation_format:he.attestation_format??null}:{persisted:!1,reason:I.skipped??C.run_note??"not_persisted",...I.detail?{detail:I.detail}:{}};wn.persisted&&h.set(w,he.id);let au=typeof U?.attestation_grade=="boolean"?U.attestation_grade:null,cu=Array.isArray(U?.grade_blockers)?U.grade_blockers:[],ki=C.counts??{},$o=Array.isArray(C.findings)?C.findings:[],rk=`Verdict ${C.verdict??"?"}: ${ki.block??0} block, ${ki.warn??0} warn, ${ki.note??0} note`+(C.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:C.verdict??null,counts:ki,record:wn,attest:U?{attestation_grade:au,grade_blockers:cu,attestation_format:U.attestation_format??null,input_hash:U.input_hash??null,policy_hash:U.policy_hash??null,evaluated_convention_count:U.evaluated_convention_count??null,detector_coverage:U.detector_coverage??null}:null,hint:`${rk} ${oN(wn,au,cu,y.headSha)}`,findings:$o.slice(0,Cl).map(X=>({convention_id:X.convention_id,convention_version:X.convention_version,severity:X.severity,action:X.action,...X.downgrade_reason?{downgrade_reason:X.downgrade_reason}:{},summary:X.summary,matched_changed_symbols:(X.matched_changed_symbols??[]).slice(0,zI),matched_symbol_count:X.matched_symbols?.length??0})),...$o.length>Cl?{findings_not_shown:$o.length-Cl}:{},detector_findings:C.detector_findings??[],policy_source:C.policy_source??null,coverage_note:Gc(y,U?.evaluated_convention_count,E),base:v,local:F,warnings:m}}a(M_,"runAttestReview");var L_=(()=>{let e=Object.keys(Lr),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function no(e){return aN("sha256").update(e,"utf8").digest("hex")}a(no,"nodeKeyHash");var cN=["module","class","interface","function","method","type_alias","enum","variable"],Dl=[{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:cN,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 "+L_+" \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 "+L_+", 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."}}}}],Pl=new Map([["codebase_review_verdict","attest_review_changes"]]),j_=new Set([...Dl.map(e=>e.name),...Pl.keys()]),Ml=new Set(["attest_review_changes",...[...Pl].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function U_(e,t,n,r){if(!Ml.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 M_(e,n,r),s=Pl.get(t);return s?{...i,renamed:{from:t,to:s,note:`${t} is ${s} since bridge 0.79.0 \u2014 call ${s}; the old name goes in a later minor.`}}:i}a(U_,"dispatchCloudBackedTool");function re(e){return typeof e=="string"&&e.length>0?e:void 0}a(re,"str");function un(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}a(un,"num");function $_(e){if(e===void 0)return{repoRoot:fe(),scanDirs:void 0};let t=ir(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}a($_,"anchorRepo");function F_(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}.`}}a(F_,"dirNotFound");async function H_(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(o=>typeof o=="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(o=>o.status==="open").length,s=r.findings.filter(o=>o.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=re(n.for_path);if(i!==void 0){let u=By(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 Gt(u.repoRoot,u.repoRelPath,{minFiles:r}),h=p.namespace,m=a(y=>y===null?null:`${h?.prefix??""}${y}`,"full"),g=h===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:h===null?null:{dir:h.dir,prefix:h.prefix,file_count:h.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 s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,p=[];for(let E of s){let w=ir(E);if(w===null){p.push(E);continue}let x=u.get(w.repoRoot)??new Set;x.add(w.repoRelDir),u.set(w.repoRoot,x)}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 h=[],m=[],g=[],y=[];for(let[E,w]of u){let x=[...w],I=x.includes(""),F=await Bt(E,{dirs:I?void 0:x,minFiles:r});h.push({repo_root:E,dirs:I?null:x}),m.push(...F.findings),g.push(...F.facts.namespaces.map(B=>({repo_root:E,dir:B.dir,prefix:B.prefix,file_count:B.fileCount}))),y.push(...F.facts.skipped)}let v=m.filter(E=>E.status==="open"),b=m.filter(E=>E.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:v.length===0,open_count:v.length,preexisting_count:b.length,findings:v,preexisting:b.map(E=>`${E.namespace.prefix}${E.number}`),namespaces:g,skipped:y,scanned:h,...p.length>0?{unresolved_dirs:p}:{},hint:(v.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.":`${v.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let o=fe(),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:o,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:re(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=a(p=>r.findings.filter(h=>h.status===p),"of"),s=i("open"),o=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=s.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:s.length,warn_count:o.length,preexisting_count:c.length,findings:[...s,...o],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${s.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${s.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=re(n.dir),i,s;if(r!==void 0){let u=ir(r);if(u===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=u.repoRoot,s=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=fe(),s=void 0;let o=Vt(i,{dirs:s,baseRef:re(n.base_ref),includeBaseline:n.include_baseline!==!1});if(o.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=o.findings.filter(u=>u.status==="open").length,l=o.findings.length-c;return{ok:o.ok,verdict:o.verdict,repo_root:i,token_count:o.tokenCount,namespace_count:o.namespaceCount,scanned_files:o.scannedFiles,findings:o.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.namespace})),hint:(o.findings.length===0?`All house-namespace classes are covered (${o.tokenCount} tokens, ${o.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=$_(re(n.dir));if(r===null)return F_("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Kt(r.repoRoot,{dirs:r.scanDirs,baseRef:re(n.base_ref),includeBaseline:n.include_baseline!==!1}),s="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let o=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:o.length,preexisting_count:c.length,findings:o,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(o.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.`:`${o.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+s}}case"check_migration_ledger_drift":{let r=$_(re(n.dir));if(r===null)return F_("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=$c(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:re(n.remote_db_url)}),s=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let o=a(p=>i.findings.filter(h=>h.status===p),"of"),c=o("open"),l=o("warn"),d=o("info"),u=s.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:s,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=re(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:re(n.kind),limit:un(n.limit)})).map(s=>({...s,nodeKeyHash:no(s.nodeKey)}))}case"codebase_trace":{let r=re(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:un(n.max_depth),limit:un(n.limit)})}case"codebase_snippet":{let r=re(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:no(r)}}case"codebase_map":return e.getArchitecture({topN:un(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:re(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:un(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:no(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:re(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:un(n.limit)}),i;if(n.include_history!==!1)try{i=ka(await e.fileHistory({since:re(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:re(n.since)})}catch(l){s=be(Xe(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let o={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:no(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:o,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:o},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await e.fileHistory({paths:r,since:re(n.since),limit:un(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(o=>({sha:o.sha,author_name:o.authorName,author_email:o.authorEmail,date_iso:o.dateIso,subject:o.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(o=>({name:o.name,email:o.email,commits:o.commits,last_date_iso:o.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}a(H_,"dispatchLocalTool");var ro=class{constructor(t=Wy,n=null,r=fe,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{a(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Dl}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&j_.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let o=Ml.has(i)?await U_(this.getEngine(),i,s,this.ctx??void 0):await H_(this.getEngine(),i,s),c=JSON.stringify(o,null,2);return this.recordSavings(i,o,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(o){let c=o instanceof Error?o.message:String(o),l=Uy(o)?`${Hy} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(s=>s&&typeof s=="object"?s.name:void 0).filter(s=>typeof s=="string")),i=this.descriptors().filter(s=>!r.has(s.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=x_(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Kn();var lN="/mcp-client-metrics-ingest",dN=4e3,uN="codebase_search_tokens_saved";async function B_(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${zr()}${lN}`,n=new AbortController,r=setTimeout(()=>n.abort(),dN);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:uN,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)}
|
|
937
|
+
`),!1}finally{clearTimeout(r)}}a(B_,"postSavingsMetric");Fl();so();ao();ur();import{join as qC}from"node:path";var YC="<synthetic>";function Pb(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:qC(ad,cd(e.cwd),`${e.transcript_stem}.jsonl`)}a(Pb,"transcriptPathFromSideChannel");var yo=class{constructor(t){this.deps=t}static{a(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??od)(n,{start:this.offset});for(let s of i.events)if(s.kind==="title"){let o=s.title.trim();o.length>0&&(this.title=o)}else s.kind==="assistant"&&!s.isSidechain&&typeof s.model=="string"&&s.model.length>0&&s.model!==YC&&(this.model=s.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as JC}from"node:child_process";var XC=8,ZC=32;function QC(e){return e.split(`
|
|
938
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,ZC)}a(QC,"parsePorcelain");function eO(e,t=XC){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(s.length===0||n.includes(s))&&(n.push(s),n.length>=t))break}return n}a(eO,"condenseToDirs");async function Mb(e=tO){let t=await e();if(t===null)return null;let n=eO(QC(t));return n.length>0?n:null}a(Mb,"deriveWorkingPaths");async function tO(){return await new Promise(e=>{JC("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}a(tO,"defaultGitStatus");var oM=1,aM=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function cM(e){return aM.includes(e)}a(cM,"isHookSubcommand");var lM=6e4;async function dM(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==K()&&Xt(e),e;let t=K();if(t!==null)return t;let n=await Vn(j);return n===null&&(Zt("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:j}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
939
|
+
`),process.exit(1)),Zt("paired",null,{version:j}),n.apiKey}a(dM,"ensureApiKey");async function uM(e){let t=await Vn(j);return t===null&&(Zt("auth_failed",`${e}; re-authorization did not complete`,{version:j}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
940
|
+
`),process.exit(1)),Zt("paired",null,{version:j}),t.apiKey}a(uM,"reauth");async function pM(){let e=process.argv.slice(2).find(w=>!w.startsWith("-"));if(e==="install"){let w=process.argv.indexOf("install"),x=process.argv.slice(w+1),I=await b_(x);process.exit(I)}if(e==="doctor"){let{runDoctor:w}=await Promise.resolve().then(()=>(hd(),Bb));process.exit(await w(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:w}=await Promise.resolve().then(()=>(Gw(),Bw));process.exit(await w())}if(e==="guard"){let w=process.argv.indexOf("guard"),{runGuard:x}=await Promise.resolve().then(()=>(Yw(),qw));process.exit(await x(process.argv.slice(w+1)))}if(e==="guard-inject"){let{runGuardInject:w}=await Promise.resolve().then(()=>(Rl(),c_));process.exit(await w())}if(e==="guard-gate"){let{runGuardGate:w}=await Promise.resolve().then(()=>(rv(),nv));process.exit(await w())}if(e==="guard-stop"){let{runGuardStop:w}=await Promise.resolve().then(()=>(ov(),sv));process.exit(await w())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:w}=await Promise.resolve().then(()=>(Wd(),Zw));process.exit(await w())}if(e==="guard-capture"){let{runGuardCapture:w}=await Promise.resolve().then(()=>(dv(),lv));process.exit(await w())}if(e==="gateway"){let w=process.argv.indexOf("gateway"),{runGateway:x}=await Promise.resolve().then(()=>(qv(),zv));process.exit(await x(process.argv.slice(w+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:w}=await Promise.resolve().then(()=>(iu(),ru));process.exit(await w())}if(e==="guard-cross-check"){let{runGuardCrossCheck:w}=await Promise.resolve().then(()=>(iu(),ru));process.exit(await w())}if(e==="on-index-refresh"){let{runOnIndexRefresh:w}=await Promise.resolve().then(()=>(ou(),su));process.exit(await w())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:w}=await Promise.resolve().then(()=>(ou(),su));process.exit(await w())}if(e!==void 0&&cM(e)){let w=await Promise.resolve().then(()=>(Fd(),Nw)),x={"on-session-start":w.runOnSessionStart,"on-tool-use":w.runOnToolUse,"on-file-write":w.runOnFileWrite,"on-file-edit":w.runOnFileEdit,"on-repo-health":w.runOnRepoHealth,"on-write-health":w.runOnWriteHealth,"sync-config":w.runSyncConfig,flush:w.runFlush,status:w.runHookStatus}[e];process.exit(await x())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(j+`
|
|
941
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(fM(),process.exit(0)),process.argv.includes("--reauth")&&(Vr(),await Vn(j,process.stdout)===null&&process.exit(1),Zt("paired",null,{version:j}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
942
|
+
`),process.exit(0));let t=ne(),n=await dM(),r=z(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Qs:null,o=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new ro(void 0,s,void 0,{callCloudTool:a((w,x,I)=>o===null?Promise.resolve({kind:"no_session"}):o.callCloudTool(w,x,I),"callCloudTool"),projectKey:r,engineFor:a(w=>{let x=c.get(w);return x===void 0&&(x=Ky(w),c.set(w,x)),x},"engineFor"),projectKeyFor:ks}),d=`bridge-${sM()}`,u=a(async()=>{if(!s)return;let w=s.takePending();w.tokens<=0||await B_({apiKey:n,deviceId:t,sessionId:d,tokensSaved:w.tokens,bridgeVersion:j})},"flushSavings"),p=s?setInterval(()=>{u()},lM):null;p?.unref();let h=new oo({projectKey:r}),m=new yo({resolvePath:a(()=>Pb(h.sideChannel()),"resolvePath"),fallbackModel:a(()=>h.sideChannel()?.model??null,"fallbackModel")}),g=new io({projectKey:r,identity:h,sessionMeta:a(()=>m.read(),"sessionMeta"),postToolCall:a((w,x)=>o===null?Promise.reject(new Error("presence: no active forwarder")):o.postPresenceToolCall(w,x),"postToolCall"),deriveWorkingPaths:a(()=>Mb(),"deriveWorkingPaths"),snapshot:r!==null?Q_({projectKey:r}):void 0}),y=g.isEnabled?setInterval(()=>{g.pollActivity()},K_):null;if(y?.unref(),g.isEnabled){let w=a(x=>{g.end().finally(()=>process.exit(x))},"endAndExit");process.on("SIGTERM",()=>w(143)),process.on("SIGINT",()=>w(130))}let v=!1,b=a(w=>{if(v||w!=="codex")return;v=!0,setTimeout(()=>{Promise.resolve().then(()=>(Il(),y_)).then(({refreshAgentsMdConventions:I})=>I(w,{apiKey:n,projectKey:r})).catch(()=>{})},0).unref()},"scheduleAgentsMdRefresh"),k=0,E=Yc();try{for(;;){let w=o?.carryOver()??null,x=new _s({apiKey:n,deviceId:t,bridgeVersion:j,projectKey:r,localRouter:l,presence:g,onConnectionOutcome:a((I,F)=>Zt(I,F,{version:j}),"onConnectionOutcome"),onSessionReady:a(({clientFamily:I})=>b(I),"onSessionReady"),carry:w});o=x;try{await x.run(E);return}catch(I){if(I instanceof Kr&&k<oM){k+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${I.message}; re-authorizing\u2026
|
|
943
|
+
`),n=await uM(I.reason);continue}throw I}}}finally{p&&clearInterval(p),y&&clearInterval(y),await g.end(),await u()}}a(pM,"main");function fM(){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 --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>"," guard difficulty <on|off> | guard capture <on|off> in-loop triggers (ADR-360)",' guard skip --session <id> --reason "\u2026" [--kind consult|difficulty|capture] logged override'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop,"," guard-cross-observe, guard-cross-check, guard-difficulty, guard-outcome, guard-capture)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_NO_AGENTS_MD_REFRESH Set to 1 to stop refreshing the conventions block in AGENTS.md for Codex (ADR-359 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
|
|
944
|
+
`))}a(fM,"printHelp");pM().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
932
945
|
`),process.exit(1)});
|