@maind-dev/mcp-bridge 0.75.0 → 0.76.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.js +274 -242
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,40 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ll=Object.defineProperty;var o=(e,t)=>ll(e,"name",{value:t,configurable:!0});var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var oe=(e,t)=>{for(var n in t)ll(e,n,{get:t[n],enumerable:!0})};function ul(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Yt(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 Ds(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ps(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Ms(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var $s=b(()=>{"use strict";o(ul,"parseFrame");o(Yt,"denyResult");o(Ds,"toolEvent");o(Ps,"policyEvent");o(Ms,"shaEvent")});import{execFileSync as ml}from"node:child_process";function hl(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=P_}function M_(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 N_){let a=r[s];typeof a=="string"&&pl.test(a)&&i.push({field:s,sha:a})}for(let[s,a]of O_){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&pl.test(l)&&i.push({field:`${s}.${a}`,sha:l})}return i}function $_(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,fl);for(let i=fl;i>=D_;i--){let s=r.slice(0,i),a=t(s);if(a!==null&&a.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Jt(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 gl(){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 Mr(e=process.cwd()){try{let n=ml("git",["rev-parse","--show-toplevel"],{cwd:e,env:gl(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function L_(e){return t=>{try{let r=ml("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:gl(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function $r(e,t){if(t===null)return[];let n=M_(e);if(n.length===0)return[];let r=L_(t),i=[];for(let{field:s,sha:a}of n){let c=$_(a,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var N_,O_,pl,D_,fl,P_,Ls=b(()=>{"use strict";N_=["commit_sha","base_sha","head_sha"],O_=[["diff_stats","head_sha"],["diff_stats","base_sha"]],pl=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,D_=7,fl=12,P_=10;o(hl,"isDenyGrade");o(M_,"extractShaArgs");o($_,"classifySha");o(Jt,"shaFindingText");o(gl,"cleanGitEnv");o(Mr,"resolveRepoRootForSha");o(L_,"gitShaResolver");o($r,"inspectLineForShas")});var yl=b(()=>{"use strict"});var P,Fs,A,we,Vn=b(()=>{(function(e){e.assertEqual=i=>{};function t(i){}o(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}o(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of s)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},e.find=(i,s)=>{for(let a of i)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}o(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(P||(P={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Fs||(Fs={}));A=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),we=o(e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}},"getParsedType")});var v,F_,ae,Lr=b(()=>{Vn();v=P.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"]),F_=o(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ae=class e extends Error{static{o(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},i=o(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],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,P.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()}};ae.create=e=>new ae(e)});var j_,De,js=b(()=>{Lr();Vn();j_=o((e,t)=>{let n;switch(e.code){case v.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,P.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${P.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${P.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${P.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.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}"`:P.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case v.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 v.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 v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,P.assertNever(e)}return{message:n}},"errorMap"),De=j_});function U_(e){_l=e}function Xt(){return _l}var _l,Fr=b(()=>{js();_l=De;o(U_,"setErrorMap");o(Xt,"getErrorMap")});function E(e,t){let n=Xt(),r=zn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===De?void 0:De].filter(i=>!!i)});e.common.issues.push(r)}var zn,H_,V,C,ct,Z,jr,Ur,ze,Zt,Us=b(()=>{Fr();js();zn=o(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),H_=[];o(E,"addIssueToContext");V=class e{static{o(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return 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,a=await i.value;r.push({key:s,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return C;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}},C=Object.freeze({status:"aborted"}),ct=o(e=>({status:"dirty",value:e}),"DIRTY"),Z=o(e=>({status:"valid",value:e}),"OK"),jr=o(e=>e.status==="aborted","isAborted"),Ur=o(e=>e.status==="dirty","isDirty"),ze=o(e=>e.status==="valid","isValid"),Zt=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var bl=b(()=>{});var R,wl=b(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(R||(R={}))});function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:o((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function xl(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 ib(e){return new RegExp(`^${xl(e)}$`)}function El(e){let t=`${Sl}T${xl(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 sb(e,t){return!!((t==="v4"||!t)&&X_.test(e)||(t==="v6"||!t)&&Q_.test(e))}function ob(e,t){if(!z_.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 ab(e,t){return!!((t==="v4"||!t)&&Z_.test(e)||(t==="v6"||!t)&&eb.test(e))}function cb(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}function Qt(e){if(e instanceof ce){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=de.create(Qt(r))}return new ce({...e._def,shape:o(()=>t,"shape")})}else return e instanceof $e?new $e({...e._def,type:Qt(e.element)}):e instanceof de?de.create(Qt(e.unwrap())):e instanceof ke?ke.create(Qt(e.unwrap())):e instanceof ve?ve.create(e.items.map(t=>Qt(t))):e}function Gs(e,t){let n=we(e),r=we(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let i=P.objectKeys(t),s=P.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of s){let l=Gs(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let a=e[s],c=t[s],l=Gs(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function Al(e,t){return new bt({values:e,typeName:N.ZodEnum,...O(t)})}function kl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Tl(e,t={},n){return e?Ye.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(a=>{if(!a){let c=kl(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let a=kl(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Ye.create()}var ue,vl,D,G_,W_,B_,K_,V_,z_,q_,Y_,J_,Hs,X_,Z_,Q_,eb,tb,nb,Sl,rb,qe,lt,dt,ut,pt,en,ft,mt,Ye,Me,he,tn,$e,ce,ht,Pe,Hr,gt,ve,Gr,nn,rn,Wr,yt,_t,bt,wt,Je,pe,de,ke,vt,kt,sn,lb,qn,Yn,St,db,N,ub,Rl,Il,pb,fb,Cl,mb,hb,gb,yb,_b,bb,wb,vb,kb,Sb,xb,Eb,Ab,Tb,Rb,Ib,Cb,Nb,Ob,Db,Pb,Mb,$b,Lb,Fb,jb,Ub,Hb,Gb,Wb,Bb,Kb,Vb,zb,Nl=b(()=>{Lr();Fr();wl();Us();Vn();ue=class{static{o(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},vl=o((e,t)=>{if(ze(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ae(e.common.issues);return this._error=n,this._error}}},"handleResult");o(O,"processCreateParams");D=class{static{o(this,"ZodType")}get description(){return this._def.description}_getType(t){return we(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:we(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new V,ctx:{common:t.parent.common,data:t.data,parsedType:we(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Zt(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:we(t)},i=this._parseSync({data:t,path:r.path,parent:r});return vl(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:we(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ze(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=>ze(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:we(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(Zt(i)?i:Promise.resolve(i));return vl(r,s)}refine(t,n){let r=o(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let a=t(i),c=o(()=>s.addIssue({code:v.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new pe({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:o(n=>this["~validate"](n),"validate")}}optional(){return de.create(this,this._def)}nullable(){return ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $e.create(this)}promise(){return Je.create(this,this._def)}or(t){return ht.create([this,t],this._def)}and(t){return gt.create(this,t,this._def)}transform(t){return new pe({...O(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new vt({...O(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new qn({typeName:N.ZodBranded,type:this,...O(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new kt({...O(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Yn.create(this,t)}readonly(){return St.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},G_=/^c[^\s-]{8,}$/i,W_=/^[0-9a-z]+$/,B_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,K_=/^[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,V_=/^[a-z0-9_-]{21}$/i,z_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,q_=/^[-+]?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)?)??$/,Y_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",X_=/^(?:(?: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])$/,Z_=/^(?:(?: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])$/,Q_=/^(([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]))$/,eb=/^(([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])$/,tb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sl="((\\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])))",rb=new RegExp(`^${Sl}$`);o(xl,"timeRegexSource");o(ib,"timeRegex");o(El,"datetimeRegex");o(sb,"isValidIP");o(ob,"isValidJWT");o(ab,"isValidCidr");qe=class e extends D{static{o(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_type,expected:A.string,received:s.parsedType}),C}let r=new V,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:v.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:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?E(i,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&E(i,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Y_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"email",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Hs||(Hs=new RegExp(J_,"u")),Hs.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"emoji",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")K_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"uuid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")V_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"nanoid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")G_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")W_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid2",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")B_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ulid",code:v.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:v.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:v.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:v.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:v.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:v.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?El(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?rb.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ib(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?q_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"duration",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?sb(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ip",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?ob(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"jwt",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?ab(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cidr",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?tb.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?nb.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64url",code:v.invalid_string,message:s.message}),r.dirty()):P.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:v.invalid_string,...R.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...R.errToObj(t)})}url(t){return this._addCheck({kind:"url",...R.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...R.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...R.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...R.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...R.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...R.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...R.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...R.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...R.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...R.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...R.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...R.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...R.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...R.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...R.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...R.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...R.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...R.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...R.errToObj(n)})}nonempty(t){return this.min(1,R.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}};qe.create=e=>new qe({checks:[],typeName:N.ZodString,coerce:e?.coerce??!1,...O(e)});o(cb,"floatSafeRemainder");lt=class e extends D{static{o(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_type,expected:A.number,received:s.parsedType}),C}let r,i=new V;for(let s of this._def.checks)s.kind==="int"?P.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.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:v.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:v.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?cb(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.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:v.not_finite,message:s.message}),i.dirty()):P.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,R.toString(n))}gt(t,n){return this.setLimit("min",t,!1,R.toString(n))}lte(t,n){return this.setLimit("max",t,!0,R.toString(n))}lt(t,n){return this.setLimit("max",t,!1,R.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:R.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:R.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.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"&&P.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)}};lt.create=e=>new lt({checks:[],typeName:N.ZodNumber,coerce:e?.coerce||!1,...O(e)});dt=class e extends D{static{o(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let r,i=new V;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:v.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:v.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:v.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):P.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:v.invalid_type,expected:A.bigint,received:n.parsedType}),C}gte(t,n){return this.setLimit("min",t,!0,R.toString(n))}gt(t,n){return this.setLimit("min",t,!1,R.toString(n))}lte(t,n){return this.setLimit("max",t,!0,R.toString(n))}lt(t,n){return this.setLimit("max",t,!1,R.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.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:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:R.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}};dt.create=e=>new dt({checks:[],typeName:N.ZodBigInt,coerce:e?.coerce??!1,...O(e)});ut=class extends D{static{o(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.boolean,received:r.parsedType}),C}return Z(t.data)}};ut.create=e=>new ut({typeName:N.ZodBoolean,coerce:e?.coerce||!1,...O(e)});pt=class e extends D{static{o(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_type,expected:A.date,received:s.parsedType}),C}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_date}),C}let r=new V,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:v.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:v.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):P.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:R.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:R.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}};pt.create=e=>new pt({checks:[],coerce:e?.coerce||!1,typeName:N.ZodDate,...O(e)});en=class extends D{static{o(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.symbol,received:r.parsedType}),C}return Z(t.data)}};en.create=e=>new en({typeName:N.ZodSymbol,...O(e)});ft=class extends D{static{o(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.undefined,received:r.parsedType}),C}return Z(t.data)}};ft.create=e=>new ft({typeName:N.ZodUndefined,...O(e)});mt=class extends D{static{o(this,"ZodNull")}_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.null,received:r.parsedType}),C}return Z(t.data)}};mt.create=e=>new mt({typeName:N.ZodNull,...O(e)});Ye=class extends D{static{o(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return Z(t.data)}};Ye.create=e=>new Ye({typeName:N.ZodAny,...O(e)});Me=class extends D{static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return Z(t.data)}};Me.create=e=>new Me({typeName:N.ZodUnknown,...O(e)});he=class extends D{static{o(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:v.invalid_type,expected:A.never,received:n.parsedType}),C}};he.create=e=>new he({typeName:N.ZodNever,...O(e)});tn=class extends D{static{o(this,"ZodVoid")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.void,received:r.parsedType}),C}return Z(t.data)}};tn.create=e=>new tn({typeName:N.ZodVoid,...O(e)});$e=class e extends D{static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==A.array)return E(n,{code:v.invalid_type,expected:A.array,received:n.parsedType}),C;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(E(n,{code:a?v.too_big:v.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(E(n,{code:v.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:v.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new ue(n,a,n.path,c)))).then(a=>V.mergeArray(r,a));let s=[...n.data].map((a,c)=>i.type._parseSync(new ue(n,a,n.path,c)));return V.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:R.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:R.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:R.toString(n)}})}nonempty(t){return this.min(1,t)}};$e.create=(e,t)=>new $e({type:e,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...O(t)});o(Qt,"deepPartialify");ce=class e extends D{static{o(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=P.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let u=this._getOrReturnCtx(t);return E(u,{code:v.invalid_type,expected:A.object,received:u.parsedType}),C}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof he&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let d=s[u],p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ue(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof he){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")c.length>0&&(E(i,{code:v.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of c){let p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ue(i,p,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of l){let p=await d.key,h=await d.value;u.push({key:p,value:h,alwaysSet:d.alwaysSet})}return u}).then(u=>V.mergeObjectSync(r,u)):V.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return R.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:o((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:R.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:o(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:o(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:N.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 P.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}omit(t){let n={};for(let r of P.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}deepPartial(){return Qt(this)}partial(t){let n={};for(let r of P.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:o(()=>n,"shape")})}required(t){let n={};for(let r of P.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof de;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return Al(P.objectKeys(this.shape))}};ce.create=(e,t)=>new ce({shape:o(()=>e,"shape"),unknownKeys:"strip",catchall:he.create(),typeName:N.ZodObject,...O(t)});ce.strictCreate=(e,t)=>new ce({shape:o(()=>e,"shape"),unknownKeys:"strict",catchall:he.create(),typeName:N.ZodObject,...O(t)});ce.lazycreate=(e,t)=>new ce({shape:e,unknownKeys:"strip",catchall:he.create(),typeName:N.ZodObject,...O(t)});ht=class extends D{static{o(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=s.map(c=>new ae(c.ctx.common.issues));return E(n,{code:v.invalid_union,unionErrors:a}),C}if(o(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=a.map(l=>new ae(l));return E(n,{code:v.invalid_union,unionErrors:c}),C}}get options(){return this._def.options}};ht.create=(e,t)=>new ht({options:e,typeName:N.ZodUnion,...O(t)});Pe=o(e=>e instanceof yt?Pe(e.schema):e instanceof pe?Pe(e.innerType()):e instanceof _t?[e.value]:e instanceof bt?e.options:e instanceof wt?P.objectValues(e.enum):e instanceof vt?Pe(e._def.innerType):e instanceof ft?[void 0]:e instanceof mt?[null]:e instanceof de?[void 0,...Pe(e.unwrap())]:e instanceof ke?[null,...Pe(e.unwrap())]:e instanceof qn||e instanceof St?Pe(e.unwrap()):e instanceof kt?Pe(e._def.innerType):[],"getDiscriminator"),Hr=class e extends D{static{o(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return E(n,{code:v.invalid_type,expected:A.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:v.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 a=Pe(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...O(r)})}};o(Gs,"mergeValues");gt=class extends D{static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=o((s,a)=>{if(jr(s)||jr(a))return C;let c=Gs(s.value,a.value);return c.valid?((Ur(s)||Ur(a))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:v.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,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};gt.create=(e,t,n)=>new gt({left:e,right:t,typeName:N.ZodIntersection,...O(n)});ve=class e extends D{static{o(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return E(r,{code:v.invalid_type,expected:A.array,received:r.parsedType}),C;if(r.data.length<this._def.items.length)return E(r,{code:v.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:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ue(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>V.mergeArray(n,a)):V.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ve.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ve({items:e,typeName:N.ZodTuple,rest:null,...O(t)})};Gr=class e extends D{static{o(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return E(r,{code:v.invalid_type,expected:A.object,received:r.parsedType}),C;let i=[],s=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ue(r,c,r.path,c)),value:a._parse(new ue(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?V.mergeObjectAsync(n,i):V.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:N.ZodRecord,...O(r)}):new e({keyType:qe.create(),valueType:t,typeName:N.ZodRecord,...O(n)})}},nn=class extends D{static{o(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.map)return E(r,{code:v.invalid_type,expected:A.map,received:r.parsedType}),C;let i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:i._parse(new ue(r,c,r.path,[u,"key"])),value:s._parse(new ue(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return C;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return C;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}}}};nn.create=(e,t,n)=>new nn({valueType:t,keyType:e,typeName:N.ZodMap,...O(n)});rn=class e extends D{static{o(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return E(r,{code:v.invalid_type,expected:A.set,received:r.parsedType}),C;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(E(r,{code:v.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:v.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function a(l){let u=new Set;for(let d of l){if(d.status==="aborted")return C;d.status==="dirty"&&n.dirty(),u.add(d.value)}return{status:n.value,value:u}}o(a,"finalizeSet");let c=[...r.data.values()].map((l,u)=>s._parse(new ue(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:R.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:R.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};rn.create=(e,t)=>new rn({valueType:e,minSize:null,maxSize:null,typeName:N.ZodSet,...O(t)});Wr=class e extends D{static{o(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return E(n,{code:v.invalid_type,expected:A.function,received:n.parsedType}),C;function r(c,l){return zn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xt(),De].filter(u=>!!u),issueData:{code:v.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function i(c,l){return zn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xt(),De].filter(u=>!!u),issueData:{code:v.invalid_return_type,returnTypeError:l}})}o(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Je){let c=this;return Z(async function(...l){let u=new ae([]),d=await c._def.args.parseAsync(l,s).catch(m=>{throw u.addIssue(r(l,m)),u}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,s).catch(m=>{throw u.addIssue(i(p,m)),u})})}else{let c=this;return Z(function(...l){let u=c._def.args.safeParse(l,s);if(!u.success)throw new ae([r(l,u.error)]);let d=Reflect.apply(a,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new ae([i(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ve.create(t).rest(Me.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||ve.create([]).rest(Me.create()),returns:n||Me.create(),typeName:N.ZodFunction,...O(r)})}},yt=class extends D{static{o(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};yt.create=(e,t)=>new yt({getter:e,typeName:N.ZodLazy,...O(t)});_t=class extends D{static{o(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:v.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}};_t.create=(e,t)=>new _t({value:e,typeName:N.ZodLiteral,...O(t)});o(Al,"createZodEnum");bt=class e extends D{static{o(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:P.joinValues(r),received:n.parsedType,code:v.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:v.invalid_enum_value,options:r}),C}return Z(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})}};bt.create=Al;wt=class extends D{static{o(this,"ZodNativeEnum")}_parse(t){let n=P.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let i=P.objectValues(n);return E(r,{expected:P.joinValues(i),received:r.parsedType,code:v.invalid_type}),C}if(this._cache||(this._cache=new Set(P.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=P.objectValues(n);return E(r,{received:r.data,code:v.invalid_enum_value,options:i}),C}return Z(t.data)}get enum(){return this._def.values}};wt.create=(e,t)=>new wt({values:e,typeName:N.ZodNativeEnum,...O(t)});Je=class extends D{static{o(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return E(n,{code:v.invalid_type,expected:A.promise,received:n.parsedType}),C;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return Z(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Je.create=(e,t)=>new Je({type:e,typeName:N.ZodPromise,...O(t)});pe=class extends D{static{o(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o(a=>{E(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return C;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?C:l.status==="dirty"?ct(l.value):n.value==="dirty"?ct(l.value):l});{if(n.value==="aborted")return C;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?C:c.status==="dirty"?ct(c.value):n.value==="dirty"?ct(c.value):c}}if(i.type==="refinement"){let a=o(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ze(a))return C;let c=i.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ze(a)?Promise.resolve(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):C);P.assertNever(i)}};pe.create=(e,t,n)=>new pe({schema:e,typeName:N.ZodEffects,effect:t,...O(n)});pe.createWithPreprocess=(e,t,n)=>new pe({schema:t,effect:{type:"preprocess",transform:e},typeName:N.ZodEffects,...O(n)});de=class extends D{static{o(this,"ZodOptional")}_parse(t){return this._getType(t)===A.undefined?Z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};de.create=(e,t)=>new de({innerType:e,typeName:N.ZodOptional,...O(t)});ke=class extends D{static{o(this,"ZodNullable")}_parse(t){return this._getType(t)===A.null?Z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ke.create=(e,t)=>new ke({innerType:e,typeName:N.ZodNullable,...O(t)});vt=class extends D{static{o(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:N.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...O(t)});kt=class extends D{static{o(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Zt(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ae(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};kt.create=(e,t)=>new kt({innerType:e,typeName:N.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...O(t)});sn=class extends D{static{o(this,"ZodNaN")}_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.nan,received:r.parsedType}),C}return{status:"valid",value:t.data}}};sn.create=e=>new sn({typeName:N.ZodNaN,...O(e)});lb=Symbol("zod_brand"),qn=class extends D{static{o(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Yn=class e extends D{static{o(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return o(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?C:s.status==="dirty"?(n.dirty(),ct(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:N.ZodPipeline})}},St=class extends D{static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(i=>(ze(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Zt(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};St.create=(e,t)=>new St({innerType:e,typeName:N.ZodReadonly,...O(t)});o(kl,"cleanParams");o(Tl,"custom");db={object:ce.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"})(N||(N={}));ub=o((e,t={message:`Input not instance of ${e.name}`})=>Tl(n=>n instanceof e,t),"instanceOfType"),Rl=qe.create,Il=lt.create,pb=sn.create,fb=dt.create,Cl=ut.create,mb=pt.create,hb=en.create,gb=ft.create,yb=mt.create,_b=Ye.create,bb=Me.create,wb=he.create,vb=tn.create,kb=$e.create,Sb=ce.create,xb=ce.strictCreate,Eb=ht.create,Ab=Hr.create,Tb=gt.create,Rb=ve.create,Ib=Gr.create,Cb=nn.create,Nb=rn.create,Ob=Wr.create,Db=yt.create,Pb=_t.create,Mb=bt.create,$b=wt.create,Lb=Je.create,Fb=pe.create,jb=de.create,Ub=ke.create,Hb=pe.createWithPreprocess,Gb=Yn.create,Wb=o(()=>Rl().optional(),"ostring"),Bb=o(()=>Il().optional(),"onumber"),Kb=o(()=>Cl().optional(),"oboolean"),Vb={string:o(e=>qe.create({...e,coerce:!0}),"string"),number:o(e=>lt.create({...e,coerce:!0}),"number"),boolean:o(e=>ut.create({...e,coerce:!0}),"boolean"),bigint:o(e=>dt.create({...e,coerce:!0}),"bigint"),date:o(e=>pt.create({...e,coerce:!0}),"date")},zb=C});var f={};oe(f,{BRAND:()=>lb,DIRTY:()=>ct,EMPTY_PATH:()=>H_,INVALID:()=>C,NEVER:()=>zb,OK:()=>Z,ParseStatus:()=>V,Schema:()=>D,ZodAny:()=>Ye,ZodArray:()=>$e,ZodBigInt:()=>dt,ZodBoolean:()=>ut,ZodBranded:()=>qn,ZodCatch:()=>kt,ZodDate:()=>pt,ZodDefault:()=>vt,ZodDiscriminatedUnion:()=>Hr,ZodEffects:()=>pe,ZodEnum:()=>bt,ZodError:()=>ae,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>Wr,ZodIntersection:()=>gt,ZodIssueCode:()=>v,ZodLazy:()=>yt,ZodLiteral:()=>_t,ZodMap:()=>nn,ZodNaN:()=>sn,ZodNativeEnum:()=>wt,ZodNever:()=>he,ZodNull:()=>mt,ZodNullable:()=>ke,ZodNumber:()=>lt,ZodObject:()=>ce,ZodOptional:()=>de,ZodParsedType:()=>A,ZodPipeline:()=>Yn,ZodPromise:()=>Je,ZodReadonly:()=>St,ZodRecord:()=>Gr,ZodSchema:()=>D,ZodSet:()=>rn,ZodString:()=>qe,ZodSymbol:()=>en,ZodTransformer:()=>pe,ZodTuple:()=>ve,ZodType:()=>D,ZodUndefined:()=>ft,ZodUnion:()=>ht,ZodUnknown:()=>Me,ZodVoid:()=>tn,addIssueToContext:()=>E,any:()=>_b,array:()=>kb,bigint:()=>fb,boolean:()=>Cl,coerce:()=>Vb,custom:()=>Tl,date:()=>mb,datetimeRegex:()=>El,defaultErrorMap:()=>De,discriminatedUnion:()=>Ab,effect:()=>Fb,enum:()=>Mb,function:()=>Ob,getErrorMap:()=>Xt,getParsedType:()=>we,instanceof:()=>ub,intersection:()=>Tb,isAborted:()=>jr,isAsync:()=>Zt,isDirty:()=>Ur,isValid:()=>ze,late:()=>db,lazy:()=>Db,literal:()=>Pb,makeIssue:()=>zn,map:()=>Cb,nan:()=>pb,nativeEnum:()=>$b,never:()=>wb,null:()=>yb,nullable:()=>Ub,number:()=>Il,object:()=>Sb,objectUtil:()=>Fs,oboolean:()=>Kb,onumber:()=>Bb,optional:()=>jb,ostring:()=>Wb,pipeline:()=>Gb,preprocess:()=>Hb,promise:()=>Lb,quotelessJson:()=>F_,record:()=>Ib,set:()=>Nb,setErrorMap:()=>U_,strictObject:()=>xb,string:()=>Rl,symbol:()=>hb,transformer:()=>Fb,tuple:()=>Rb,undefined:()=>gb,union:()=>Eb,unknown:()=>bb,util:()=>P,void:()=>vb});var Ws=b(()=>{Fr();Us();bl();Vn();Nl();Lr()});var Q=b(()=>{Ws();Ws()});var Bs,Ks=b(()=>{"use strict";Q();Bs=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 qb,Ol=b(()=>{"use strict";Q();Ks();qb=Bs.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 Dl,Pl,Ml,$l,Vs,Ll,Fl,jl,Yb,Ul=b(()=>{"use strict";Q();Dl=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Pl=f.enum(Dl),Ml=["new_to_ai_agents","new_to_this_client","experienced"],$l=f.enum(Ml),Vs=[{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"}],Ll=Vs.map(e=>e.header),Fl=f.object({experience_level:f.array($l).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),jl=f.object({id:f.string().min(1),client:Pl,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:Fl,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Yb=jl.extend({body:f.string().min(1)})});var Gl,Br,Wl,Kr,Jb,Xb,Bl,Kl,Vl,zl,Vr,Zb,Qb,Hl,ew,ql,tw,Yl=b(()=>{"use strict";Q();Gl=["operating_procedure","code_review","communication_style"],Br=f.enum(Gl),Wl=["info","recommended","required"],Kr=f.enum(Wl),Jb=["optional","default_on","mandatory"],Xb=f.enum(Jb),Bl=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Kl=f.enum(Bl),Vl=["verify","contribute","mixed"],zl=f.enum(Vl),Vr=f.object({clients:f.array(Kl).default([]),stacks:f.array(f.string()).default([]),intents:f.array(zl).default([])}).default({clients:[],stacks:[],intents:[]}),Zb=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Qb=64,Hl=200,ew=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")),ql=f.object({id:f.string().min(5).max(Qb).regex(Zb,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:Br,version:f.number().int().min(1),changed_at:ew,changelog:f.string().max(500).optional(),applies_to:Vr,severity:Kr.default("recommended"),disableability:Xb.default("default_on"),summary:f.string().min(1).max(Hl,`summary must be \u2264 ${Hl} 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()}),tw=ql.extend({body:f.string().min(1)})});var Xe=b(()=>{"use strict";Ks();Ol();Ul();Yl()});var zs,zr,qs,Jl,Xl,Zl,nw,Ql=b(()=>{"use strict";Q();zs=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),zr=f.number().min(0).max(1).optional(),qs=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:zr,right:zr,bottom:zr,left:zr}).optional()}),Jl=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")}),Xl=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Jl.optional(),blocks:f.array(f.discriminatedUnion("type",[zs,qs])).max(50)}),Zl=f.discriminatedUnion("type",[zs,qs,Xl]),nw=f.array(Zl).max(100)});var ed,rw,td,nd,iw,sw,ow,rd=b(()=>{"use strict";Q();ed=["free","solo_pro","team","enterprise"],rw=f.enum(ed),td=["solo_pro","team","enterprise"],nd=f.enum(td),iw=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),sw=f.object({user_id:f.string().uuid(),tier:nd,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:iw.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"}),ow=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var id=b(()=>{"use strict"});var aw,cw,lw,sd=b(()=>{"use strict";Q();aw=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),cw=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:aw.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"}),lw=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var od,dw,ad,cd,ld,dd,uw,ud=b(()=>{"use strict";Q();od=f.enum(["info","important","critical"]),dw=f.enum(["pass","warn","fail"]),ad=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),cd=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),ld=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")})]),dd=f.object({id:f.string().min(1),title:f.string().min(1),severity:od,weight:f.number().int().positive().max(100),applies_when:cd,check:ld,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:ad.optional()}),uw=f.object({version:f.literal(1),checks:f.array(dd).min(1)})});function fw(e){if(!pw.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function qr(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 mw(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var pw,Yr,pd,fd,Se,md,hw,hd=b(()=>{"use strict";Q();pw=/^\d{4}-\d{2}-\d{2}$/;o(fw,"isRealDate");Yr=f.string().refine(fw,{message:"expected a real calendar date as YYYY-MM-DD"}),pd=["exact","prefix"],fd=f.enum(pd),Se=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),md=f.object({model_pattern:f.string().min(1).max(100),match_kind:fd,valid_from:Yr,valid_to:Yr.nullable().optional(),input:Se,output:Se,cache_read:Se,cache_write_5m:Se,cache_write_1h:Se,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Se.optional(),output_above_200k:Se.optional(),cache_read_above_200k:Se.optional(),cache_write_5m_above_200k:Se.optional(),cache_write_1h_above_200k:Se.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=>qr(e)===0||qr(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"||qr(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=>qr(e)===0||e.context_threshold_tokens==null||e.context_threshold_tokens===2e5,{message:"above-rates are only supported at context_threshold_tokens: 200000 \u2014 the analyzer groups against that constant and cannot see another boundary",path:["context_threshold_tokens"]});o(qr,"aboveRateCount");o(mw,"rowKey");hw=f.object({changelog:f.string().min(1).max(500),as_of:Yr,source_url:f.string().url().max(500),rows:f.array(md).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let a=mw(i),c=n.get(a);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,s)});let r=new Map;e.rows.forEach((i,s)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:s,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,a)=>s.r.valid_from.localeCompare(a.r.valid_from));for(let s=0;s<i.length-1;s++){let a=i[s],c=i[s+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:f.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var on=b(()=>{"use strict"});var Jn=b(()=>{"use strict"});var bd=b(()=>{"use strict";Jn();on()});var wd=b(()=>{"use strict";on()});var vd=b(()=>{"use strict";Xe();Jn();on()});var kd=b(()=>{"use strict";Jn();on()});var Sd=b(()=>{"use strict";on();bd();wd();vd();kd();Jn()});var Pw,Mw,xd,$w,Ed,Ys,Ad,Td,Rd,Id,Lw,Js=b(()=>{"use strict";Q();Xe();Pw=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Mw=64,xd=200,$w=1e3,Ed=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")),Ys=f.enum(["low","medium","high"]),Ad=f.object({owner:f.string().min(1).max(160).optional(),risk_level:Ys.optional(),reviewed_at:Ed.optional()}).default({}),Td=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}),Rd=f.object({lesson_query:Td,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:[]}),Id=f.object({id:f.string().min(6).max(Mw).regex(Pw,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:Ed,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(xd,`summary must be \u2264 ${xd} chars (rendered as one line in skill_index)`),description:f.string().max($w).optional(),applies_to:Vr,membership:Rd,governance:Ad}),Lw=Id.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var Cd,Nd,Od,Dd,Pd,Md,Fw,$d,jw,Uw,Ld=b(()=>{"use strict";Q();Js();Cd=f.enum(["maind","agent-skill"]),Nd=f.enum(["ready","needs_attention","blocked"]),Od=f.enum(["info","important","critical"]),Dd=f.enum(["pass","warn","fail"]),Pd=f.enum(["structure","governance","scope","membership","package","references"]),Md=f.object({id:f.string().min(1),title:f.string().min(1),status:Dd,severity:Od,category:Pd,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),Fw=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({}),$d=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(),jw=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:$d,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),Uw=f.object({format:Cd,subject:f.string().min(1),status:Nd,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(Md),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var Xs=b(()=>{"use strict"});var Fd,Gw,jd,Ud,Hd,an,Ww,Gd,Wd,Bd,Kd,Vd,zd,qd,Yd,Bw,Jd,Xd,Zd,Jr,Zs,Qd,eu,Kw,tu=b(()=>{"use strict";Q();Xe();Xs();Fd=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Gw=f.enum(Fd),jd=["verdict","advisory"],Ud=f.enum(jd),Hd=["block","warn","note"],an=f.enum(Hd),Ww=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:Kr,scope:Br,grade:Ud,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()}),Gd=["open","warn","info"],Wd=f.enum(Gd),Bd=["introduced","pre_existing"],Kd=f.enum(Bd),Vd=["full","partial","none"],zd=f.enum(Vd),qd=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:Wd,baseline:Kd,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Yd=f.object({version:f.literal(1).default(1),actions:f.object({required:an.default("block"),recommended:an.default("warn"),info:an.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:an})).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:an,reason:f.string().min(1).max(200)})).max(32).optional()}),Bw=Yd.parse({}),Jd=["ran","not_applicable","unavailable","ungraded"],Xd=f.enum(Jd),Zd=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),state:Xd}),Jr=1e3,Zs=f.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Qd=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()}),eu=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:zd}),Kw=f.object({changed_symbols:f.array(Qd).max(Jr),risk_flags:f.array(f.string().max(64)).max(16),detector_findings:f.array(qd).max(64),detector_runs:f.array(Zd).min(1).max(32),diff_stats:eu,commit_sha:Zs.optional(),base_sha:Zs.optional(),merge_base_sha:Zs.optional(),dirty:f.boolean().optional(),code_index_version:f.string().min(1).max(32).optional()})});var nu,ru,iu,su,ou,Qs,Vw,zw,au,cu,lu,du,uu,qw,Yw,pu,fu,mu,Jw,hu=b(()=>{"use strict";Q();nu=14,ru=14,iu=14,su=1,ou=365,Qs=f.number().int().min(su).max(ou),Vw=["propose","direct"],zw="propose",au=["propose","direct"],cu="propose",lu=["propose","direct"],du="propose",uu=["off","propose","direct"],qw=["member","admin","owner"],Yw="member",pu="off",fu="en",mu=f.object({version:f.literal(1).default(1),at_risk_days:Qs.default(nu),stagnation_days:Qs.default(ru),agent_date_mode:f.enum(Vw).default(zw),health_manual_ttl_days:Qs.default(iu),agent_event_mode:f.enum(au).default(cu),agent_update_mode:f.enum(lu).default(du),agent_pull_mode:f.enum(uu).default(pu),org_wide_authoring_min_role:f.enum(qw).default(Yw),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(fu)}),Jw=mu.parse({})});var gu,Xw,yu=b(()=>{"use strict";Q();gu=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Xw=gu.parse({})});var _u,bu,Zw,Qw,wu=b(()=>{"use strict";Q();_u=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([])}),bu=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:_u.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()}),Zw=bu.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()}),Qw=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var vu=b(()=>{"use strict"});function Xr(e){let t=[],n=null;return e.split(`
|
|
3
|
-
`).forEach((r,i)=>{let s=r.trim(),
|
|
4
|
-
`).slice(0,1e3)}var
|
|
2
|
+
var Tl=Object.defineProperty;var a=(t,e)=>Tl(t,"name",{value:e,configurable:!0});var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>{for(var n in e)Tl(t,n,{get:e[n],enumerable:!0})};function Al(t){let e;try{e=JSON.parse(t)}catch{return{kind:"opaque"}}if(typeof e!="object"||e===null||Array.isArray(e))return{kind:"opaque"};let n=e;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 nn(t,e,n){return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:n??`maind gateway: tool '${e}' 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 Gs(t,e,n,r){return{at:r,event:t,server:e,tool:n}}function Bs(t,e,n,r,i,s){return{at:r,event:t,server:e,tool:n,convention_id:i,convention_version:s}}function Ks(t,e,n,r){return{at:r,event:t,server:e,tool:n}}var Vs=b(()=>{"use strict";a(Al,"parseFrame");a(nn,"denyResult");a(Gs,"toolEvent");a(Bs,"policyEvent");a(Ks,"shaEvent")});import{execFileSync as Cl}from"node:child_process";function Ol(t){return t.verdict==="fabricated"&&(t.matchedPrefixLen??0)>=mb}function hb(t){let e;try{e=JSON.parse(t)}catch{return[]}if(typeof e!="object"||e===null)return[];let n=e.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 ub){let o=r[s];typeof o=="string"&&Nl.test(o)&&i.push({field:s,sha:o})}for(let[s,o]of pb){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[o];typeof l=="string"&&Nl.test(l)&&i.push({field:`${s}.${o}`,sha:l})}return i}function gb(t,e){let n=e(t);if(n===t)return{field:"",sha:t,verdict:"proven"};if(n!==null)return{field:"",sha:t,verdict:"unknown"};let r=t.slice(0,Il);for(let i=Il;i>=fb;i--){let s=r.slice(0,i),o=e(s);if(o!==null&&o.startsWith(s))return{field:"",sha:t,verdict:"fabricated",matchedPrefixOf:o,matchedPrefixLen:i}}return{field:"",sha:t,verdict:"unknown"}}function rn(t,e){return t.verdict==="fabricated"?[`${e?"DENIED":"WARNING"}: the ${t.field} you passed (${t.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${t.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`.",e?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${t.field} you passed (${t.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 Dl(){let t={...process.env};for(let e of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete t[e];return t}function Vr(t=process.cwd()){try{let n=Cl("git",["rev-parse","--show-toplevel"],{cwd:t,env:Dl(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function yb(t){return e=>{try{let r=Cl("git",["rev-parse","--verify","--quiet",`${e}^{commit}`],{cwd:t,env:Dl(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function zr(t,e){if(e===null)return[];let n=hb(t);if(n.length===0)return[];let r=yb(e),i=[];for(let{field:s,sha:o}of n){let c=gb(o,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var ub,pb,Nl,fb,Il,mb,zs=b(()=>{"use strict";ub=["commit_sha","base_sha","head_sha"],pb=[["diff_stats","head_sha"],["diff_stats","base_sha"]],Nl=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,fb=7,Il=12,mb=10;a(Ol,"isDenyGrade");a(hb,"extractShaArgs");a(gb,"classifySha");a(rn,"shaFindingText");a(Dl,"cleanGitEnv");a(Vr,"resolveRepoRootForSha");a(yb,"gitShaResolver");a(zr,"inspectLineForShas")});var Ml=b(()=>{"use strict"});var P,qs,T,ke,er=b(()=>{(function(t){t.assertEqual=i=>{};function e(i){}a(e,"assertIs"),t.assertIs=e;function n(i){throw new Error}a(n,"assertNever"),t.assertNever=n,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),o={};for(let c of s)o[c]=i[c];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.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},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.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"),t.joinValues=r,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(P||(P={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(qs||(qs={}));T=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ke=a(t=>{switch(typeof t){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(t)?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(t)?T.array:t===null?T.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?T.promise:typeof Map<"u"&&t instanceof Map?T.map:typeof Set<"u"&&t instanceof Set?T.set:typeof Date<"u"&&t instanceof Date?T.date:T.object;default:return T.unknown}},"getParsedType")});var v,_b,ae,qr=b(()=>{er();v=P.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"]),_b=a(t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ae=class t extends Error{static{a(this,"ZodError")}get errors(){return this.issues}constructor(e){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=e}format(e){let n=e||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(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,P.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=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(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ae.create=t=>new ae(t)});var bb,Le,Ys=b(()=>{qr();er();bb=a((t,e)=>{let n;switch(t.code){case v.invalid_type:t.received===T.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,P.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${P.joinValues(t.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${P.joinValues(t.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${P.joinValues(t.options)}, received '${t.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:P.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case v.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case v.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=e.defaultError,P.assertNever(t)}return{message:n}},"errorMap"),Le=bb});function wb(t){Pl=t}function sn(){return Pl}var Pl,Yr=b(()=>{Ys();Pl=Le;a(wb,"setErrorMap");a(sn,"getErrorMap")});function E(t,e){let n=sn(),r=tr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Le?void 0:Le].filter(i=>!!i)});t.common.issues.push(r)}var tr,vb,V,I,mt,Z,Jr,Xr,Je,on,Js=b(()=>{Yr();Ys();tr=a(t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,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:e,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),vb=[];a(E,"addIssueToContext");V=class t{static{a(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let i of n){if(i.status==="aborted")return I;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let s=await i.key,o=await i.value;r.push({key:s,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return I;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:e.value,value:r}}},I=Object.freeze({status:"aborted"}),mt=a(t=>({status:"dirty",value:t}),"DIRTY"),Z=a(t=>({status:"valid",value:t}),"OK"),Jr=a(t=>t.status==="aborted","isAborted"),Xr=a(t=>t.status==="dirty","isDirty"),Je=a(t=>t.status==="valid","isValid"),on=a(t=>typeof Promise<"u"&&t instanceof Promise,"isAsync")});var Ll=b(()=>{});var N,$l=b(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}))});function O(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:i}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:a((o,c)=>{let{message:l}=t;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 Hl(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Fb(t){return new RegExp(`^${Hl(t)}$`)}function Wl(t){let e=`${Ul}T${Hl(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function jb(t,e){return!!((e==="v4"||!e)&&Cb.test(t)||(e==="v6"||!e)&&Db.test(t))}function Ub(t,e){if(!Rb.test(t))return!1;try{let[n]=t.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||e&&i.alg!==e)}catch{return!1}}function Hb(t,e){return!!((e==="v4"||!e)&&Ob.test(t)||(e==="v6"||!e)&&Mb.test(t))}function Wb(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}function an(t){if(t instanceof ce){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=de.create(an(r))}return new ce({...t._def,shape:a(()=>e,"shape")})}else return t instanceof je?new je({...t._def,type:an(t.element)}):t instanceof de?de.create(an(t.unwrap())):t instanceof Se?Se.create(an(t.unwrap())):t instanceof xe?xe.create(t.items.map(e=>an(e))):t}function Zs(t,e){let n=ke(t),r=ke(e);if(t===e)return{valid:!0,data:t};if(n===T.object&&r===T.object){let i=P.objectKeys(e),s=P.objectKeys(t).filter(c=>i.indexOf(c)!==-1),o={...t,...e};for(let c of s){let l=Zs(t[c],e[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(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],c=e[s],l=Zs(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&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Gl(t,e){return new Et({values:t,typeName:C.ZodEnum,...O(e)})}function jl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Bl(t,e={},n){return t?Ze.create().superRefine((r,i)=>{let s=t(r);if(s instanceof Promise)return s.then(o=>{if(!o){let c=jl(e,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let o=jl(e,r),c=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:c})}}):Ze.create()}var ue,Fl,M,kb,xb,Sb,Eb,Tb,Rb,Ab,Nb,Ib,Xs,Cb,Ob,Db,Mb,Pb,Lb,Ul,$b,Xe,ht,gt,yt,_t,cn,bt,wt,Ze,Fe,he,ln,je,ce,vt,$e,Zr,kt,xe,Qr,dn,un,ei,xt,St,Et,Tt,Qe,pe,de,Se,Rt,At,pn,Gb,nr,rr,Nt,Bb,C,Kb,Kl,Vl,Vb,zb,zl,qb,Yb,Jb,Xb,Zb,Qb,ew,tw,nw,rw,iw,sw,ow,aw,cw,lw,dw,uw,pw,fw,mw,hw,gw,yw,_w,bw,ww,vw,kw,xw,Sw,Ew,Tw,Rw,ql=b(()=>{qr();Yr();$l();Js();er();ue=class{static{a(this,"ParseInputLazyPath")}constructor(e,n,r,i){this._cachedPath=[],this.parent=e,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}},Fl=a((t,e)=>{if(Je(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ae(t.common.issues);return this._error=n,this._error}}},"handleResult");a(O,"processCreateParams");M=class{static{a(this,"ZodType")}get description(){return this._def.description}_getType(e){return ke(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new V,ctx:{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(on(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)},i=this._parseSync({data:e,path:r.path,parent:r});return Fl(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Je(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:e,path:[],parent:n}).then(r=>Je(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)},i=this._parse({data:e,path:r.path,parent:r}),s=await(on(i)?i:Promise.resolve(i));return Fl(r,s)}refine(e,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=e(i),c=a(()=>s.addIssue({code:v.custom,...r(i)}),"setError");return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,n){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new pe({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 de.create(this,this._def)}nullable(){return Se.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return je.create(this)}promise(){return Qe.create(this,this._def)}or(e){return vt.create([this,e],this._def)}and(e){return kt.create(this,e,this._def)}transform(e){return new pe({...O(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Rt({...O(this._def),innerType:this,defaultValue:n,typeName:C.ZodDefault})}brand(){return new nr({typeName:C.ZodBranded,type:this,...O(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new At({...O(this._def),innerType:this,catchValue:n,typeName:C.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return rr.create(this,e)}readonly(){return Nt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kb=/^c[^\s-]{8,}$/i,xb=/^[0-9a-z]+$/,Sb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Eb=/^[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,Tb=/^[a-z0-9_-]{21}$/i,Rb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ab=/^[-+]?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)?)??$/,Nb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ib="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Cb=/^(?:(?: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])$/,Ob=/^(?:(?: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])$/,Db=/^(([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]))$/,Mb=/^(([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])$/,Pb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Lb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ul="((\\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])))",$b=new RegExp(`^${Ul}$`);a(Hl,"timeRegexSource");a(Fb,"timeRegex");a(Wl,"datetimeRegex");a(jb,"isValidIP");a(Ub,"isValidJWT");a(Hb,"isValidCidr");Xe=class t extends M{static{a(this,"ZodString")}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==T.string){let s=this._getOrReturnCtx(e);return E(s,{code:v.invalid_type,expected:T.string,received:s.parsedType}),I}let r=new V,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),E(i,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),E(i,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,c=e.data.length<s.value;(o||c)&&(i=this._getOrReturnCtx(e,i),o?E(i,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&E(i,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Nb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"email",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Xs||(Xs=new RegExp(Ib,"u")),Xs.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"emoji",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Eb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"uuid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Tb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"nanoid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")kb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"cuid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")xb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"cuid2",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Sb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"ulid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),E(i,{validation:"url",code:v.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"regex",code:v.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),E(i,{code:v.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),E(i,{code:v.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),E(i,{code:v.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Wl(s).test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:v.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?$b.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:v.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Fb(s).test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:v.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Ab.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"duration",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?jb(e.data,s.version)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"ip",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Ub(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"jwt",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Hb(e.data,s.version)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"cidr",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Pb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"base64",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Lb.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"base64url",code:v.invalid_string,message:s.message}),r.dirty()):P.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:v.invalid_string,...N.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...N.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...N.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...N.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...N.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...N.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...N.errToObj(n)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Xe.create=t=>new Xe({checks:[],typeName:C.ZodString,coerce:t?.coerce??!1,...O(t)});a(Wb,"floatSafeRemainder");ht=class t extends M{static{a(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==T.number){let s=this._getOrReturnCtx(e);return E(s,{code:v.invalid_type,expected:T.number,received:s.parsedType}),I}let r,i=new V;for(let s of this._def.checks)s.kind==="int"?P.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),E(r,{code:v.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),E(r,{code:v.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),E(r,{code:v.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?Wb(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),E(r,{code:v.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),E(r,{code:v.not_finite,message:s.message}),i.dirty()):P.assertNever(s);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:N.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&P.isInteger(e.value))}get isFinite(){let e=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"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};ht.create=t=>new ht({checks:[],typeName:C.ZodNumber,coerce:t?.coerce||!1,...O(t)});gt=class t extends M{static{a(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==T.bigint)return this._getInvalidInput(e);let r,i=new V;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),E(r,{code:v.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),E(r,{code:v.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),E(r,{code:v.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):P.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return E(n,{code:v.invalid_type,expected:T.bigint,received:n.parsedType}),I}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:N.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};gt.create=t=>new gt({checks:[],typeName:C.ZodBigInt,coerce:t?.coerce??!1,...O(t)});yt=class extends M{static{a(this,"ZodBoolean")}_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==T.boolean){let r=this._getOrReturnCtx(e);return E(r,{code:v.invalid_type,expected:T.boolean,received:r.parsedType}),I}return Z(e.data)}};yt.create=t=>new yt({typeName:C.ZodBoolean,coerce:t?.coerce||!1,...O(t)});_t=class t extends M{static{a(this,"ZodDate")}_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==T.date){let s=this._getOrReturnCtx(e);return E(s,{code:v.invalid_type,expected:T.date,received:s.parsedType}),I}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:v.invalid_date}),I}let r=new V,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),E(i,{code:v.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),E(i,{code:v.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):P.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};_t.create=t=>new _t({checks:[],coerce:t?.coerce||!1,typeName:C.ZodDate,...O(t)});cn=class extends M{static{a(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==T.symbol){let r=this._getOrReturnCtx(e);return E(r,{code:v.invalid_type,expected:T.symbol,received:r.parsedType}),I}return Z(e.data)}};cn.create=t=>new cn({typeName:C.ZodSymbol,...O(t)});bt=class extends M{static{a(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==T.undefined){let r=this._getOrReturnCtx(e);return E(r,{code:v.invalid_type,expected:T.undefined,received:r.parsedType}),I}return Z(e.data)}};bt.create=t=>new bt({typeName:C.ZodUndefined,...O(t)});wt=class extends M{static{a(this,"ZodNull")}_parse(e){if(this._getType(e)!==T.null){let r=this._getOrReturnCtx(e);return E(r,{code:v.invalid_type,expected:T.null,received:r.parsedType}),I}return Z(e.data)}};wt.create=t=>new wt({typeName:C.ZodNull,...O(t)});Ze=class extends M{static{a(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return Z(e.data)}};Ze.create=t=>new Ze({typeName:C.ZodAny,...O(t)});Fe=class extends M{static{a(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return Z(e.data)}};Fe.create=t=>new Fe({typeName:C.ZodUnknown,...O(t)});he=class extends M{static{a(this,"ZodNever")}_parse(e){let n=this._getOrReturnCtx(e);return E(n,{code:v.invalid_type,expected:T.never,received:n.parsedType}),I}};he.create=t=>new he({typeName:C.ZodNever,...O(t)});ln=class extends M{static{a(this,"ZodVoid")}_parse(e){if(this._getType(e)!==T.undefined){let r=this._getOrReturnCtx(e);return E(r,{code:v.invalid_type,expected:T.void,received:r.parsedType}),I}return Z(e.data)}};ln.create=t=>new ln({typeName:C.ZodVoid,...O(t)});je=class t extends M{static{a(this,"ZodArray")}_parse(e){let{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==T.array)return E(n,{code:v.invalid_type,expected:T.array,received:n.parsedType}),I;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?v.too_big:v.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:v.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:v.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 ue(n,o,n.path,c)))).then(o=>V.mergeArray(r,o));let s=[...n.data].map((o,c)=>i.type._parseSync(new ue(n,o,n.path,c)));return V.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:N.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:N.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:N.toString(n)}})}nonempty(e){return this.min(1,e)}};je.create=(t,e)=>new je({type:t,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...O(e)});a(an,"deepPartialify");ce=class t 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 e=this._def.shape(),n=P.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==T.object){let d=this._getOrReturnCtx(e);return E(d,{code:v.invalid_type,expected:T.object,received:d.parsedType}),I}let{status:r,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof he&&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 ue(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof he){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:v.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 ue(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=>V.mergeObjectSync(r,d)):V.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:a((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:N.errToObj(e).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:a(()=>({...this._def.shape(),...e}),"shape")})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:a(()=>({...this._def.shape(),...e._def.shape()}),"shape"),typeName:C.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of P.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:a(()=>n,"shape")})}omit(e){let n={};for(let r of P.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:a(()=>n,"shape")})}deepPartial(){return an(this)}partial(e){let n={};for(let r of P.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new t({...this._def,shape:a(()=>n,"shape")})}required(e){let n={};for(let r of P.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof de;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:a(()=>n,"shape")})}keyof(){return Gl(P.objectKeys(this.shape))}};ce.create=(t,e)=>new ce({shape:a(()=>t,"shape"),unknownKeys:"strip",catchall:he.create(),typeName:C.ZodObject,...O(e)});ce.strictCreate=(t,e)=>new ce({shape:a(()=>t,"shape"),unknownKeys:"strict",catchall:he.create(),typeName:C.ZodObject,...O(e)});ce.lazycreate=(t,e)=>new ce({shape:t,unknownKeys:"strip",catchall:he.create(),typeName:C.ZodObject,...O(e)});vt=class extends M{static{a(this,"ZodUnion")}_parse(e){let{ctx:n}=this._processInputParams(e),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 ae(c.ctx.common.issues));return E(n,{code:v.invalid_union,unionErrors:o}),I}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 ae(l));return E(n,{code:v.invalid_union,unionErrors:c}),I}}get options(){return this._def.options}};vt.create=(t,e)=>new vt({options:t,typeName:C.ZodUnion,...O(e)});$e=a(t=>t instanceof xt?$e(t.schema):t instanceof pe?$e(t.innerType()):t instanceof St?[t.value]:t instanceof Et?t.options:t instanceof Tt?P.objectValues(t.enum):t instanceof Rt?$e(t._def.innerType):t instanceof bt?[void 0]:t instanceof wt?[null]:t instanceof de?[void 0,...$e(t.unwrap())]:t instanceof Se?[null,...$e(t.unwrap())]:t instanceof nr||t instanceof Nt?$e(t.unwrap()):t instanceof At?$e(t._def.innerType):[],"getDiscriminator"),Zr=class t extends M{static{a(this,"ZodDiscriminatedUnion")}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==T.object)return E(n,{code:v.invalid_type,expected:T.object,received:n.parsedType}),I;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:v.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),I)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let s of n){let o=$e(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,s)}}return new t({typeName:C.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...O(r)})}};a(Zs,"mergeValues");kt=class extends M{static{a(this,"ZodIntersection")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=a((s,o)=>{if(Jr(s)||Jr(o))return I;let c=Zs(s.value,o.value);return c.valid?((Xr(s)||Xr(o))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:v.invalid_intersection_types}),I)},"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}))}};kt.create=(t,e,n)=>new kt({left:t,right:e,typeName:C.ZodIntersection,...O(n)});xe=class t extends M{static{a(this,"ZodTuple")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==T.array)return E(r,{code:v.invalid_type,expected:T.array,received:r.parsedType}),I;if(r.data.length<this._def.items.length)return E(r,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:v.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 ue(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>V.mergeArray(n,o)):V.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xe({items:t,typeName:C.ZodTuple,rest:null,...O(e)})};Qr=class t extends M{static{a(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==T.object)return E(r,{code:v.invalid_type,expected:T.object,received:r.parsedType}),I;let i=[],s=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ue(r,c,r.path,c)),value:o._parse(new ue(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?V.mergeObjectAsync(n,i):V.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof M?new t({keyType:e,valueType:n,typeName:C.ZodRecord,...O(r)}):new t({keyType:Xe.create(),valueType:e,typeName:C.ZodRecord,...O(n)})}},dn=class extends M{static{a(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==T.map)return E(r,{code:v.invalid_type,expected:T.map,received:r.parsedType}),I;let i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ue(r,c,r.path,[d,"key"])),value:s._parse(new ue(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 I;(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 I;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};dn.create=(t,e,n)=>new dn({valueType:e,keyType:t,typeName:C.ZodMap,...O(n)});un=class t extends M{static{a(this,"ZodSet")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==T.set)return E(r,{code:v.invalid_type,expected:T.set,received:r.parsedType}),I;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(E(r,{code:v.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:v.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 I;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 ue(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(e,n){return new t({...this._def,minSize:{value:e,message:N.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:N.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({valueType:t,minSize:null,maxSize:null,typeName:C.ZodSet,...O(e)});ei=class t extends M{static{a(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==T.function)return E(n,{code:v.invalid_type,expected:T.function,received:n.parsedType}),I;function r(c,l){return tr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),Le].filter(d=>!!d),issueData:{code:v.invalid_arguments,argumentsError:l}})}a(r,"makeArgsIssue");function i(c,l){return tr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),Le].filter(d=>!!d),issueData:{code:v.invalid_return_type,returnTypeError:l}})}a(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Qe){let c=this;return Z(async function(...l){let d=new ae([]),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 Z(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new ae([r(l,d.error)]);let u=Reflect.apply(o,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new ae([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xe.create(e).rest(Fe.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||xe.create([]).rest(Fe.create()),returns:n||Fe.create(),typeName:C.ZodFunction,...O(r)})}},xt=class extends M{static{a(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};xt.create=(t,e)=>new xt({getter:t,typeName:C.ZodLazy,...O(e)});St=class extends M{static{a(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return E(n,{received:n.data,code:v.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:e.data}}get value(){return this._def.value}};St.create=(t,e)=>new St({value:t,typeName:C.ZodLiteral,...O(e)});a(Gl,"createZodEnum");Et=class t extends M{static{a(this,"ZodEnum")}_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return E(n,{expected:P.joinValues(r),received:n.parsedType,code:v.invalid_type}),I}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return E(n,{received:n.data,code:v.invalid_enum_value,options:r}),I}return Z(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Et.create=Gl;Tt=class extends M{static{a(this,"ZodNativeEnum")}_parse(e){let n=P.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==T.string&&r.parsedType!==T.number){let i=P.objectValues(n);return E(r,{expected:P.joinValues(i),received:r.parsedType,code:v.invalid_type}),I}if(this._cache||(this._cache=new Set(P.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=P.objectValues(n);return E(r,{received:r.data,code:v.invalid_enum_value,options:i}),I}return Z(e.data)}get enum(){return this._def.values}};Tt.create=(t,e)=>new Tt({values:t,typeName:C.ZodNativeEnum,...O(e)});Qe=class extends M{static{a(this,"ZodPromise")}unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==T.promise&&n.common.async===!1)return E(n,{code:v.invalid_type,expected:T.promise,received:n.parsedType}),I;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return Z(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Qe.create=(t,e)=>new Qe({type:t,typeName:C.ZodPromise,...O(e)});pe=class extends M{static{a(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),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 I;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?I:l.status==="dirty"?mt(l.value):n.value==="dirty"?mt(l.value):l});{if(n.value==="aborted")return I;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?I:c.status==="dirty"?mt(c.value):n.value==="dirty"?mt(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"?I:(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"?I:(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(!Je(o))return I;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=>Je(o)?Promise.resolve(i.transform(o.value,s)).then(c=>({status:n.value,value:c})):I);P.assertNever(i)}};pe.create=(t,e,n)=>new pe({schema:t,typeName:C.ZodEffects,effect:e,...O(n)});pe.createWithPreprocess=(t,e,n)=>new pe({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,...O(n)});de=class extends M{static{a(this,"ZodOptional")}_parse(e){return this._getType(e)===T.undefined?Z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};de.create=(t,e)=>new de({innerType:t,typeName:C.ZodOptional,...O(e)});Se=class extends M{static{a(this,"ZodNullable")}_parse(e){return this._getType(e)===T.null?Z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Se.create=(t,e)=>new Se({innerType:t,typeName:C.ZodNullable,...O(e)});Rt=class extends M{static{a(this,"ZodDefault")}_parse(e){let{ctx:n}=this._processInputParams(e),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}};Rt.create=(t,e)=>new Rt({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...O(e)});At=class extends M{static{a(this,"ZodCatch")}_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return on(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ae(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};At.create=(t,e)=>new At({innerType:t,typeName:C.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...O(e)});pn=class extends M{static{a(this,"ZodNaN")}_parse(e){if(this._getType(e)!==T.nan){let r=this._getOrReturnCtx(e);return E(r,{code:v.invalid_type,expected:T.nan,received:r.parsedType}),I}return{status:"valid",value:e.data}}};pn.create=t=>new pn({typeName:C.ZodNaN,...O(t)});Gb=Symbol("zod_brand"),nr=class extends M{static{a(this,"ZodBranded")}_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},rr=class t extends M{static{a(this,"ZodPipeline")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);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"?I:s.status==="dirty"?(n.dirty(),mt(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"?I:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:C.ZodPipeline})}},Nt=class extends M{static{a(this,"ZodReadonly")}_parse(e){let n=this._def.innerType._parse(e),r=a(i=>(Je(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return on(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Nt.create=(t,e)=>new Nt({innerType:t,typeName:C.ZodReadonly,...O(e)});a(jl,"cleanParams");a(Bl,"custom");Bb={object:ce.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(C||(C={}));Kb=a((t,e={message:`Input not instance of ${t.name}`})=>Bl(n=>n instanceof t,e),"instanceOfType"),Kl=Xe.create,Vl=ht.create,Vb=pn.create,zb=gt.create,zl=yt.create,qb=_t.create,Yb=cn.create,Jb=bt.create,Xb=wt.create,Zb=Ze.create,Qb=Fe.create,ew=he.create,tw=ln.create,nw=je.create,rw=ce.create,iw=ce.strictCreate,sw=vt.create,ow=Zr.create,aw=kt.create,cw=xe.create,lw=Qr.create,dw=dn.create,uw=un.create,pw=ei.create,fw=xt.create,mw=St.create,hw=Et.create,gw=Tt.create,yw=Qe.create,_w=pe.create,bw=de.create,ww=Se.create,vw=pe.createWithPreprocess,kw=rr.create,xw=a(()=>Kl().optional(),"ostring"),Sw=a(()=>Vl().optional(),"onumber"),Ew=a(()=>zl().optional(),"oboolean"),Tw={string:a(t=>Xe.create({...t,coerce:!0}),"string"),number:a(t=>ht.create({...t,coerce:!0}),"number"),boolean:a(t=>yt.create({...t,coerce:!0}),"boolean"),bigint:a(t=>gt.create({...t,coerce:!0}),"bigint"),date:a(t=>_t.create({...t,coerce:!0}),"date")},Rw=I});var f={};oe(f,{BRAND:()=>Gb,DIRTY:()=>mt,EMPTY_PATH:()=>vb,INVALID:()=>I,NEVER:()=>Rw,OK:()=>Z,ParseStatus:()=>V,Schema:()=>M,ZodAny:()=>Ze,ZodArray:()=>je,ZodBigInt:()=>gt,ZodBoolean:()=>yt,ZodBranded:()=>nr,ZodCatch:()=>At,ZodDate:()=>_t,ZodDefault:()=>Rt,ZodDiscriminatedUnion:()=>Zr,ZodEffects:()=>pe,ZodEnum:()=>Et,ZodError:()=>ae,ZodFirstPartyTypeKind:()=>C,ZodFunction:()=>ei,ZodIntersection:()=>kt,ZodIssueCode:()=>v,ZodLazy:()=>xt,ZodLiteral:()=>St,ZodMap:()=>dn,ZodNaN:()=>pn,ZodNativeEnum:()=>Tt,ZodNever:()=>he,ZodNull:()=>wt,ZodNullable:()=>Se,ZodNumber:()=>ht,ZodObject:()=>ce,ZodOptional:()=>de,ZodParsedType:()=>T,ZodPipeline:()=>rr,ZodPromise:()=>Qe,ZodReadonly:()=>Nt,ZodRecord:()=>Qr,ZodSchema:()=>M,ZodSet:()=>un,ZodString:()=>Xe,ZodSymbol:()=>cn,ZodTransformer:()=>pe,ZodTuple:()=>xe,ZodType:()=>M,ZodUndefined:()=>bt,ZodUnion:()=>vt,ZodUnknown:()=>Fe,ZodVoid:()=>ln,addIssueToContext:()=>E,any:()=>Zb,array:()=>nw,bigint:()=>zb,boolean:()=>zl,coerce:()=>Tw,custom:()=>Bl,date:()=>qb,datetimeRegex:()=>Wl,defaultErrorMap:()=>Le,discriminatedUnion:()=>ow,effect:()=>_w,enum:()=>hw,function:()=>pw,getErrorMap:()=>sn,getParsedType:()=>ke,instanceof:()=>Kb,intersection:()=>aw,isAborted:()=>Jr,isAsync:()=>on,isDirty:()=>Xr,isValid:()=>Je,late:()=>Bb,lazy:()=>fw,literal:()=>mw,makeIssue:()=>tr,map:()=>dw,nan:()=>Vb,nativeEnum:()=>gw,never:()=>ew,null:()=>Xb,nullable:()=>ww,number:()=>Vl,object:()=>rw,objectUtil:()=>qs,oboolean:()=>Ew,onumber:()=>Sw,optional:()=>bw,ostring:()=>xw,pipeline:()=>kw,preprocess:()=>vw,promise:()=>yw,quotelessJson:()=>_b,record:()=>lw,set:()=>uw,setErrorMap:()=>wb,strictObject:()=>iw,string:()=>Kl,symbol:()=>Yb,transformer:()=>_w,tuple:()=>cw,undefined:()=>Jb,union:()=>sw,unknown:()=>Qb,util:()=>P,void:()=>tw});var Qs=b(()=>{Yr();Js();Ll();er();ql();qr()});var Q=b(()=>{Qs();Qs()});var eo,to=b(()=>{"use strict";Q();eo=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((t,e)=>{t.type==="template"&&(t.template_body||e.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),t.target_file||e.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var Aw,Yl=b(()=>{"use strict";Q();to();Aw=eo.superRefine((t,e)=>{t.type!=="template"&&e.addIssue({code:f.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!t.template_body||t.template_body.length===0)&&e.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!t.target_file||t.target_file.length===0)&&e.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),t.tier!=="curated"&&e.addIssue({code:f.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var Jl,Xl,Zl,Ql,no,ed,td,nd,Nw,rd=b(()=>{"use strict";Q();Jl=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Xl=f.enum(Jl),Zl=["new_to_ai_agents","new_to_this_client","experienced"],Ql=f.enum(Zl),no=[{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"}],ed=no.map(t=>t.header),td=f.object({experience_level:f.array(Ql).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),nd=f.object({id:f.string().min(1),client:Xl,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:td,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Nw=nd.extend({body:f.string().min(1)})});var sd,ti,od,ni,Iw,Cw,ad,cd,ld,dd,ri,Ow,Dw,id,Mw,ud,Pw,pd=b(()=>{"use strict";Q();sd=["operating_procedure","code_review","communication_style"],ti=f.enum(sd),od=["info","recommended","required"],ni=f.enum(od),Iw=["optional","default_on","mandatory"],Cw=f.enum(Iw),ad=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],cd=f.enum(ad),ld=["verify","contribute","mixed"],dd=f.enum(ld),ri=f.object({clients:f.array(cd).default([]),stacks:f.array(f.string()).default([]),intents:f.array(dd).default([])}).default({clients:[],stacks:[],intents:[]}),Ow=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Dw=64,id=200,Mw=f.preprocess(t=>t instanceof Date&&!Number.isNaN(t.getTime())?t.toISOString().slice(0,10):t,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),ud=f.object({id:f.string().min(5).max(Dw).regex(Ow,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:ti,version:f.number().int().min(1),changed_at:Mw,changelog:f.string().max(500).optional(),applies_to:ri,severity:ni.default("recommended"),disableability:Cw.default("default_on"),summary:f.string().min(1).max(id,`summary must be \u2264 ${id} 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()}),Pw=ud.extend({body:f.string().min(1)})});var et=b(()=>{"use strict";to();Yl();rd();pd()});var ro,ii,io,fd,md,hd,Lw,gd=b(()=>{"use strict";Q();ro=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),ii=f.number().min(0).max(1).optional(),io=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:ii,right:ii,bottom:ii,left:ii}).optional()}),fd=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")}),md=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:fd.optional(),blocks:f.array(f.discriminatedUnion("type",[ro,io])).max(50)}),hd=f.discriminatedUnion("type",[ro,io,md]),Lw=f.array(hd).max(100)});var yd,$w,_d,bd,Fw,jw,Uw,wd=b(()=>{"use strict";Q();yd=["free","solo_pro","team","enterprise"],$w=f.enum(yd),_d=["solo_pro","team","enterprise"],bd=f.enum(_d),Fw=f.string().refine(t=>!Number.isNaN(Date.parse(t)),"must be ISO datetime"),jw=f.object({user_id:f.string().uuid(),tier:bd,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:Fw.nullable().optional(),auto_revoke_on_stripe:f.boolean().optional().default(!1)}).refine(t=>t.effective_until==null?!0:new Date(t.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),Uw=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var vd=b(()=>{"use strict"});var Hw,Ww,Gw,kd=b(()=>{"use strict";Q();Hw=f.string().refine(t=>!Number.isNaN(Date.parse(t)),"must be ISO datetime"),Ww=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:Hw.nullable().optional(),auto_revoke_on_stripe:f.boolean().optional().default(!1)}).refine(t=>t.effective_until==null?!0:new Date(t.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),Gw=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var xd,Bw,Sd,Ed,Td,Rd,Kw,Ad=b(()=>{"use strict";Q();xd=f.enum(["info","important","critical"]),Bw=f.enum(["pass","warn","fail"]),Sd=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),Ed=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),Td=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")})]),Rd=f.object({id:f.string().min(1),title:f.string().min(1),severity:xd,weight:f.number().int().positive().max(100),applies_when:Ed,check:Td,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:Sd.optional()}),Kw=f.object({version:f.literal(1),checks:f.array(Rd).min(1)})});function zw(t){if(!Vw.test(t))return!1;let e=new Date(`${t}T00:00:00Z`);return!Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}function si(t){return[t.input_above_200k,t.output_above_200k,t.cache_read_above_200k,t.cache_write_5m_above_200k,t.cache_write_1h_above_200k].filter(e=>e!==void 0).length}function qw(t){return`${t.model_pattern}|${t.match_kind}|${t.valid_from}`}var Vw,oi,Nd,Id,Ee,Cd,Yw,Od=b(()=>{"use strict";Q();Vw=/^\d{4}-\d{2}-\d{2}$/;a(zw,"isRealDate");oi=f.string().refine(zw,{message:"expected a real calendar date as YYYY-MM-DD"}),Nd=["exact","prefix"],Id=f.enum(Nd),Ee=f.number().finite().min(0).refine(t=>Number.isInteger(t*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Cd=f.object({model_pattern:f.string().min(1).max(100),match_kind:Id,valid_from:oi,valid_to:oi.nullable().optional(),input:Ee,output:Ee,cache_read:Ee,cache_write_5m:Ee,cache_write_1h:Ee,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Ee.optional(),output_above_200k:Ee.optional(),cache_read_above_200k:Ee.optional(),cache_write_5m_above_200k:Ee.optional(),cache_write_1h_above_200k:Ee.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(t=>!t.valid_to||t.valid_to>t.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(t=>si(t)===0||si(t)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(t=>t.long_context==="tiered"||si(t)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(t=>t.context_threshold_tokens==null||t.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(t=>si(t)===0||t.context_threshold_tokens==null||t.context_threshold_tokens===2e5,{message:"above-rates are only supported at context_threshold_tokens: 200000 \u2014 the analyzer groups against that constant and cannot see another boundary",path:["context_threshold_tokens"]});a(si,"aboveRateCount");a(qw,"rowKey");Yw=f.object({changelog:f.string().min(1).max(500),as_of:oi,source_url:f.string().url().max(500),rows:f.array(Cd).min(1)}).strict().superRefine((t,e)=>{let n=new Map;t.rows.forEach((i,s)=>{let o=qw(i),c=n.get(o);c!==void 0?e.addIssue({code:f.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${o} (first at rows[${c}])`}):n.set(o,s)});let r=new Map;t.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)&&e.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 fn=b(()=>{"use strict"});var ir=b(()=>{"use strict"});var Ld=b(()=>{"use strict";ir();fn()});var $d=b(()=>{"use strict";fn()});var Fd=b(()=>{"use strict";et();ir();fn()});var jd=b(()=>{"use strict";ir();fn()});var Ud=b(()=>{"use strict";fn();Ld();$d();Fd();jd();ir()});var mv,hv,Hd,gv,Wd,so,Gd,Bd,Kd,Vd,yv,oo=b(()=>{"use strict";Q();et();mv=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,hv=64,Hd=200,gv=1e3,Wd=f.preprocess(t=>t instanceof Date&&!Number.isNaN(t.getTime())?t.toISOString().slice(0,10):t,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),so=f.enum(["low","medium","high"]),Gd=f.object({owner:f.string().min(1).max(160).optional(),risk_level:so.optional(),reviewed_at:Wd.optional()}).default({}),Bd=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}),Kd=f.object({lesson_query:Bd,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:[]}),Vd=f.object({id:f.string().min(6).max(hv).regex(mv,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:Wd,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(Hd,`summary must be \u2264 ${Hd} chars (rendered as one line in skill_index)`),description:f.string().max(gv).optional(),applies_to:ri,membership:Kd,governance:Gd}),yv=Vd.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var zd,qd,Yd,Jd,Xd,Zd,_v,Qd,bv,wv,eu=b(()=>{"use strict";Q();oo();zd=f.enum(["maind","agent-skill"]),qd=f.enum(["ready","needs_attention","blocked"]),Yd=f.enum(["info","important","critical"]),Jd=f.enum(["pass","warn","fail"]),Xd=f.enum(["structure","governance","scope","membership","package","references"]),Zd=f.object({id:f.string().min(1),title:f.string().min(1),status:Jd,severity:Yd,category:Xd,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),_v=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({}),Qd=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(),bv=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:Qd,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),wv=f.object({format:zd,subject:f.string().min(1),status:qd,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(Zd),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var ao=b(()=>{"use strict"});var tu,kv,nu,ru,iu,mn,xv,su,ou,au,cu,lu,du,uu,pu,Sv,fu,mu,hu,ai,co,gu,yu,Ev,_u=b(()=>{"use strict";Q();et();ao();tu=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],kv=f.enum(tu),nu=["verdict","advisory"],ru=f.enum(nu),iu=["block","warn","note"],mn=f.enum(iu),xv=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:ni,scope:ti,grade:ru,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()}),su=["open","warn","info"],ou=f.enum(su),au=["introduced","pre_existing"],cu=f.enum(au),lu=["full","partial","none"],du=f.enum(lu),uu=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:ou,baseline:cu,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),pu=f.object({version:f.literal(1).default(1),actions:f.object({required:mn.default("block"),recommended:mn.default("warn"),info:mn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:mn})).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:mn,reason:f.string().min(1).max(200)})).max(32).optional()}),Sv=pu.parse({}),fu=["ran","not_applicable","unavailable","ungraded"],mu=f.enum(fu),hu=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),state:mu}),ai=1e3,co=f.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),gu=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()}),yu=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:du}),Ev=f.object({changed_symbols:f.array(gu).max(ai),risk_flags:f.array(f.string().max(64)).max(16),detector_findings:f.array(uu).max(64),detector_runs:f.array(hu).min(1).max(32),diff_stats:yu,commit_sha:co.optional(),base_sha:co.optional(),merge_base_sha:co.optional(),dirty:f.boolean().optional(),code_index_version:f.string().min(1).max(32).optional()})});var bu,wu,vu,ku,xu,lo,Tv,Rv,Su,Eu,Tu,Ru,Au,Av,Nv,Nu,Iu,Cu,Iv,Ou=b(()=>{"use strict";Q();bu=14,wu=14,vu=14,ku=1,xu=365,lo=f.number().int().min(ku).max(xu),Tv=["propose","direct"],Rv="propose",Su=["propose","direct"],Eu="propose",Tu=["propose","direct"],Ru="propose",Au=["off","propose","direct"],Av=["member","admin","owner"],Nv="member",Nu="off",Iu="en",Cu=f.object({version:f.literal(1).default(1),at_risk_days:lo.default(bu),stagnation_days:lo.default(wu),agent_date_mode:f.enum(Tv).default(Rv),health_manual_ttl_days:lo.default(vu),agent_event_mode:f.enum(Su).default(Eu),agent_update_mode:f.enum(Tu).default(Ru),agent_pull_mode:f.enum(Au).default(Nu),org_wide_authoring_min_role:f.enum(Av).default(Nv),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Iu)}),Iv=Cu.parse({})});var Du,Cv,Mu=b(()=>{"use strict";Q();Du=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Cv=Du.parse({})});var Pu,Lu,Ov,Dv,$u=b(()=>{"use strict";Q();Pu=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([])}),Lu=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:Pu.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()}),Ov=Lu.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()}),Dv=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var Fu=b(()=>{"use strict"});function ci(t){let e=[],n=null;return t.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=Pv.exec(r);if(!c)return;let l=c[3]??"";if(Mv.has(l.trim())){n=o;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&e.push({line:i+1,value:d})}),e}var Mv,Pv,ju=b(()=>{"use strict";Mv=new Set(["|",">","|-",">-","|+",">+"]),Pv=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;a(ci,"plainScalarViolations")});function or(t,e){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(t),[s,o]=n(e);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 Uu=b(()=>{"use strict";a(or,"compareSemver")});var li=b(()=>{"use strict";et();gd();et();et();wd();vd();kd();Ad();Od();Ud();et();oo();eu();_u();Ou();Mu();$u();Fu();ao();ju();Uu()});function Hu(t){return[`${t.kind} ${t.qualifiedName}`,t.signature??"",t.doc??"",t.filePath].filter(e=>e.length>0).join(`
|
|
4
|
+
`).slice(0,1e3)}var Wu=b(()=>{"use strict";a(Hu,"nodeEmbedText")});var uo,po=b(()=>{"use strict";uo=["function","method","class","interface","enum","type_alias"]});function Gu(t,e){let n=Math.min(t.length,e.length),r=0,i=0,s=0;for(let o=0;o<n;o++){let c=t[o],l=e[o];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}var Bu=b(()=>{"use strict";a(Gu,"cosineSimilarity")});import{execFileSync as Lv}from"node:child_process";import{createHash as $v}from"node:crypto";import{readFileSync as Fv}from"node:fs";import{posix as ge}from"node:path";function Ku(t){let e=$v("sha256"),n=[];try{n=Lv("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:t,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
5
|
+
`).filter(l=>jv.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:e.digest("hex")}}let r=new Map,i=a(l=>{if(r.has(l))return r.get(l);try{let d=Fv(ge.join(t,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=Vu(l,i,0),u=ge.dirname(l)==="."?"":ge.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=zu(i(l));if(!d||typeof d.name!="string")continue;let u=ge.dirname(l)==="."?"":ge.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())e.update(l).update("\0").update(r.get(l)).update("\0");return{config:{packages:c,tsconfigs:s},fingerprint:e.digest("hex")}}function Vu(t,e,n){let r=zu(e(t));if(!r)return{};let i=ge.dirname(t)==="."?"":ge.dirname(t),s={},o=r.extends;if(typeof o=="string"&&o.startsWith(".")&&n<4){let d=ge.normalize(ge.join(i,o.endsWith(".json")?o:o+".json"));s=Vu(d,e,n+1)}let c=r.compilerOptions??{},l={...s};return typeof c.outDir=="string"&&(l.outDir=ge.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=ge.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 zu(t){if(t===null)return null;let e="",n=!1;for(let r=0;r<t.length;r++){let i=t[r];if(n){e+=i,i==="\\"?e+=t[++r]??"":i==='"'&&(n=!1);continue}if(i==='"')n=!0,e+=i;else if(i==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
|
|
6
|
+
`;)r++;e+=`
|
|
7
|
+
`}else if(i==="/"&&t[r+1]==="*"){for(r+=2;r<t.length&&!(t[r]==="*"&&t[r+1]==="/");)r++;r++}else e+=i}try{let r=JSON.parse(Uv(e));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function Uv(t){let e="",n=!1;for(let r=0;r<t.length;r++){let i=t[r];if(n){e+=i,i==="\\"?e+=t[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let s=r+1;for(;s<t.length&&/\s/.test(t[s]);)s++;if(t[s]==="}"||t[s]==="]")continue}e+=i}return e}var jv,qu=b(()=>{"use strict";jv=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;a(Ku,"loadModuleConfig");a(Vu,"compilerFacts");a(zu,"parseJsonc");a(Uv,"dropTrailingCommas")});import{posix as ye}from"node:path";function ar(t,e){let n=ye.normalize(t).replace(/^\.\//,""),r=[],i=di.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 di)r.push(c+l)}if(!i&&!s){for(let c of di)r.push(n+c);for(let c of di)r.push(`${n}/index${c}`)}for(let c of r)if(e.has(c))return c;return null}function Ju(t,e){if(t==null)return null;if(typeof t=="string")return e==="."?t:null;if(Array.isArray(t)){for(let i of t){let s=Ju(i,e);if(s)return s}return null}if(typeof t!="object")return null;let n=t,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(e in n)return cr(n[e]);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(e.startsWith(o)&&e.endsWith(c)){let l=cr(n[i]);if(l)return l.replace("*",e.slice(o.length,e.length-c.length))}}return null}return e==="."?cr(t):null}function cr(t){if(typeof t=="string")return t;if(Array.isArray(t)){for(let e of t){let n=cr(e);if(n)return n}return null}if(t&&typeof t=="object"){let e=t;for(let n of Hv)if(n in e){let r=cr(e[n]);if(r)return r}}return null}function Wv(t,e){let n=ye.normalize(e).replace(/^\.\//,""),r=[n];if(t.outDir){let i=ye.normalize(t.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=ye.normalize(t.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(ye.join(s,n.slice(i.length+1)))}return r}var di,Hv,fo,Yu,hn,mo=b(()=>{"use strict";di=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],Hv=["import","default","node","require","types"],fo={kind:"unresolved"},Yu={kind:"external"};a(ar,"resolvePathCandidates");hn=class{static{a(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(e,n){this.files=n,this.packages=[...e.packages].sort((r,i)=>i.name.length-r.name.length),this.tsconfigs=e.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,i)=>i.dir.length-r.dir.length)}resolve(e,n){let r=`${ye.dirname(e)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(e,n),this.cache.set(r,i)),i}compute(e,n){if(n.startsWith(".")){let s=ar(ye.join(ye.dirname(e),n),this.files);return s?{kind:"file",path:s}:fo}if(n.startsWith("node:"))return Yu;let r=this.viaTsconfigPaths(e,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}:fo}return Yu}viaTsconfigPaths(e,n){let r=this.tsconfigs.find(s=>s.dir===""||e.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=ye.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(ye.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return fo}}return null}viaPackage(e,n){let r=[],i=Ju(e.exports,n);if(i)r.push(i);else if(e.exports===void 0)if(n==="."){for(let s of[e.module,e.main,e.types])s&&r.push(s);r.push("index")}else r.push(n);for(let s of r)for(let o of Wv(e,s)){let c=ar(ye.join(e.dir,o),this.files);if(c)return c}return null}};a(Ju,"exportTarget");a(cr,"conditionTarget");a(Wv,"toSource")});function tt(t){return`${t}#<module>`}function Te(t,e,n){return`${t}#${e}:${n}`}var gn=b(()=>{"use strict";a(tt,"moduleKey");a(Te,"symbolKey")});import{posix as Xu}from"node:path";function Qu(t){let e=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 t)if(n.add(c.filePath),s.add(c.nodeKey),Gv.has(c.kind)&&o(e,c.name,c.nodeKey),c.kind==="method"&&o(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Te(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:e,files:n,topLevel:r,methodsByName:i,keys:s}}function ep(t,e,n=new hn({packages:[],tsconfigs:[]},e.files)){let r=zv(),i=new ho(t,e,n);for(let s of t)s.language==="python"?qv(s.filePath,s.refs,s.imports,e,r.push):i.resolveFile(s,r.push);return r.edges}function Vv(t,e,n){return e.startsWith(".")?ar(Xu.join(Xu.dirname(t),e),n):null}function zv(){let t=new Set,e=[];return{edges:e,push(n,r,i){if(n===r)return;let s=`${n} ${r} ${i}`;t.has(s)||(t.add(s),e.push({srcKey:n,dstKey:r,kind:i}))}}}function qv(t,e,n,r,i){for(let s of e){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=Vv(t,s.specifier,r.files);o&&i(s.fromModuleKey,tt(o),"imports")}}function Yv(t){let e=t.indexOf("#"),n=t.slice(e+1,t.lastIndexOf(":"));return Te(t.slice(0,e),n.slice(0,n.lastIndexOf(".")),"class")}var Gv,Zu,Bv,Kv,ho,tp=b(()=>{"use strict";gn();mo();Gv=new Set(["function","method","class","interface","enum","type_alias"]),Zu=["function","class","variable","enum","interface","type_alias"],Bv=8,Kv=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(Qu,"buildResolutionIndex");a(ep,"resolveCrossFileEdges");a(Vv,"resolveImportTarget");a(zv,"edgeCollector");a(qv,"legacyFacts");a(Yv,"classKeyOfMethod");ho=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(e,n,r){this.index=n,this.modules=r;for(let i of e){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(e,n){for(let r of e.refs){let i=this.resolveRef(e.filePath,r);i&&n(r.fromKey,i,r.kind)}for(let r of e.imports){let i=this.modules.resolve(e.filePath,r.specifier);i.kind==="file"&&n(tt(e.filePath),tt(i.path),"imports")}}resolveRef(e,n){let r=n.receiver??null;if(r===null){let o=this.resolveLocal(e,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(e,n.receiverType,n.targetName);if(r!=="?"&&r!=="this.*"&&!r.startsWith("this.")){let o=r.endsWith(".*"),c=o?r.slice(0,-2):r;if(Kv.has(c)&&!this.bindings.get(e)?.has(c))return null;let l=this.bindings.get(e)?.get(c);if(l&&this.modules.resolve(e,l.specifier).kind!=="file")return null;if(!o){let d=this.resolveLocal(e,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(e),s=(this.index.methodsByName.get(n.targetName)??[]).filter(o=>{let c=Yv(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(e,n,r){if(n==="#")return null;let i=n.indexOf("."),s;if(i<0)s=this.resolveLocal(e,n,0);else{let c=this.resolveLocal(e,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(e,n){let r=e.indexOf("#"),i=Te(e.slice(0,r),`${e.slice(r+1,e.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let s of this.supertypes(e)){if(!s.endsWith(":class"))continue;let o=s.indexOf("#"),c=Te(s.slice(0,o),`${s.slice(o+1,s.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(e){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(e)??new Set}nameableKeys(e){let n=this.nameableMemo.get(e);if(n)return n;n=new Set;for(let r of this.bindings.get(e)?.keys()??[]){let i=this.resolveLocal(e,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(e)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(e,n),n}supertypes(e){let n=this.supertypesMemo.get(e);if(n)return n;n=new Set,this.supertypesMemo.set(e,n);for(let{file:r,ref:i}of this.heritage.get(e)??[]){let s=this.resolveRef(r,i);if(s){n.add(s);for(let o of this.supertypes(s))n.add(o)}}return n}ownMethod(e,n){let r=e.indexOf("#"),i=e.lastIndexOf(":");if(r<0||i<r)return null;let s=e.slice(0,r),o=e.slice(r+1,i),c=e.slice(i+1),l=c==="method"?o.slice(0,o.lastIndexOf(".")):c==="class"?o:null;if(!l)return null;let d=Te(s,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(e,n,r){let i=this.bindings.get(e)?.get(n);return i?this.resolveBinding(e,i,r):this.topLevel(e,n)}resolveBinding(e,n,r){let i=this.modules.resolve(e,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(e,n,r){let i=`${e}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>Bv)return null;this.memo.set(i,null);let s=this.computeExport(e,n,r);return this.memo.set(i,s),s}computeExport(e,n,r){let i=this.exports.get(e)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(e,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(e,l.localName,r+1)}let s=this.topLevel(e,n);if(s)return s;let o=this.bindings.get(e)?.get(n);if(o)return this.resolveBinding(e,o,r);let c=new Map;for(let l of i){if(l.exportedName!=="*"||!l.specifier)continue;let d=this.modules.resolve(e,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(e,n){let r=this.index.topLevel.get(e)?.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=Zu.indexOf(s.slice(s.lastIndexOf(":")+1));return o<0?Zu.length:o},"rank");return{kind:"symbol",key:[...r].sort((s,o)=>i(s)-i(o))[0]}}}});function ui(t){let e=t.toLowerCase();return e.endsWith(".tsx")?"tsx":e.endsWith(".ts")||e.endsWith(".mts")||e.endsWith(".cts")?"typescript":e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs")||e.endsWith(".cjs")?"javascript":e.endsWith(".py")||e.endsWith(".pyi")?"python":null}function go(t){return t.toLowerCase().endsWith(".d.ts")}var pi=b(()=>{"use strict";a(ui,"languageForPath");a(go,"isSkippablePath")});import{appendFileSync as Jv,existsSync as np,mkdirSync as Xv,readFileSync as Zv}from"node:fs";import{join as Qv}from"node:path";function lr(t,e={}){try{if(!np(t)){if(!e.create)return"skipped";Xv(t,{recursive:!0})}let n=Qv(t,".gitignore"),r=np(n)?Zv(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=fi.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let o=r===null?[...ek,...s]:s,c=r&&!r.endsWith(`
|
|
5
8
|
`)?`
|
|
6
|
-
`:"";return
|
|
9
|
+
`:"";return Jv(n,c+o.join(`
|
|
7
10
|
`)+`
|
|
8
|
-
`),r===null?"created":"appended"}catch{return"skipped"}}var
|
|
9
|
-
`));let n=[];return
|
|
10
|
-
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let
|
|
11
|
-
`)){if(l.length<4)continue;let
|
|
12
|
-
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=
|
|
13
|
-
`),"norm"),l=c(s),
|
|
14
|
-
`).map(p=>p.trim()).every(p=>p.length===0||
|
|
15
|
-
`)){if(
|
|
16
|
-
`)){if(l.startsWith("diff --git ")){c(),s=!1,
|
|
17
|
-
`),_=Wu(y[0]??"");if(!_)continue;let w=y.slice(1).filter(k=>k.trim().length>0).length;m.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:w})}u={sinceInput:n.since,sinceResolved:d,commits:m.slice(0,di),truncated:m.length>di}}return{history:l,regression:u,ownershipWindowCommits:s,pathsTruncated:a.length>po}}var Sv,xv,Bu,po,di,Hu,fo=b(()=>{"use strict";te();Sv="",xv="\0",Bu=200,po=50,di=100,Hu="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";o(Ev,"clamp");o(Gu,"splitRecords");o(Wu,"parseHistoryRecord");o(Av,"aggregateOwnership");o(Ku,"readFileHistory")});import{execFileSync as Tv}from"node:child_process";import{readdirSync as Rv,statSync as Vu}from"node:fs";import{isAbsolute as Iv,join as mo,relative as Cv,resolve as Nv}from"node:path";function Dv(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Pv(e,t){try{let n=Tv("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 Mv(e){let t;try{t=Rv(e)}catch{return null}for(let n of t.filter(Dv))try{let r=Vu(mo(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function $v(e){try{return Vu(e).isDirectory()}catch{return!1}}function Lv(e,t){let n=Cv(e,t);return!n||n.startsWith("..")?t:n}function ho(e){let t=Ov.filter(c=>$v(mo(e,c))),n=Pv(e,"core.hooksPath"),r=n?Iv(n)?n:Nv(e,n):mo(e,".git","hooks"),i=Lv(e,r),s=Mv(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function go(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 Ov,yo=b(()=>{"use strict";Ov=[".githooks",".husky"];o(Dv,"isRealHook");o(Pv,"gitConfig");o(Mv,"hasExecutableHook");o($v,"isDir");o(Lv,"displayPath");o(ho,"resolveHookState");o(go,"describeHookState")});import{posix as zu}from"node:path";function cn(e){let t=Fv.exec(e);return t?t[1]:null}function Le(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function xt(e,t){let n=T(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=o(s=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let a=zu.basename(s),c=cn(a);if(c===null)continue;let l=zu.dirname(s),u=i.get(l)??[];u.push({path:s,name:a,version:c}),i.set(l,u)}return[...i.entries()].map(([s,a])=>({dir:s,files:a.sort((c,l)=>Le(c.version,l.version))})).sort((s,a)=>s.dir.localeCompare(a.dir))}function qu(e){let t=T(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(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var Fv,nr=b(()=>{"use strict";te();Fv=/^(\d+)_.+\.sql$/;o(cn,"parseMigrationVersion");o(Le,"compareVersions");o(xt,"discoverSupabaseProjects");o(qu,"resolveDefaultBranch")});import{execFileSync as jv}from"node:child_process";import{existsSync as ee,readFileSync as Qe,readdirSync as ui,statSync as bo}from"node:fs";import{posix as M}from"node:path";function Wv(e,t){let n=(()=>{let i=T(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=M.dirname(e);for(let i=0;i<8&&r&&r!==M.dirname(r);i++){if(ee(M.join(r,".git"))){let s=(()=>{let c=T(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&vo(n,s))){let c=Bv(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=M.dirname(r)}return null}function Bv(e,t){let n=[];for(let r of Hv){let i;try{i=ui(M.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let a=`${r}/${s}`,c=M.join(e,a),l=M.join(t,a);try{let u=bo(c),d=bo(l);if(!d.isFile())continue;if(u.size!==d.size){n.push(a);continue}if(u.size>Gv)continue;Qe(c).equals(Qe(l))||n.push(a)}catch{continue}}}return n.sort()}function tp(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 ${ko}.`})}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 ${M.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,u=l.slice(0,3).join(", "),d=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 ${u}${d} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=o(d=>d.impact==="runtime"?`${d.packageDir} (runtime)`:d.packageDir,"label"),u=c.every(d=>d.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(d=>d.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(d=>d.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${u}`,hint:`Rebuild: pnpm --filter ./${c[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let a=Kv(e.hooks);return a&&t.push(a),Vv(t)}function Kv(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:go(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 Vv(e){return[...e].sort((t,n)=>Yu[t.status]-Yu[n.status]||t.id.localeCompare(n.id))}function np(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Fe(e){let t=e?.trim();return t||null}function zv(e){let t=Fe(T(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(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function qv(e){let t=Fe(T(e,["rev-parse","--git-dir"]));if(!t)return null;let n=M.isAbsolute(t)?t:M.join(e,t);return ee(M.join(n,"rebase-merge"))||ee(M.join(n,"rebase-apply"))?"rebase":ee(M.join(n,"MERGE_HEAD"))?"merge":ee(M.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Yv(e){let t=[],n=null,r=o(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
18
|
-
`))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(),
|
|
19
|
-
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function
|
|
20
|
-
`).filter(
|
|
21
|
-
`).map(
|
|
22
|
-
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let
|
|
23
|
-
`).filter(Boolean):[]}function
|
|
24
|
-
`,
|
|
25
|
-
`:i==="r"?"\r":i==="t"?" ":i)}function
|
|
26
|
-
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let
|
|
27
|
-
Pre-existing at ${
|
|
28
|
-
`);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&&
|
|
29
|
-
`).map(
|
|
30
|
-
`;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)
|
|
31
|
-
`).filter(Boolean)){let[p,...h]=
|
|
32
|
-
`).map(
|
|
33
|
-
`)}function
|
|
34
|
-
`).filter(Boolean)}function
|
|
35
|
-
`).filter(Boolean)),l=
|
|
36
|
-
`).filter(i=>i.length>0&&n.some(s=>rS(i,s)))}function rS(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 iS(e){let t=T(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>T(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function ra(e,t){try{let n=Xk(e,"utf8");return n.length>t?null:n}catch{return null}}var tf,Zk,Qk,Zp,tS,ki=b(()=>{"use strict";te();o(ia,"isThemeClassDriftGraded");tf=["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"],Zk=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Qk=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+tf.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(sa,"extractTokens");o(oa,"deriveNamespaces");o(nf,"stripCommentLines");o(aa,"evaluateThemeClasses");o(Xp,"findingKey");o(eS,"gradeAgainstBaseline");o(rf,"deriveThemeClassVerdict");Zp=["*.ts","*.tsx","*.js","*.jsx"],tS=15e5;o(ca,"isScannableSource");o(Qp,"listTracked");o(It,"checkThemeClassDrift");o(nS,"baselineFindings");o(ef,"listTrackedAt");o(rS,"matchesSourcePattern");o(iS,"resolveBaseRef");o(ra,"safeRead")});function la(e){return Do[e].version}function Ue(e,t,n,r){return{detector_id:e,detector_version:la(e),state:t,finding_count:n,...r?{reason:r}:{}}}function j(e,t,n){return{summary:Ue(e,t,0,n),findings:[]}}function df(e){return e==="open"||e==="warn"||e==="info"}function sS(e){let t="det_number_collisions";if(!e.ok)return j(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return j(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return j(t,"not_applicable","no numbered namespaces");if(!Ao(n))return j(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!df(s.status))continue;let{level:a,baseline:c}=un(s.status);i.push({detector_id:t,rule_id:Po,level:a,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:Ue(t,"ran",i.length),findings:i}}function oS(e){let t="det_spec_drift";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return j(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return j(t,"not_applicable",n.reason??"no opinion");if(!Go(n))return j(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!df(i.status))continue;let{level:s,baseline:a}=un(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Lo(i.dimension),level:s,baseline:a,evidence:[i.id],title:i.title})}return{summary:Ue(t,"ran",r.length),findings:r}}function aS(e){let t="det_theme_class_drift";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable","no theme tokens");if(!ia(n))return j(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=un(i.status);r.push({detector_id:t,rule_id:Mo,level:s,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Ue(t,"ran",r.length),findings:r}}function cS(e){let t="det_table_acl_lint";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable","no supabase migrations");if(!ta(n))return j(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=un(i.status);r.push({detector_id:t,rule_id:$o,level:s,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Ue(t,"ran",r.length),findings:r}}function lS(e){let t="det_changelog_duplicates";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return j(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:Ue(t,"ran",r.length),findings:r}}function dS(e){let t="det_workflow_yaml";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return j(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:Ue(t,"ran",r.length),findings:r}}function uS(e){let t="det_release_claims";if(!e.ok)return j(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?j(t,"ungraded",n.reason??"registry unreachable"):j(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:Ue(t,"ran",r.length),findings:r}}function pS(e){let t="det_agent_doc_prose";if(!e.ok)return j(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?j(t,"ungraded",n.reason??"no base ref to grade against"):j(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:Ue(t,"ran",r.length),findings:r}}function da(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Si[e.level]-Si[t.level]||of[e.baseline]-of[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function af(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function fS(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=or(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:la(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,a=n.get(s);a?(a.evidence.push(...i.evidence),a.count+=1,Si[i.level]<Si[a.level]&&(a.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:la(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:or(i.evidence),count:i.count});return r.sort(da)}function mS(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 Ee(e){let t={det_number_collisions:sS(e.number),det_spec_drift:oS(e.spec),det_theme_class_drift:aS(e.theme),det_table_acl_lint:cS(e.acl),det_changelog_duplicates:lS(e.changelog),det_workflow_yaml:dS(e.workflow),det_release_claims:uS(e.release),det_agent_doc_prose:pS(e.agentDoc)},n=sf.map(l=>t[l].summary),r=sf.flatMap(l=>t[l].findings),i=fS(r),s=[...i].sort((l,u)=>af(l)-af(u)||da(l,u)).slice(0,cf).sort(da),a=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:or(l.evidence),title:l.title}));return{findings:s,coverage:mS(n,a),engines:n,local:c,truncated:a}}function Ct(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 pa(e){return e instanceof Error?e.message:String(e)}async function et(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:pa(t)}}}async function fa(e,t={}){let n={...lf,...t.engines};try{if(!uf(e))return Ee(Ct("not a git work tree"));let r=await pf(e,n,t.baseRef),i=await ua(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return Ee({...r,number:i})}catch(r){return Ee(Ct(`detector adapter failed: ${pa(r)}`))}}async function ma(e,t={}){let n={...lf,...t.engines};try{if(!uf(e)){let a=Ee(Ct("not a git work tree"));return{commit:a,local:a}}let r=await pf(e,n,t.baseRef),i=await ua(e,n,t.baseRef,"commit"),s=await ua(e,n,t.baseRef,"local");return{commit:Ee({...r,number:i}),local:Ee({...r,number:s})}}catch(r){let i=Ee(Ct(`detector adapter failed: ${pa(r)}`));return{commit:i,local:i}}}function uf(e){return T(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function pf(e,t,n){let r=n?{baseRef:n}:{};return{spec:await et(()=>t.spec(e,r)),theme:await et(()=>t.theme(e,r)),acl:await et(()=>t.acl(e,r)),changelog:await et(()=>t.changelog(e,r)),workflow:await et(()=>t.workflow(e,r)),release:await et(()=>t.release(e,r)),agentDoc:await et(()=>t.agentDoc(e,r))}}function ua(e,t,n,r,i){let s=r==="local";return et(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var cf,lf,sf,Si,of,ha=b(()=>{"use strict";te();Fo();sr();cr();Vo();Yo();Xo();bi();vi();ki();cf=64,lf={number:o((e,t)=>Et(e,t),"number"),spec:o((e,t)=>Tt(e,t),"spec"),theme:o((e,t)=>It(e,t),"theme"),acl:o((e,t)=>Rt(e,t),"acl"),changelog:o((e,t)=>Wo(e,t),"changelog"),workflow:o((e,t)=>Jo(e,t),"workflow"),release:o((e,t)=>Ko(e,t),"release"),agentDoc:o((e,t)=>qo(e,t),"agentDoc")},sf=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint","det_changelog_duplicates","det_workflow_yaml","det_release_claims","det_agent_doc_prose"];o(la,"versionOf");o(Ue,"summary");o(j,"noFindings");o(df,"isFindingStatus");o(sS,"adaptNumber");o(oS,"adaptSpec");o(aS,"adaptTheme");o(cS,"adaptAcl");o(lS,"adaptChangelog");o(dS,"adaptWorkflow");o(uS,"adaptRelease");o(pS,"adaptAgentDoc");Si={open:0,warn:1,info:2},of={introduced:0,pre_existing:1};o(da,"compareWire");o(af,"capPriority");o(fS,"buildWire");o(mS,"deriveCoverage");o(Ee,"adaptDetectorReports");o(Ct,"unavailableDetectorReports");o(pa,"errorText");o(et,"attempt");o(fa,"runRepoHealthDetectors");o(ma,"runRepoHealthDetectorScopes");o(uf,"insideWorkTree");o(pf,"runSharedEngines");o(ua,"runNumberEngine")});var ff,ga=b(()=>{"use strict";ff=[{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:/^\.github\/workflows\/[^/]+\.ya?ml$|^\.gitlab-ci\.yml$/},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function mf(e){let t=new Set;for(let[n,r]of e.paths)for(let i of ff){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=hS(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function hS(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
37
|
-
`):
|
|
11
|
+
`),r===null?"created":"appended"}catch{return"skipped"}}var fi,yo,ek,mi=b(()=>{"use strict";fi=["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"],yo=["# 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).'],ek=yo;a(lr,"ensureMaindLocalIgnore")});import{execFileSync as tk}from"node:child_process";import{createHash as nk}from"node:crypto";import{readFileSync as rk,readdirSync as ik,statSync as sk}from"node:fs";import{posix as bo,sep as rp}from"node:path";function R(t,e){try{return tk("git",[...ok,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function ak(t){return rp==="/"?t:t.split(rp).join("/")}function hi(t){let e=[];for(let n of t){let r=ak(n).trim();if(!r||go(r))continue;let i=ui(r);i&&e.push({path:r,language:i})}return e}function sp(t){return hi(t)}function op(t){let e=nt(t,["ls-files","--cached","--others","--exclude-standard"]);if(e!==null)return hi(e.split(`
|
|
12
|
+
`));let n=[];return ap(t,"",n),hi(n)}function ap(t,e,n){let r;try{r=ik(bo.join(t,e),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&ip.has(i.name)||ip.has(i.name))continue;let s=e?`${e}/${i.name}`:i.name;i.isDirectory()?ap(t,s,n):i.isFile()&&n.push(s)}}function wo(t,e){return vo(t,e)??e}function vo(t,e){let n=R(t,["merge-base",e,"HEAD"])?.trim();return n&&n.length>0?n:null}function gi(t,e={}){if(dr(t)===null)return null;let n=e.includeUncommitted!==!1,r=e.since?wo(t,e.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!e.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=nt(t,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=_o((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=nt(t,["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=_o(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 _o(t){return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function ko(t,e={}){let n=gi(t,e);return n===null?null:hi(n.keys())}function cp(t,e){try{let n=sk(bo.join(t,e));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function yi(t){return nk("sha256").update(t).digest("hex")}function dr(t){return nt(t,["rev-parse","HEAD"])?.trim()??null}function _i(t,e){return nt(t,["rev-parse","--verify",`${e}^{commit}`])?.trim()??null}function xo(t){let e=nt(t,["status","--porcelain","-uall"]);if(e===null)return!1;let n=e.split(`
|
|
15
|
+
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=ck(t);return n.some(i=>r===null||!lk(t,i,r))}function ck(t){let e=nt(t,["rev-parse","--show-prefix"]);return e===null?null:`${e.trim()}.maind/.gitignore`}function lk(t,e,n){let r=e[0],i=e[1];if(_o(e.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=nt(t,["show",`HEAD:${n}`]);if(p===null)return!1;s=p}else return!1;let o;try{o=rk(bo.join(t,".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([...fi,...yo]);return d.slice(l.length).split(`
|
|
17
|
+
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var ip,ok,nt,te=b(()=>{"use strict";pi();mi();ip=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),ok=["-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");nt=R;a(ak,"toPosix");a(hi,"classify");a(sp,"classifyPaths");a(op,"discoverSourceFiles");a(ap,"walk");a(wo,"resolveDiffBase");a(vo,"resolveMergeBase");a(gi,"enumerateChangedPaths");a(_o,"unquote");a(ko,"changedSourceFiles");a(cp,"statFile");a(yi,"hashContent");a(dr,"headCommit");a(_i,"resolveCommitSha");a(xo,"isWorktreeDirty");a(ck,"toolIgnoreRepoPath");a(lk,"isToolOnlyIgnoreChange")});function dp(t,e={}){if(R(t,["rev-parse","HEAD"])===null)return null;let n=e.includeUncommitted!==!1,r=e.since?wo(t,e.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!e.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=R(t,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")>dk?c="none":mk(s,o,()=>{c="partial"}),n){let l=R(t,["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 mk(t,e,n){let r=null,i=0,s=!1,o=!1,c=a(()=>{r&&e.set(r.path,r),r=null,i=0},"commit");for(let l of t.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=fk.exec(l);if(d){if(i++,i>uk){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<pk&&r.addedLines.push(l.slice(1))}c()}var dk,uk,pk,lp,fk,up=b(()=>{"use strict";te();dk=16*1024*1024,uk=500,pk=4e3,lp=256*1024,fk=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;a(dp,"changedHunks");a(mk,"parseUnifiedDiff")});function yk(t,e,n){return t===void 0||!Number.isFinite(t)||t<=0?e:Math.min(Math.floor(t),n)}function fp(t){return t.split(hk).filter(e=>e.trim().length>0)}function mp(t){let[e,n,r,i,s]=t.replace(/\n+$/,"").split(gk);return!e||!i?null:{sha:e,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function _k(t){let e=new Map;for(let n of t){let r=n.authorEmail.toLowerCase()||n.authorName,i=e.get(r);i?i.commits+=1:e.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...e.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function gp(t,e,n={}){let r=yk(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,hp),o=e.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=o.slice(0,So),l=[];for(let u of c){let p=R(t,["log","-n",String(s),pp,"--",u]),h=p===null?[]:fp(p).map(mp).filter(m=>m!==null);l.push({path:u,lastCommits:h.slice(0,r),ownership:i?{topAuthors:_k(h),commitsInWindow:h.length}:null})}let d=null;if(n.since){let u=_i(t,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],h=R(t,["log",...p,"-n",String(bi+1),pp,"--name-only","--",...c]),m=[];if(h!==null)for(let g of fp(h)){let y=g.split(`
|
|
20
|
+
`),_=mp(y[0]??"");if(!_)continue;let w=y.slice(1).filter(k=>k.trim().length>0).length;m.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,bi),truncated:m.length>bi}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:o.length>So}}var hk,gk,hp,So,bi,pp,Eo=b(()=>{"use strict";te();hk="",gk="\0",hp=200,So=50,bi=100,pp="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";a(yk,"clamp");a(fp,"splitRecords");a(mp,"parseHistoryRecord");a(_k,"aggregateOwnership");a(gp,"readFileHistory")});import{execFileSync as bk}from"node:child_process";import{readdirSync as wk,statSync as yp}from"node:fs";import{isAbsolute as vk,join as To,relative as kk,resolve as xk}from"node:path";function Ek(t){return!t.endsWith(".sample")&&!t.startsWith(".")}function Tk(t,e){try{let n=bk("git",["-C",t,"config","--get",e],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}function Rk(t){let e;try{e=wk(t)}catch{return null}for(let n of e.filter(Ek))try{let r=yp(To(t,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Ak(t){try{return yp(t).isDirectory()}catch{return!1}}function Nk(t,e){let n=kk(t,e);return!n||n.startsWith("..")?e:n}function Ro(t){let e=Sk.filter(c=>Ak(To(t,c))),n=Tk(t,"core.hooksPath"),r=n?vk(n)?n:xk(t,n):To(t,".git","hooks"),i=Nk(t,r),s=Rk(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:e,hooksPath:n,effectiveDir:i};let o=n?s===null?"path_missing":"path_empty":e.length>0?"path_unset":"no_hooks";return{verdict:e.length>0?"present_unwired":"absent",reason:o,hookDirs:e,hooksPath:n,effectiveDir:i}}function Ao(t){switch(t.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${t.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${t.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${t.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${t.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}var Sk,No=b(()=>{"use strict";Sk=[".githooks",".husky"];a(Ek,"isRealHook");a(Tk,"gitConfig");a(Rk,"hasExecutableHook");a(Ak,"isDir");a(Nk,"displayPath");a(Ro,"resolveHookState");a(Ao,"describeHookState")});import{posix as _p}from"node:path";function yn(t){let e=Ik.exec(t);return e?e[1]:null}function Ue(t,e){return t.length!==e.length?t.length-e.length:t<e?-1:t>e?1:0}function It(t,e){let n=R(t,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=a(s=>!e||e.length===0?!0:e.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=_p.basename(s),c=yn(o);if(c===null)continue;let l=_p.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)=>Ue(c.version,l.version))})).sort((s,o)=>s.dir.localeCompare(o.dir))}function bp(t){let e=R(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(e){let n=/refs\/remotes\/origin\/(.+)$/.exec(e);if(n)return n[1]}for(let n of["main","master"])if(R(t,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var Ik,ur=b(()=>{"use strict";te();Ik=/^(\d+)_.+\.sql$/;a(yn,"parseMigrationVersion");a(Ue,"compareVersions");a(It,"discoverSupabaseProjects");a(bp,"resolveDefaultBranch")});import{execFileSync as Ck}from"node:child_process";import{existsSync as ee,readFileSync as rt,readdirSync as wi,statSync as Co}from"node:fs";import{posix as L}from"node:path";function Pk(t,e){let n=(()=>{let i=R(e,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=L.dirname(t);for(let i=0;i<8&&r&&r!==L.dirname(r);i++){if(ee(L.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&&Do(n,s))){let c=Lk(t,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=L.dirname(r)}return null}function Lk(t,e){let n=[];for(let r of Dk){let i;try{i=wi(L.join(t,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let o=`${r}/${s}`,c=L.join(t,o),l=L.join(e,o);try{let d=Co(c),u=Co(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(o);continue}if(d.size>Mk)continue;rt(c).equals(rt(l))||n.push(o)}catch{continue}}}return n.sort()}function Tp(t){let e=[];if(!t.isRepo)return e;let n=t.branch!=null&&t.defaultBranch!=null&&t.branch!==t.defaultBranch&&!t.detachedHead;if(t.detachedHead&&e.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(t.upstream==null)e.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${t.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${t.branch}`});else{let c=t.upstream.split("/").slice(1).join("/");c&&c!==t.branch&&e.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${t.branch}' tracks '${t.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${t.branch} (then push -u)`}),t.remoteTrackingExists===!1&&e.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${t.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${t.branch}`})}let r=t.behind??0,i=t.ahead??0;r>0&&e.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${t.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${t.defaultBranch}`});let s=t.isSharedMainTree&&t.otherWorktrees>0&&!n&&!t.detachedHead&&(t.ahead??0)>0;if(s){let c=t.ahead??0;e.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 '${t.defaultBranch}' checkout and not on ${t.upstream??`origin/${t.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 ${t.upstream??`origin/${t.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!s&&t.upstream!=null&&t.headMatchesUpstream===!1&&e.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${t.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),t.unmergedMigrations.length>0){let c=t.unmergedMigrations.length;e.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${t.branch}' are not on origin/${t.defaultBranch} yet \u2014 a cloud DB push run from ${t.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${t.defaultBranch} first (promote), then run 'supabase db push --linked' from ${t.defaultBranch}.`})}if(t.isSharedMainTree&&t.otherWorktrees>0&&t.uncommitted>0&&!n&&e.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 '${t.defaultBranch}' checkout while ${t.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>)."}),t.inProgressOp&&e.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${t.inProgressOp} in progress`,detail:`A ${t.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${t.inProgressOp} --continue | --abort`}),t.worktreeParity&&t.worktreeParity.missing.length>0){let c=t.worktreeParity.missing;e.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 ${t.worktreeParity.mainWorktreePath}, or declare them in ${Mo}.`})}if(t.worktreeParity&&t.worktreeParity.missingDeps.length>0){let c=t.worktreeParity.missingDeps;e.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 ${L.dirname(l.dir)})`).join(" | ")})}if(t.toolCopyDrift&&t.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=t.toolCopyDrift,d=l.slice(0,3).join(", "),u=l.length>3?` (+${l.length-3} more)`:"";e.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(t.stalePackageBuilds.length>0){let c=t.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.';e.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.`})}t.release?.allRed&&e.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${t.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=$k(t.hooks);return o&&e.push(o),Fk(e)}function $k(t){return!t||t.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:Ao(t),hint:t.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${t.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${t.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}function Fk(t){return[...t].sort((e,n)=>wp[e.status]-wp[n.status]||e.id.localeCompare(n.id))}function Rp(t){return!t.some(e=>e.status==="open"||e.status==="warn")}function He(t){let e=t?.trim();return e||null}function jk(t){let e=He(R(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(e){let n=/refs\/remotes\/origin\/(.+)$/.exec(e);if(n)return n[1]}for(let n of["main","master"])if(R(t,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Uk(t){let e=He(R(t,["rev-parse","--git-dir"]));if(!e)return null;let n=L.isAbsolute(e)?e:L.join(t,e);return ee(L.join(n,"rebase-merge"))||ee(L.join(n,"rebase-apply"))?"rebase":ee(L.join(n,"MERGE_HEAD"))?"merge":ee(L.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Hk(t){let e=[],n=null,r=a(()=>{n?.path&&e.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of t.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(),e}function Wk(t){let e=L.join(t,Mo);if(!ee(e))return[];try{return rt(e,"utf8").split(`
|
|
22
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function Gk(t){try{return It(t).map(e=>L.join(L.dirname(e.dir),"config.toml"))}catch{return[]}}function Bk(t){let e=R(t,["ls-files","-z","--",...Ok]);if(e===null)return[];let n=new Map;for(let r of e.split("\0").filter(Boolean)){let i=Ep[L.basename(r)];if(i===void 0)continue;let s=L.dirname(r);if(!Kk(t,s))continue;let o=s==="."?"node_modules":L.join(s,"node_modules");n.has(o)||n.set(o,{dir:o,install:i})}return[...n.values()]}function Kk(t,e){return e==="."?!0:Oo(t,e)}function Oo(t,e){if(ee(L.join(t,e,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(rt(L.join(t,e,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Ap(t,e={}){if(He(R(t,["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=He(R(t,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,o=jk(t),c=He(R(t,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let j=He(R(t,["rev-parse","HEAD"])),H=He(R(t,["rev-parse","@{u}"]));l=j!=null&&H!=null?j===H:null,d=R(t,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(o){let j=He(R(t,["rev-list","--left-right","--count",`origin/${o}...HEAD`]));if(j){let[H,$]=j.split(/\s+/).map(B=>Number.parseInt(B,10));Number.isFinite(H)&&(p=H),Number.isFinite($)&&(u=$)}}let m=(R(t,["status","--porcelain"])??"").split(`
|
|
23
|
+
`).filter(j=>j.trim().length>0).length,g=Uk(t),y=He(R(t,["rev-parse","--show-toplevel"]))??t,_=Hk(R(t,["worktree","list","--porcelain"])??""),w=_[0]?.path??null,k=w!=null&&Do(w,y),x=Math.max(0,_.length-1),S=null;if(w&&!Do(w,y)){let j=a($=>ee(L.join(w,$))&&!ee(L.join(y,$)),"here"),H=[...Sp,...Gk(y),...Wk(y),...e.probePaths??[]];S={mainWorktreePath:w,currentWorktreePath:y,missing:[...new Set(H.filter(j))],missingDeps:Bk(y).filter($=>j($.dir))}}let A=Pk(y,t),D=e.includeRelease===!1?null:Zk(t,s),F=[];return o&&(F=(R(t,["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:x,worktreeParity:S,toolCopyDrift:A,stalePackageBuilds:Np(y),release:D,unmergedMigrations:F,hooks:Ro(t)}}function Do(t,e){let n=a(r=>r.replace(/\/+$/,""),"norm");return n(t)===n(e)}function qk(t){let e=new Set;Oo(t,".")&&e.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<kp;){let i=n.pop();if(i===void 0)break;if(i.depth>=zk)continue;let s;try{s=wi(L.join(t,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:L.join(i.rel,o.name);if(r+=1,r>=kp)break;Oo(t,c)&&e.add(c),n.push({rel:c,depth:i.depth+1})}}return[...e].sort()}function Yk(t){let e=[];try{let n=L.join(t,"pnpm-workspace.yaml");if(ee(n)){let r=!1;for(let i of rt(n,"utf8").split(`
|
|
25
|
+
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let o=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);o?e.push(o[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=L.join(t,"package.json");if(ee(r)){let i=JSON.parse(rt(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&e.push(...s.filter(o=>typeof o=="string"))}}}catch{return[]}return e}function Jk(t){let e=[];for(let n of qk(t)){let r=n==="."?t:L.join(t,n),i=a(s=>n==="."?s:L.join(n,s),"prefix");for(let s of Yk(r)){if(e.length>=Io)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let o=s.slice(0,-2),c=L.join(r,o);if(!ee(c))continue;for(let l of wi(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&e.push(i(L.join(o,l.name))),e.length>=Io)break}else s.includes("*")||e.push(i(s))}catch{}}}return e.slice(0,Io)}function xp(t){let e=null,n=0,r=[t];for(;r.length>0&&n<vp;){let i=r.pop();if(i===void 0)break;let s;try{s=wi(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let c=L.join(i,o.name);if(o.isDirectory())r.push(c);else if(o.isFile()){n+=1;try{let l=Co(c).mtimeMs;(e===null||l>e)&&(e=l)}catch{}if(n>=vp)break}}}return e}function Xk(t,e){let n=new Set;for(let r of e)try{let i=L.join(t,r,"package.json");if(!ee(i))continue;let s=JSON.parse(rt(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 Np(t){let e=[],n=Jk(t),r=Xk(t,n);for(let i of n)try{let s=L.join(t,i,"package.json");if(!ee(s))continue;let o=JSON.parse(rt(s,"utf8"));if(typeof o.name!="string"||!r.has(o.name))continue;let c=a(w=>{if(typeof w!="string")return null;let k=w.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=L.join(t,i,"src"),m=L.join(t,i,u);if(!ee(h)||!ee(m))continue;let g=xp(h),y=xp(m);if(g===null||y===null)continue;let _=g-y;_>Vk&&e.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return e.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function Zk(t,e){if(!e)return null;let n=Qk(t,["pr","checks",e,"--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 Qk(t,e){try{return Ck("gh",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function pr(t,e={}){let n=await Ap(t,e);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Tp(n),i=Rp(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var Sp,Mo,Ep,Ok,Dk,Mk,wp,Vk,Io,vp,zk,kp,Po=b(()=>{"use strict";No();te();ur();Sp=["supabase/config.toml","supabase/.temp",".env"],Mo=".maind/worktree-requirements",Ep={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},Ok=Object.keys(Ep).flatMap(t=>[t,"*/"+t]),Dk=["scripts"],Mk=512*1024;a(Pk,"gatherToolCopyDrift");a(Lk,"compareToolDirs");a(Tp,"computeDivergence");a($k,"computeHookFinding");wp={open:0,warn:1,info:2,passed:3};a(Fk,"sortFindings");a(Rp,"isHealthy");a(He,"trimOrNull");a(jk,"resolveDefaultBranch");a(Uk,"detectInProgressOp");a(Hk,"parseWorktrees");a(Wk,"readWorktreeRequirements");a(Gk,"discoverSupabaseConfigProbes");a(Bk,"discoverDependencyDirs");a(Kk,"isWorkspaceRoot");a(Oo,"hasWorkspaceMarkers");a(Ap,"gatherRepoHealthFacts");a(Do,"samePath");Vk=2e3,Io=64,vp=4e3,zk=3,kp=400;a(qk,"findWorkspaceRoots");a(Yk,"workspacePatternsAt");a(Jk,"listWorkspacePackageDirs");a(xp,"newestMtimeUnder");a(Xk,"consumedWorkspaceNames");a(Np,"gatherStalePackageBuilds");a(Zk,"gatherReleaseFact");a(Qk,"runGh");a(pr,"checkDivergence")});import{existsSync as Lo,readdirSync as Ip}from"node:fs";import{posix as Re}from"node:path";function Fo(t){return t.isRepo&&t.baseRef!==null&&!t.skipped.includes($o)}function Op(t,e={}){let n=e.minFiles??jo;return t.length<n?!1:new Set(t).size/t.length>=(e.minDistinctRatio??Cp)}function bn(t){return`${t.dir}#${t.prefix}`}function fr(t){let e=ex.exec(t);return e?.groups?{prefix:e.groups.prefix??"",number:e.groups.num}:null}function Dp(t){let e=[];if(!t.isRepo)return e;let n=new Set(t.addedPaths);for(let i of t.namespaces){let s=bn(i),o=t.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}`;e.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}${Uo(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 e.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}function Mp(t){return!t.some(e=>e.status==="open")}function Uo(t,e){let n=0;for(let r of t){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(e.length,"0")}function Ho(t){return t.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Pp(t,e){let n=Ho(e),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=fr(Re.basename(n));if(!i)return r;let s=`${Re.dirname(n)}#${i.prefix}`,o=t.namespaces.find(u=>bn(u)===s)??null;if(!o)return{...r,number:i.number};let c=t.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:Uo(c.keys(),i.number)}}function vi(t){let e=t?.trim();return e||null}function _n(t){return t?t.split(`
|
|
26
|
+
`).filter(Boolean):[]}function tx(t){let e=vi(R(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(e){let n=/refs\/remotes\/origin\/(.+)$/.exec(e);if(n)return n[1]}for(let n of["main","master"])if(R(t,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Lp(t,e={}){let n=e.minFiles??jo,r=["ls-files","-z","--"];r.push(...e.dirs?.length?e.dirs:["."]);let i=R(t,r);if(i===null)return[];let s=new Map;for(let o of i.split("\0").filter(Boolean)){let c=Re.dirname(o),l=fr(Re.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=>Op(o.numbers,{...e,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)=>bn(o).localeCompare(bn(c)))}async function Wo(t,e={}){let n=[];if(vi(R(t,["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=Lp(t,e),s=new Map(i.map(m=>[bn(m),m])),o=[...new Set(i.map(m=>m.dir))],c=new Map,l=a((m,g,y)=>{let _=Re.dirname(m),w=fr(Re.basename(m));if(!w)return;let k=`${_}#${w.prefix}`;if(!s.has(k))return;let x=c.get(k)??new Map,S=x.get(w.number)??[];S.push({kind:g,where:y,path:m}),x.set(w.number,S),c.set(k,x)},"record"),d=a((m,g,y)=>{if(o.length===0)return;let _=R(t,["ls-tree","-r","--name-only",m,"--",...o]);if(_===null){n.push(`could not read ${y}`);return}for(let w of _n(_))l(w,g,y)},"scanTree");for(let m of o){let g=Re.join(t,m);if(Lo(g))try{for(let y of Ip(g))l(`${m}/${y}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let u=tx(t),p=e.baseRef??(u?`origin/${u}`:null);if(p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),e.includeBranches!==!1){let m=vi(R(t,["rev-parse","--abbrev-ref","HEAD"]));for(let g of _n(R(t,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==m&&d(g,"branch",`Branch ${g}`)}if(e.includeWorktrees!==!1){let m=vi(R(t,["rev-parse","--show-toplevel"]));for(let g of _n(R(t,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===m||!Lo(y)))for(let _ of o){let w=Re.join(y,_);if(Lo(w))try{for(let k of Ip(w))l(`${_}/${k}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${_} in ${y}`)}}}}let h=[];if(p&&o.length>0){let m=R(t,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...o]);m===null?n.push($o):h=_n(m);let g=R(t,["ls-files","--others","--exclude-standard","--",...o]);g!==null&&(h=[...h,..._n(g)]);let y=R(t,["diff","--cached","--name-only","--diff-filter=A","--",...o]);y!==null&&(h=[...h,..._n(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:h,skipped:n}}async function Ct(t,e={}){let n=await Wo(t,e),r=Dp(n);return{ok:Mp(r),findings:r,facts:n}}async function Ot(t,e,n={}){let r=Ho(e);if(!fr(Re.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Wo(t,{...n,dirs:n.dirs??[Re.dirname(r)]});return Pp(i,r)}var $o,ex,jo,Cp,mr=b(()=>{"use strict";te();$o="could not diff against the base ref \u2014 everything reported as info";a(Fo,"isNumberCollisionsGraded");ex=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,jo=3,Cp=.8;a(Op,"isCounterNamespace");a(bn,"namespaceKey");a(fr,"parseNumbered");a(Dp,"computeNumberCollisions");a(Mp,"isCollisionFree");a(Uo,"suggestNextNumber");a(Ho,"normaliseRepoPath");a(Pp,"checkProposedNumber");a(vi,"trimOrNull");a(_n,"lines");a(tx,"resolveDefaultBranch");a(Lp,"detectNamespaces");a(Wo,"gatherNumberCollisionFacts");a(Ct,"checkNumberCollisions");a(Ot,"checkNumberForPath")});import{execFileSync as nx}from"node:child_process";import{createHash as rx}from"node:crypto";function Go(t){return rx("sha256").update(t).digest("hex")}function ix(t){let e=t.trim();if(!e)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(e);if(n)e=e.slice(n[0].length),e=e.replace(/^[^@/]+@/,""),e=e.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{e=e.replace(/^[^@/]+@/,"");let r=e.indexOf(":");r>=0&&(e=`${e.slice(0,r)}/${e.slice(r+1)}`)}return e=e.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),e.length>0?e:null}function sx(t){let e=ix(t);return e?Go(e):null}function ax(t){return typeof t=="string"&&ox.test(t)}function $p(t=process.cwd()){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(ax(e))return e;let n;try{n=nx("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?sx(n):null}var ox,Bo=b(()=>{"use strict";a(Go,"sha256Hex");a(ix,"normalizeRemoteUrl");a(sx,"projectKeyFromRemote");ox=/^[a-f0-9]{64}$/;a(ax,"isProjectKey");a($p,"computeProjectKey")});function Yo(t){return`spec.${t}`}function wn(t,e={}){switch(t){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return e.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(t)}' is not a finding status`)}}function cx(t,e){let n=Array.from(t),r=Array.from(e),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 Fp(t){let e=t.map(n=>n.normalize("NFC"));return Array.from(new Set(e)).sort(cx)}function hr(t){return Go(JSON.stringify(Fp(t)))}var Ko,Vo,zo,qo,Jo=b(()=>{"use strict";Bo();Ko={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.0.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.0.0",rules:["agentdoc.added_prose"]}},Vo="number.collision",zo="theme.dead_class",qo="acl.missing_revoke";a(Yo,"specDriftRuleId");a(wn,"gradeEngineStatus");a(cx,"codePointCompare");a(Fp,"normalizeEvidenceForHash");a(hr,"hashDetectorEvidence")});import{existsSync as lx,readFileSync as jp}from"node:fs";import{posix as dx}from"node:path";function Si(t,e){let n=t[e],r=e+1;for(;r<t.length;){let i=t[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return t.length}function Ei(t,e){if(t.startsWith("//",e)){let n=t.indexOf(`
|
|
27
|
+
`,e);return n===-1?t.length:n+1}if(t.startsWith("/*",e)){let n=t.indexOf("*/",e+2);return n===-1?t.length:n+2}return e+1}function gr(t){return t==='"'||t==="'"||t==="`"}function Ti(t,e){return t[e]==="/"&&(t[e+1]==="/"||t[e+1]==="*")}function ki(t,e){let n=t[e];if(n!=="["&&n!=="{")return null;let r=0,i=e;for(;i<t.length;){let s=t[i];if(gr(s)){i=Si(t,i);continue}if(Ti(t,i)){i=Ei(t,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return t.slice(e,i+1);i++}return null}function ux(t){let e=0;for(;;){for(;e<t.length&&/\s/.test(t[e]);)e++;if(Ti(t,e)){e=Ei(t,e);continue}break}return t.slice(e)}function vn(t){let e=[],n=0,r=0,i=0;for(;i<t.length;){let s=t[i];if(gr(s)){i=Si(t,i);continue}if(Ti(t,i)){i=Ei(t,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(e.push(t.slice(r,i)),r=i+1),i++}return e.push(t.slice(r)),e.map(s=>ux(s).trim()).filter(s=>s.length>0)}function Gp(t){let e=Si(t,0);return t.slice(1,e-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
28
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function px(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zo(t,e){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${px(e)}\b`,"m").exec(t);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<t.length;){let o=t[i];if(gr(o)){i=Si(t,i);continue}if(Ti(t,i)){i=Ei(t,i);continue}if(!s){if(o==="="&&t[i+1]!=="="&&!"=!<>".includes(t[i-1]??" "))s=!0;else if(o===";")return null;i++;continue}if(o==="[")return ki(t,i);if(o===";")return null;i++}return null}function Qo(t){let e={};if(!t.startsWith("{"))return e;for(let n of vn(t.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();gr(s[0]??"")&&(e[i]=Gp(s))}return e}function fx(t,e){if(!t.startsWith("{"))return null;for(let n of vn(t.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===e)return r[4].trim()}return null}function Bp(t,e){if(!e)return{...t};let n={};for(let r of e)n[r]=t[r]??"";return n}function Kp(){let t=new Map;return e=>{let n=e.join("\0"),r=t.get(n)??0;return t.set(n,r+1),r}}function Vp(t,e){let n=Zo(t,e.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${e.symbol}\` in ${e.path}`,dropped:0};let r=Kp(),i=[],s=0;for(let o of vn(n.slice(1,-1))){if(!o.startsWith("{")){s++;continue}let c=Qo(o),l=c[e.key_field];if(!l){s++;continue}let d=(e.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:Bp(c,e.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${e.symbol}\` in ${e.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function zp(t,e){let n=Zo(t,e.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${e.symbol}\` in ${e.path}`,dropped:0};if(e.levels.length===0)return{records:[],error:`contract declares no levels for \`${e.symbol}\``,dropped:0};let r=Kp(),i=[],s=0,o=a((c,l,d)=>{let u=e.levels[l],p=l===e.levels.length-1;for(let h of vn(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!h.startsWith("{")){s++;continue}let y=Qo(h);for(let[_,w]of Object.entries(u.fields??{}))m[_]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let _=fx(h,u.children);g=_&&_.startsWith("[")?ki(_,0):null}}else{if(!h.startsWith("[")){s++;continue}let y=vn(h.slice(1,-1));for(let[_,w]of Object.entries(u.fields??{})){let k=y[Number(w)];m[_]=k!==void 0&&gr(k[0]??"")?Gp(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?ki(_,0):null}}if(p){let y=m[e.key_field];if(!y){s++;continue}let _=(e.partition_by??[]).map(w=>m[w]??"");i.push({key:y,fields:Bp(m,e.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&o(g,l+1,m)}},"walk");return o(n,0,{}),i.length===0?{records:[],error:`\`${e.symbol}\` in ${e.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Up(t,e){return e.extractor==="object-array"?Vp(t,e):zp(t,e)}function qp(t,e,n){let r=t;return e.strip_prefix&&r.startsWith(e.strip_prefix)&&(r=r.slice(e.strip_prefix.length)),e.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function Yp(t,e,n){return`spec.drift:${t}#${e}:${n}`}function mx(t){return t.orderPath.join(" / ")||"(flat)"}function Jp(t,e,n,r){let i=[],s=a((d,u,p,h,m,g)=>{i.push({id:Yp(t.id,d,p),contract:t.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(e.map(d=>[d.key,d]));for(let d of e){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 ${mx(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 t.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 e){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(t.grounding)for(let d of new Set([...o.keys(),...c.keys()])){if(qp(d,t.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 ${t.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 hx(t,e,n){let r=[];for(let i of t.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=e[i.counts];l!==d&&r.push({id:`spec.drift:${t.id}#assertion:${i.path}`,contract:t.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 Hp(t,e){return{id:`contract.unreadable:${t}`,contract:t,dimension:"contract",status:"open",key:null,title:`Contract "${t}" could not be evaluated`,detail:e,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 Xp(t,e={}){let n=a(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!t.isRepo)return n("not a git work tree");if(!t.manifest)return n(t.manifestError??`no contract could be read from ${t.manifestPath}`);let r=e.contracts?.length?t.manifest.contracts.filter(u=>e.contracts.includes(u.id)):t.manifest.contracts;if(r.length===0)return n(e.contracts?.length?`no contract in ${t.manifestPath} matches ${e.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${t.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 x=g==null?m.spec.path:m.impl.path;p.push(Hp(m.id,`Declared file could not be read: ${x}`)),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=Up(g,m.spec),w=Up(y,m.impl);if(_.error||w.error){p.push(Hp(m.id,_.error??w.error??"unknown")),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=_.dropped>0||w.dropped>0;h.push({id:m.id,measured:!0,specRecords:_.records.length,implRecords:w.records.length,partial:k}),k&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${_.dropped} specification and ${w.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(...Jp(m,_.records,w.records,t.files)),p.push(...hx(m,{spec:_.records.length,impl:w.records.length},u))}return{findings:p,contracts:h}},"runOnce"),s=i(t.sources),o=new Set;if(e.includeBaseline!==!1&&t.baseRef&&t.baselineSources.size>0)for(let u of i(t.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(Yp(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 ${t.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>Wp[u.status]-Wp[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 Xo(t){let e=t?.trim();return e||null}function Ri(t){let e;try{e=JSON.parse(t)}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(e);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 gx(t){let e=Xo(R(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(e){let n=/refs\/remotes\/origin\/(.+)$/.exec(e);if(n)return n[1]}for(let n of["main","master"])if(R(t,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function yx(t){let e=new Set;for(let n of t.contracts){e.add(n.spec.path),e.add(n.impl.path);for(let r of n.assertions??[])e.add(r.path)}return[...e]}async function Zp(t,e={}){let n=a((g,y)=>dx.join(g,y),"join"),r=e.manifestPath??xi,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Xo(R(t,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let o=n(t,r);if(!lx(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}=Ri(jp(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 yx(c))try{d.set(g,jp(n(t,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=R(t,["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(e.includeBaseline!==!1){let g=e.baseRef?null:gx(t),y=e.baseRef??(g?`origin/${g}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(h=Xo(R(t,["merge-base",y,"HEAD"])),!h)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())m.set(_,R(t,["show",`${h}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:h,files:u,skipped:i}}async function Dt(t,e={}){let n=await Zp(t,e);return{...Xp(n,e),facts:n}}function ea(t){return t.verdict!=="no_opinion"&&t.facts.baseRef!==null}var xi,Wp,yr=b(()=>{"use strict";te();xi=".maind/spec-contracts.json";a(Si,"endOfString");a(Ei,"skipComment");a(gr,"isQuote");a(Ti,"isCommentStart");a(ki,"sliceBalanced");a(ux,"stripLeadingTrivia");a(vn,"splitTopLevel");a(Gp,"readStringLiteral");a(px,"escapeRe");a(Zo,"findSymbolArray");a(Qo,"parseObjectFields");a(fx,"objectFieldRaw");a(Bp,"pickFields");a(Kp,"makeOrdinals");a(Vp,"extractObjectArray");a(zp,"extractNestedList");a(Up,"extractRecords");a(qp,"isGrounded");a(Yp,"findingId");a(mx,"partitionOf");a(Jp,"compareContract");a(hx,"checkAssertions");a(Hp,"unreadable");Wp={open:0,warn:1,info:2,passed:3};a(Xp,"computeSpecDrift");a(Xo,"trimOrNull");a(Ri,"parseManifest");a(gx,"resolveDefaultBranch");a(yx,"declaredPaths");a(Zp,"gatherSpecDriftFacts");a(Dt,"checkSpecDrift");a(ea,"isSpecDriftGraded")});import{execFileSync as _x}from"node:child_process";import{existsSync as bx,readFileSync as wx}from"node:fs";import{join as vx}from"node:path";function _r(t){let e=[],n=t.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&&e.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":kx.test(i)?"never-published":"released"})}return e}function ef(t){let e=new Map;for(let n of _r(t)){let r=e.get(n.version);r?r.push(n):e.set(n.version,[n])}return[...e.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 tf(t,e){let n=ef(t);if(e===null)return{introduced:[],preExisting:n.map(o=>({...o,countBefore:o.count})),baseResolved:!1};let r=new Map;for(let o of _r(e))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 nf(t){if(!t.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:t};if(t.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:t};let e=[];for(let r of t.files){if(r.head===null)continue;let i=tf(r.head,t.baseRef===null?null:r.base);for(let s of i.introduced)e.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)e.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:!e.some(r=>r.level==="open"),verdict:e.length===0?"clean":"duplicates",reason:null,findings:e,facts:t}}function Qp(t,e){try{return _x("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function xx(t,e={}){let n=Qp(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],t);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=e.baseRef??null,s=r.map(o=>{let c=vx(t,o);return{path:o,head:bx(c)?wx(c,"utf8"):null,base:i===null?null:Qp(["show",`${i}:${o}`],t)}});return{isRepo:!0,baseRef:i,files:s}}function ta(t,e={}){return nf(xx(t,e))}var kx,Ai=b(()=>{"use strict";kx=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;a(_r,"parseVersionHeadings");a(ef,"findDuplicateHeadings");a(tf,"classifyIntroduced");a(nf,"computeChangelogDuplicates");a(Qp,"git");a(xx,"gatherChangelogFacts");a(ta,"checkChangelogDuplicates")});import{execFileSync as Sx}from"node:child_process";import{existsSync as Ex,readFileSync as rf}from"node:fs";import{dirname as sf,join as of}from"node:path";function cf(t){if(!t.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:t};if(t.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:t};if(!t.registryReachable)return{ok:!1,verdict:"no_opinion",reason:t.registryError??"registry unreachable",findings:[],facts:t};let e=[];for(let n of t.packages){let r=new Set(t.published[n.name]??[]),i=new Set(n.documentedBase??n.documented),s=[...n.documented].sort(or);for(let o of s){if(r.has(o)||or(o,n.version)>=0)continue;let c=!i.has(o);e.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(or))r.has(o)&&e.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)||e.push({package:n.name,version:n.version,level:"info",rule:"release.unpublished",title:`${n.name}@${n.version} is not published yet`})}return{ok:!e.some(n=>n.level==="open"),verdict:e.length===0?"clean":"mismatch",reason:null,findings:e,facts:t}}function af(t){let e=_r(t),n=[...new Set(e.filter(s=>s.shape!=="never-published").map(s=>s.version))],r=new Set(n),i=[...new Set(e.filter(s=>s.shape==="never-published"&&!r.has(s.version)).map(s=>s.version))];return{documented:n,neverPublished:i}}function na(t,e){try{return Sx("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function lf(t,e=null){let n=na(["ls-files","-z","--","package.json","*/package.json"],t);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let s;try{s=JSON.parse(rf(of(t,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let o=sf(i)==="."?"":sf(i),c=of(t,o,"CHANGELOG.md"),{documented:l,neverPublished:d}=Ex(c)?af(rf(c,"utf8")):{documented:[],neverPublished:[]},u=o===""?"CHANGELOG.md":`${o}/CHANGELOG.md`,p=e===null?null:na(["show",`${e}:${u}`],t),h=e===null?null:p===null?[]:af(p).documented;r.push({dir:o,name:s.name,version:s.version,documented:l,documentedBase:h,neverPublished:d})}return r}async function Tx(t){let e=`https://registry.npmjs.org/${t.replace("/","%2F")}`,n=await fetch(e,{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 df(t,e={}){if(na(["rev-parse","--is-inside-work-tree"],t)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=lf(t,e.baseRef??null);if(e.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=e.fetchVersions??Tx,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 ra(t,e={}){return cf(await df(t,e))}var ia=b(()=>{"use strict";li();Ai();a(cf,"computeReleaseClaims");a(af,"claimsOf");a(na,"git");a(lf,"discoverPackages");a(Tx,"packument");a(df,"gatherReleaseClaimsFacts");a(ra,"checkReleaseClaims")});import{execFileSync as Rx}from"node:child_process";import{existsSync as Ax,readFileSync as Nx}from"node:fs";import{join as Ix}from"node:path";function uf(t){return t.split(`
|
|
32
|
+
`).map(e=>e.trim()).filter(e=>e.length>0)}function ff(t,e){let n=new Map;for(let s of uf(e??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of uf(t)){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 mf(t){if(!t.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:t};if(t.baseRef===null)return{ok:!1,verdict:"no_opinion",reason:"no base to measure growth against",findings:[],facts:t};if(t.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no agent instruction file tracked",findings:[],facts:t};let e=[];for(let n of t.files){if(n.head===null)continue;let r=ff(n.head,n.base);r.net!==0&&e.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:e.length===0,verdict:e.length===0?"clean":"grown",reason:null,findings:e,facts:t}}function sa(t,e){try{return Rx("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function hf(t,e={}){let n=sa(["ls-files","-z","--",...pf],t);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=e.baseRef&&sa(["merge-base",e.baseRef,"HEAD"],t)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(o=>{let c=Ix(t,o);return{path:o,head:Ax(c)?Nx(c,"utf8"):null,base:r===null?null:sa(["show",`${r}:${o}`],t)}});return{isRepo:!0,baseRef:r,files:s}}function oa(t,e={}){return mf(hf(t,e))}var pf,aa=b(()=>{"use strict";pf=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"];a(uf,"contentLines");a(ff,"proseDelta");a(mf,"computeAgentDocProse");a(sa,"git");a(hf,"gatherAgentDocProseFacts");a(oa,"checkAgentDocProse")});import{execFileSync as Cx}from"node:child_process";import{existsSync as Ox,readFileSync as Dx}from"node:fs";import{join as Mx}from"node:path";function yf(t){if(!t.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:t};if(t.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no workflow files under .github/workflows",findings:[],facts:t};let e=[];for(let n of t.files){if(n.content===null)continue;let r=new Set(n.base===null?[]:ci(n.base).map(i=>i.value));for(let i of ci(n.content)){let s=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,o=t.baseRef!==null&&!r.has(i.value);e.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:!e.some(n=>n.level==="open"),verdict:e.length===0?"clean":"unparsable",reason:null,findings:e,facts:t}}function gf(t,e){try{return Cx("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function _f(t,e={}){let n=gf(["ls-files","-z","--",".github/workflows/*.yml",".github/workflows/*.yaml"],t);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=e.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(s=>{let o=Mx(t,s);return{path:s,content:Ox(o)?Dx(o,"utf8"):null,base:i===null?null:gf(["show",`${i}:${s}`],t)}})}}function ca(t,e={}){return yf(_f(t,e))}var la=b(()=>{"use strict";li();a(yf,"computeWorkflowYaml");a(gf,"git");a(_f,"gatherWorkflowYamlFacts");a(ca,"checkWorkflowYaml")});import{readFileSync as Px}from"node:fs";import{join as Lx,posix as $x}from"node:path";function bf(t){let e="",n=0,r=t.length;for(;n<r;){let i=t[n],s=t[n+1];if(i==="-"&&s==="-"){for(;n<r&&t[n]!==`
|
|
33
|
+
`;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)t[n]==="/"&&t[n+1]==="*"?(c++,n+=2):t[n]==="*"&&t[n+1]==="/"?(c--,n+=2):n++;e+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(t.slice(n));if(c){let l=c[0],d=t.indexOf(l,n+l.length);n=d===-1?r:d+l.length,e+=" ";continue}}let o=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(t[n-1]));if(i==="'"||o){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&t[n]==="\\"){n+=2;continue}if(t[n]==="'"){if(t[n+1]==="'"){n+=2;continue}n++;break}n++}e+=" ";continue}e+=i,n++}return e}function _e(t){let e=[],n="",r=!1,i=!1,s=a(()=>{e.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<t.length;c++){let l=t[c];if(l==='"'){if(r&&t[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let o=e.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 We(t){let e=[],n=0,r="";for(let i of t){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){e.push(r.trim()),r="";continue}r+=i}return r.trim()&&e.push(r.trim()),e}function Fx(t){let e=/^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(t.trim());if(!e)return null;let[,n,r,i,s]=e;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(t))return null;let o=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(o&&!We(o[1]).map(h=>_e(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||!We(c[1]).map(p=>_e(p)?.name??"").filter(Boolean).includes("public"))return null;let d=We(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>_e(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of We(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:[...br]};h[2]!=="("&&br.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function wf(t){let e=/^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(t.trim());if(!e)return null;let[,n,r,i,s]=e;if(n)return null;let o=i.trim();if(jx.test(o))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(o);if(l){if(!We(l[1]).map(h=>_e(h)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=o.replace(/^TABLE\s+/i,""),h=We(p).map(m=>_e(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(h.length===0)return null;c=h}let d=We(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>_e(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of We(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:[...br]};!g&&br.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function ua(t){let e=new Map,n=[...t].sort((i,s)=>Ue(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=bf(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=Fx(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=_e(l[2]);if(!p||p.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&e.has(p.name))continue;e.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 We(p)){let m=_e(h);m&&m.schema==="public"&&e.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=_e(u[1]),h=_e(u[2]);if(p&&h&&p.schema==="public"){let m=e.get(p.name);m&&(e.delete(p.name),e.set(h.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=wf(c);if(!p)continue;let h=p.tables==="all_in_public"?[...e.keys()]:p.tables,m=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!m&&!g)continue;for(let y of h){let _=e.get(y);if(_&&(m&&(_.anonAddressed=!0),g))for(let w of p.writePrivs)_.authWritesRevoked.add(w)}continue}}}return e}function da(t){let e=[];for(let[n,r]of ua(t)){let i=[];r.anonAddressed||i.push("anon"),br.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&e.push({table:n,createdIn:r.createdIn,missing:i})}return e.sort((n,r)=>n.table.localeCompare(r.table))}function vf(t){let e=da(t.files),n=new Map;if(t.baseFiles!==null)for(let r of da(t.baseFiles))n.set(r.table,new Set(r.missing));return e.map(r=>{let i=t.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:${t.dir}#${r.table}`,status:o,project:t.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 ${t.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 kf(t,e){return t===0?"no_opinion":e===0?"clean":"exposed"}function fa(t){return t.verdict!=="no_opinion"&&t.facts.baseRef!==null&&!t.facts.skipped.some(e=>e.endsWith(Ni)||e.endsWith(pa))}function Hx(t,e){try{let n=Px(t,"utf8");return n.length>e?null:n}catch{return null}}function Wx(t,e,n,r,i){let s=R(t,["diff","--name-status",`${r}...HEAD`,"--",e]);if(s===null)return i.push(`could not diff ${e} against ${r} ${Ni}`),null;let o=new Set,c=[];for(let u of s.split(`
|
|
34
|
+
`).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=$x.basename(u),h=yn(p);if(h===null)continue;let m=R(t,["show",`${r}:${u}`]);if(m===null)return i.push(`could not read ${u} at ${r} ${pa}`),null;l.push({name:p,version:h,content:m})}return l}function Mt(t,e={}){let n=e.maxFileBytes??Ux,r=[],i=It(t,e.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=e.includeBaseline!==!1,o=null;if(s)if(e.baseRef)o=e.baseRef;else{let h=bp(t);o=h?`origin/${h}`:null,o===null&&r.push(`no default branch resolvable ${Ni}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let h of i){let m=[];for(let _ of h.files){let w=Hx(Lx(t,_.path),n);if(w===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}m.push({ref:_,content:w})}let g=m.map(({ref:_,content:w})=>({name:_.name,version:_.version,content:w})),y=o===null?null:Wx(t,h.dir,m,o,r);c.push(...vf({dir:h.dir,files:g,baseFiles:y})),l.push({dir:h.dir,migrationCount:g.length,tableCount:ua(g).size})}let d=l.reduce((h,m)=>h+m.migrationCount,0),u=kf(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 br,jx,Ux,Ni,pa,Ii=b(()=>{"use strict";te();ur();a(bf,"stripSql");a(_e,"normalizeQualifiedIdent");a(We,"splitTopLevel");br=["INSERT","UPDATE","DELETE"];a(Fx,"parseDefaultAclTables");jx=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;a(wf,"parseTableRevoke");a(ua,"foldTableAcl");a(da,"evaluateTableAcl");a(vf,"computeTableAclFindings");a(kf,"deriveTableAclVerdict");Ux=5e6,Ni="\u2014 findings reported ungraded (open)",pa="\u2014 baseline degraded";a(fa,"isTableAclGraded");a(Hx,"safeRead");a(Wx,"baseFilesFor");a(Mt,"checkTableAclLint")});import{readFileSync as Gx}from"node:fs";import{join as ma}from"node:path";function ga(t){return t.verdict!=="no_opinion"&&t.graded}function ya(t){let e=new Set;for(let n of t.matchAll(Bx))e.add(n[1]);return e}function _a(t){return new Set([...t].map(e=>e.split("-")[0]))}function Af(t){return t.split(`
|
|
35
|
+
`).map(e=>{let n=e.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":e}).join(`
|
|
36
|
+
`)}function ba(t){let e=_a(t.tokens),n=[];for(let{path:r,content:i}of t.sources){let s=Af(i),o=new Set;for(let c of s.matchAll(Kx)){let l=c[2],d=l.split("-")[0];if(!e.has(d)||t.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 xf(t){return`${t.file} ${t.klass}`}function Vx(t,e){let n=e===null?null:new Set(e.map(xf));return t.map(r=>({...r,status:n!==null&&n.has(xf(r))?"info":"open"}))}function Nf(t,e){return t===0?"no_opinion":e===0?"clean":"drift"}function wa(t){return!(/\.(test|spec)\.[jt]sx?$/.test(t)||/(^|\/)__(tests|mocks)__\//.test(t))}function Ef(t,e){let n=R(t,["ls-files","--",...e]);return n===null?[]:n.split(`
|
|
37
|
+
`).filter(Boolean)}function Pt(t,e={}){let n=e.maxFileBytes??zx,r=new Set;for(let u of Ef(t,["*.css"])){let p=ha(ma(t,u),n);if(p!==null)for(let h of ya(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=e.dirs!==void 0&&e.dirs.length>0?e.dirs.flatMap(u=>Sf.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):Sf,s=[];for(let u of Ef(t,i)){if(!wa(u))continue;let p=ha(ma(t,u),n);p!==null&&s.push({path:u,content:p})}let o=ba({tokens:r,sources:s}),c=e.includeBaseline===!1?null:qx(t,i,n,e.baseRef),l=Vx(o,c?.findings??null),d=Nf(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:_a(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function qx(t,e,n,r){let i=r??Jx(t);if(i===null)return null;let s=R(t,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let o=R(t,["diff","--name-only","--no-renames",s]);if(o===null)return null;let c=new Set(o.split(`
|
|
38
|
+
`).filter(Boolean)),l=a(p=>c.has(p)?R(t,["show",`${s}:${p}`]):ha(ma(t,p),n),"atBase"),d=new Set;for(let p of Tf(t,s,["*.css"])){let h=l(p);if(h!==null)for(let m of ya(h))d.add(m)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let p of Tf(t,s,e)){if(!wa(p))continue;let h=l(p);h===null||h.length>n||u.push({path:p,content:h})}return{findings:ba({tokens:d,sources:u}),mergeBase:s}}function Tf(t,e,n){let r=R(t,["ls-tree","-r","--name-only",e]);return r===null?[]:r.split(`
|
|
39
|
+
`).filter(i=>i.length>0&&n.some(s=>Yx(i,s)))}function Yx(t,e){let n=e.lastIndexOf("/"),r=n<0?e:e.slice(n+1),i=n<0?"":e.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!t.startsWith(i+"/"))return!1;let s=t.slice(t.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}function Jx(t){let e=R(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(e?/refs\/remotes\/origin\/(.+)$/.exec(e):null)?.[1]??["main","master"].find(i=>R(t,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function ha(t,e){try{let n=Gx(t,"utf8");return n.length>e?null:n}catch{return null}}var Rf,Bx,Kx,Sf,zx,Ci=b(()=>{"use strict";te();a(ga,"isThemeClassDriftGraded");Rf=["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"],Bx=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Kx=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Rf.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");a(ya,"extractTokens");a(_a,"deriveNamespaces");a(Af,"stripCommentLines");a(ba,"evaluateThemeClasses");a(xf,"findingKey");a(Vx,"gradeAgainstBaseline");a(Nf,"deriveThemeClassVerdict");Sf=["*.ts","*.tsx","*.js","*.jsx"],zx=15e5;a(wa,"isScannableSource");a(Ef,"listTracked");a(Pt,"checkThemeClassDrift");a(qx,"baselineFindings");a(Tf,"listTrackedAt");a(Yx,"matchesSourcePattern");a(Jx,"resolveBaseRef");a(ha,"safeRead")});function va(t){return Ko[t].version}function Ge(t,e,n,r){return{detector_id:t,detector_version:va(t),state:e,finding_count:n,...r?{reason:r}:{}}}function W(t,e,n){return{summary:Ge(t,e,0,n),findings:[]}}function Pf(t){return t==="open"||t==="warn"||t==="info"}function Xx(t){let e="det_number_collisions";if(!t.ok)return W(e,"unavailable",t.error);let{facts:n,findings:r}=t.report;if(!n.isRepo)return W(e,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return W(e,"not_applicable","no numbered namespaces");if(!Fo(n))return W(e,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!Pf(s.status))continue;let{level:o,baseline:c}=wn(s.status);i.push({detector_id:e,rule_id:Vo,level:o,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:Ge(e,"ran",i.length),findings:i}}function Zx(t){let e="det_spec_drift";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(!n.facts.isRepo)return W(e,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return W(e,"not_applicable",n.reason??"no opinion");if(!ea(n))return W(e,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Pf(i.status))continue;let{level:s,baseline:o}=wn(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:e,rule_id:Yo(i.dimension),level:s,baseline:o,evidence:[i.id],title:i.title})}return{summary:Ge(e,"ran",r.length),findings:r}}function Qx(t){let e="det_theme_class_drift";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(n.verdict==="no_opinion")return W(e,"not_applicable","no theme tokens");if(!ga(n))return W(e,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=wn(i.status);r.push({detector_id:e,rule_id:zo,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:Ge(e,"ran",r.length),findings:r}}function eS(t){let e="det_table_acl_lint";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(n.verdict==="no_opinion")return W(e,"not_applicable","no supabase migrations");if(!fa(n))return W(e,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=wn(i.status);r.push({detector_id:e,rule_id:qo,level:s,baseline:o,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Ge(e,"ran",r.length),findings:r}}function tS(t){let e="det_changelog_duplicates";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(n.verdict==="no_opinion")return W(e,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return W(e,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:e,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:Ge(e,"ran",r.length),findings:r}}function nS(t){let e="det_workflow_yaml";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(n.verdict==="no_opinion")return W(e,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return W(e,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:e,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:Ge(e,"ran",r.length),findings:r}}function rS(t){let e="det_release_claims";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?W(e,"ungraded",n.reason??"registry unreachable"):W(e,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:e,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:Ge(e,"ran",r.length),findings:r}}function iS(t){let e="det_agent_doc_prose";if(!t.ok)return W(e,"unavailable",t.error);let n=t.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.files.length>0&&n.facts.baseRef===null?W(e,"ungraded",n.reason??"no base ref to grade against"):W(e,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:e,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:Ge(e,"ran",r.length),findings:r}}function ka(t,e){return t.detector_id.localeCompare(e.detector_id)||t.rule_id.localeCompare(e.rule_id)||Oi[t.level]-Oi[e.level]||Cf[t.baseline]-Cf[e.baseline]||(t.evidence_hash<e.evidence_hash?-1:t.evidence_hash>e.evidence_hash?1:0)}function Of(t){return t.baseline==="pre_existing"?3:t.level==="open"?0:t.level==="warn"?1:2}function sS(t){let e=new Map,n=new Map;for(let i of t)if(i.baseline==="introduced"){let s=hr(i.evidence),o=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=e.get(o);c?c.count+=1:e.set(o,{detector_id:i.detector_id,detector_version:va(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,Oi[i.level]<Oi[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=[...e.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:va(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:hr(i.evidence),count:i.count});return r.sort(ka)}function oS(t,e){let n=t.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<t.length||e>0?"partial":"full"}function Ae(t){let e={det_number_collisions:Xx(t.number),det_spec_drift:Zx(t.spec),det_theme_class_drift:Qx(t.theme),det_table_acl_lint:eS(t.acl),det_changelog_duplicates:tS(t.changelog),det_workflow_yaml:nS(t.workflow),det_release_claims:rS(t.release),det_agent_doc_prose:iS(t.agentDoc)},n=If.map(l=>e[l].summary),r=If.flatMap(l=>e[l].findings),i=sS(r),s=[...i].sort((l,d)=>Of(l)-Of(d)||ka(l,d)).slice(0,Df).sort(ka),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:hr(l.evidence),title:l.title}));return{findings:s,coverage:oS(n,o),engines:n,local:c,truncated:o}}function Lt(t){return{number:{ok:!1,error:t},spec:{ok:!1,error:t},theme:{ok:!1,error:t},acl:{ok:!1,error:t},changelog:{ok:!1,error:t},workflow:{ok:!1,error:t},release:{ok:!1,error:t},agentDoc:{ok:!1,error:t}}}function Sa(t){return t instanceof Error?t.message:String(t)}async function it(t){try{return{ok:!0,report:await t()}}catch(e){return{ok:!1,error:Sa(e)}}}async function Ea(t,e={}){let n={...Mf,...e.engines};try{if(!Lf(t))return Ae(Lt("not a git work tree"));let r=await $f(t,n,e.baseRef),i=await xa(t,n,e.baseRef,e.scope??"local",e.includeWorktrees);return Ae({...r,number:i})}catch(r){return Ae(Lt(`detector adapter failed: ${Sa(r)}`))}}async function Ta(t,e={}){let n={...Mf,...e.engines};try{if(!Lf(t)){let o=Ae(Lt("not a git work tree"));return{commit:o,local:o}}let r=await $f(t,n,e.baseRef),i=await xa(t,n,e.baseRef,"commit"),s=await xa(t,n,e.baseRef,"local");return{commit:Ae({...r,number:i}),local:Ae({...r,number:s})}}catch(r){let i=Ae(Lt(`detector adapter failed: ${Sa(r)}`));return{commit:i,local:i}}}function Lf(t){return R(t,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function $f(t,e,n){let r=n?{baseRef:n}:{};return{spec:await it(()=>e.spec(t,r)),theme:await it(()=>e.theme(t,r)),acl:await it(()=>e.acl(t,r)),changelog:await it(()=>e.changelog(t,r)),workflow:await it(()=>e.workflow(t,r)),release:await it(()=>e.release(t,r)),agentDoc:await it(()=>e.agentDoc(t,r))}}function xa(t,e,n,r,i){let s=r==="local";return it(()=>e.number(t,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var Df,Mf,If,Oi,Cf,Ra=b(()=>{"use strict";te();Jo();mr();yr();ia();aa();la();Ai();Ii();Ci();Df=64,Mf={number:a((t,e)=>Ct(t,e),"number"),spec:a((t,e)=>Dt(t,e),"spec"),theme:a((t,e)=>Pt(t,e),"theme"),acl:a((t,e)=>Mt(t,e),"acl"),changelog:a((t,e)=>ta(t,e),"changelog"),workflow:a((t,e)=>ca(t,e),"workflow"),release:a((t,e)=>ra(t,e),"release"),agentDoc:a((t,e)=>oa(t,e),"agentDoc")},If=["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(va,"versionOf");a(Ge,"summary");a(W,"noFindings");a(Pf,"isFindingStatus");a(Xx,"adaptNumber");a(Zx,"adaptSpec");a(Qx,"adaptTheme");a(eS,"adaptAcl");a(tS,"adaptChangelog");a(nS,"adaptWorkflow");a(rS,"adaptRelease");a(iS,"adaptAgentDoc");Oi={open:0,warn:1,info:2},Cf={introduced:0,pre_existing:1};a(ka,"compareWire");a(Of,"capPriority");a(sS,"buildWire");a(oS,"deriveCoverage");a(Ae,"adaptDetectorReports");a(Lt,"unavailableDetectorReports");a(Sa,"errorText");a(it,"attempt");a(Ea,"runRepoHealthDetectors");a(Ta,"runRepoHealthDetectorScopes");a(Lf,"insideWorkTree");a($f,"runSharedEngines");a(xa,"runNumberEngine")});var Ff,Aa=b(()=>{"use strict";Ff=[{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:/^\.github\/workflows\/[^/]+\.ya?ml$|^\.gitlab-ci\.yml$/},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function jf(t){let e=new Set;for(let[n,r]of t.paths)for(let i of Ff){if(e.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){e.add(i.flag);continue}let s=aS(n,t);s!==null&&i.content.test(s)&&e.add(i.flag)}return[...e].sort()}function aS(t,e){let n=e.hunks.get(t);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
40
|
+
`):e.readUntracked(t)}var Uf=b(()=>{"use strict";Aa();a(jf,"scanRiskFlags");a(aS,"contentForPath")});var kn,Hf,xn,Sn,Na,Di,Ia,Mi,Pi,Li,Ca,Wf,wr=b(()=>{"use strict";kn="3",Hf=`
|
|
38
41
|
CREATE TABLE IF NOT EXISTS meta (
|
|
39
42
|
key TEXT PRIMARY KEY,
|
|
40
43
|
value TEXT NOT NULL
|
|
@@ -86,6 +89,35 @@ CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
|
|
|
86
89
|
tokenize = 'unicode61'
|
|
87
90
|
);
|
|
88
91
|
|
|
92
|
+
-- Per-file resolution facts (ADR-358 E1). Cross-file edges are NOT derived from
|
|
93
|
+
-- the file that changed but recomputed from these rows for the whole index after
|
|
94
|
+
-- every run \u2014 so an edge from an unchanged file into a changed one can never go
|
|
95
|
+
-- stale. Written in the same transaction as the file's nodes, deleted with them.
|
|
96
|
+
CREATE TABLE IF NOT EXISTS file_refs (
|
|
97
|
+
file_path TEXT NOT NULL,
|
|
98
|
+
src_key TEXT NOT NULL,
|
|
99
|
+
kind TEXT NOT NULL,
|
|
100
|
+
target_name TEXT NOT NULL,
|
|
101
|
+
receiver TEXT,
|
|
102
|
+
receiver_type TEXT
|
|
103
|
+
);
|
|
104
|
+
CREATE INDEX IF NOT EXISTS file_refs_file_idx ON file_refs(file_path);
|
|
105
|
+
CREATE TABLE IF NOT EXISTS file_imports (
|
|
106
|
+
file_path TEXT NOT NULL,
|
|
107
|
+
specifier TEXT NOT NULL,
|
|
108
|
+
imported_name TEXT,
|
|
109
|
+
local_name TEXT
|
|
110
|
+
);
|
|
111
|
+
CREATE INDEX IF NOT EXISTS file_imports_file_idx ON file_imports(file_path);
|
|
112
|
+
CREATE TABLE IF NOT EXISTS file_exports (
|
|
113
|
+
file_path TEXT NOT NULL,
|
|
114
|
+
exported_name TEXT NOT NULL,
|
|
115
|
+
local_name TEXT,
|
|
116
|
+
specifier TEXT,
|
|
117
|
+
imported_name TEXT
|
|
118
|
+
);
|
|
119
|
+
CREATE INDEX IF NOT EXISTS file_exports_file_idx ON file_exports(file_path);
|
|
120
|
+
|
|
89
121
|
-- Reserved for Phase 2 (semantic). Unused in Phase 1.
|
|
90
122
|
CREATE TABLE IF NOT EXISTS embeddings (
|
|
91
123
|
node_key TEXT PRIMARY KEY,
|
|
@@ -93,33 +125,33 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
93
125
|
vec BLOB NOT NULL,
|
|
94
126
|
content_hash TEXT NOT NULL
|
|
95
127
|
);
|
|
96
|
-
`,mn="schema_version",hn="last_index_commit",ya="last_indexed_at",xi="embed_recipe_version",Ei="embed_model",Ai="embed_dim",_a="last_synced_at",yf="last_synced_commit"});function ba(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 _f(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of ba(e.name))t.add(i);for(let i of ba(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function bf(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 ba(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var wa=b(()=>{"use strict";o(ba,"splitIdentifier");o(_f,"buildSearchText");o(bf,"toFtsMatchQuery")});import{readFileSync as wf}from"node:fs";import{posix as vf}from"node:path";function kf(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 Nt(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function Sf(e){return e==="added"?0:e==="modified"?1:2}function gS(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var pr,va=b(()=>{"use strict";Zr();Eu();to();Tu();Cu();te();Uu();fo();So();sr();ha();cr();hf();ur();wa();pr=class{static{o(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(mn),i=await this.store.countFiles()>0;(t.full||i&&r!==fn)&&await this.wipe();let s=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(s.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let g=lo(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(g===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");a=g}else a=Mu(this.repoRoot);let c=new Set(a.map(g=>g.path)),l=new Map(s.map(g=>[g.path,g])),u=s.length>0&&!t.full,d={filesScanned:a.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let g of s)c.has(g.path)||(await this.store.deleteFile(g.path),d.filesDeleted++);let p=[],h=0;for(let g of a){h++;let y=Lu(this.repoRoot,g.path);if(!y){d.filesSkipped++;continue}let _=l.get(g.path);if(_&&_.mtimeMs===y.mtimeMs&&_.size===y.size){d.filesSkipped++;continue}let w=this.readRepoFile(g.path);if(w===null){d.filesSkipped++;continue}let k=ci(w);if(_&&_.contentHash===k){await this.store.upsertFile({..._,mtimeMs:y.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let x=await this.parser.parse(g.path,w,g.language),S=new Map;for(let $ of x.nodes)S.set($.nodeKey,_f($));let I={path:g.path,language:g.language,contentHash:k,mtimeMs:y.mtimeMs,size:y.size,indexedAt:n};await this.store.replaceFileNodes(I,x.nodes,S),p.push(x),d.filesParsed++,t.onProgress?.({path:g.path,done:h,total:a.length})}if(p.length>0){let g=await this.store.getNameIndex(),y=Ru(g);for(let _ of p){let w=Iu(_,y);await this.store.replaceOutgoingEdges(w.srcKeys,w.edges)}}if(this.embedder&&t.embed){let g=await this.store.getNodesByKinds([...eo]),y=await this.store.getEmbeddingContentHashes(),_=[];for(let k of g){let x=xu(k),S=ci(`${this.embedder.recipeVersion}\0${x}`);y.get(k.nodeKey)!==S&&_.push({nodeKey:k.nodeKey,text:x,hash:S})}let w=64;for(let k=0;k<_.length;k+=w){let x=_.slice(k,k+w),S=await this.embedder.embedDocuments(x.map($=>$.text));await this.store.upsertEmbeddings(x.map(($,H)=>({nodeKey:$.nodeKey,dim:this.embedder.dim,vec:S[H],contentHash:$.hash})));let I=Math.min(k+w,_.length);t.onProgress?.({path:"embedding symbols",done:I,total:_.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(xi,this.embedder.recipeVersion),await this.store.setMeta(Ei,this.embedder.model),await this.store.setMeta(Ai,String(this.embedder.dim))}await this.store.setMeta(mn,fn),await this.store.setMeta(ya,String(n));let m=tr(this.repoRoot);return m&&await this.store.setMeta(hn,m),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}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(ya);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(hn),schemaVersion:await this.store.getMeta(mn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Nt(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&s.push({...kf(c),score:a.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Nt(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Au(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of a){let u=await this.store.getNode(l.nodeKey);u&&c.push({...kf(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Nt(n.maxDepth,3,5),s=Nt(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let p=0;p<i&&d.length>0;p++){let h=[];for(let m of d){let g=await this.store.neighbors(m,r,a,s);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let w=r==="out"?y.dstKey:y.srcKey;u.has(w)||(u.add(w),h.push(w))}}d=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=wf(vf.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let s={};for(let a of r)s[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(Nt(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=lo(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Nt(t.limit,64,200),i=[],s=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&s++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=ai(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(tr(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Ku(this.repoRoot,n,t)}async checkDivergence(t={}){return rr(this.repoRoot,t)}async checkNumberCollisions(t={}){return Et(this.repoRoot,t)}async checkNumberForPath(t,n={}){return At(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Tt(this.repoRoot,t)}async reviewDetectors(t={}){return fa(this.repoRoot,t)}async reviewDetectorScopes(t={}){return ma(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=ai(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=ju(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",a=mf({paths:n,hunks:i,readUntracked:o(h=>this.readRepoFileHead(h,Fu),"readUntracked")}),c=Pu(n.keys()),l=Nt(t.limit,64,t.attest?Jr:200),u=[],d=0,p=0;for(let h of c){let m=await this.store.getNodesByFile(h.path);if(m.length===0)continue;d++;let g=await this.store.getFile(h.path),y=this.readRepoFile(h.path),_=g!==null&&y!==null&&ci(y)!==g.contentHash;_&&(p++,s==="full"&&(s="partial"));let w=n.get(h.path)??"modified",k=i.get(h.path);for(let x of m)u.push(gS(x,w,k,_))}return u.sort((h,m)=>Sf(h.change)-Sf(m.change)||(h.filePath<m.filePath?-1:h.filePath>m.filePath?1:0)||h.startLine-m.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:p,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:a,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:tr(this.repoRoot),dirty:uo(this.repoRoot),baseSha:t.since?li(this.repoRoot,t.since):null,mergeBaseSha:t.since?co(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 wf(vf.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};o(kf,"toHit");o(Nt,"clampLimit");o(Sf,"changeRank");o(gS,"classifyReviewSymbol")});var xf=b(()=>{"use strict";te()});var yS,HM,Ef=b(()=>{"use strict";te();yS=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],HM=new RegExp(yS.join("|"),"g")});import{existsSync as ka,readdirSync as _S,readFileSync as bS}from"node:fs";import{spawnSync as wS}from"node:child_process";import{dirname as vS,join as Ti,posix as Sa}from"node:path";function Tf(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 ${xa} 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 ${xa} 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),a=e.fileVersions.filter(p=>!i.has(p)).sort(Le);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!s.has(p)).sort(Le),l=new Map,u=[];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 u.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(u.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${u.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: ${u.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:u}),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(Le),m=e.remote.versions.filter(g=>!s.has(g)).sort(Le);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 d=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function Rf(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Cf(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(`
|
|
97
|
-
`).filter(Boolean).slice(-1)[0]}}function
|
|
98
|
-
`).map(i=>i.trim()).filter(Boolean)}}function
|
|
99
|
-
`)){if(!s.startsWith("worktree "))continue;let
|
|
100
|
-
|
|
101
|
-
${i}`};return JSON.stringify({jsonrpc:"2.0",id:
|
|
102
|
-
`,{encoding:"utf8",mode:384});try{
|
|
103
|
-
`,{encoding:"utf8",mode:384});try{
|
|
104
|
-
`,{encoding:"utf8",mode:384}),dx(a,s)}catch{}}function Vf(e=ye()){try{let t=JSON.parse(lx(Kf(e),"utf8"));return t.v!==1||typeof t.at!="string"||!fx.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 fx,mx,hx,Na=b(()=>{"use strict";re();fx=["ok","paired","auth_failed","not_paired"],mx="connection-state.json",hx=200;o(Kf,"connectionStatePath");o(gx,"redactDetail");o(Pt,"writeConnectionState");o(Vf,"readConnectionState")});var F,tt=b(()=>{"use strict";F="0.75.0"});import{execFileSync as yx}from"node:child_process";import{createHash as _x}from"node:crypto";function bx(e){return _x("sha256").update(e).digest("hex")}function wx(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 Oa(e){let t=wx(e);return t?bx(t):null}function z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&vx.test(e))return e;let t;try{t=yx("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Oa(t):null}var vx,nt=b(()=>{"use strict";o(bx,"sha256Hex");o(wx,"normalizeRemoteUrl");o(Oa,"projectKeyFromRemote");vx=/^[a-f0-9]{64}$/;o(z,"computeProjectKey")});import Sx from"node:path";import{fileURLToPath as xx}from"node:url";function Ex(e,t=Sx.sep){return e.split(t).includes("_npx")}function Te(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",nm,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):Ex(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 Re(){try{let e=xx(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function vn(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${tm(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:tm(n)).join(" ")}function Li(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(nm)}function Fi(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function tm(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var nm,kn=b(()=>{"use strict";nm="@maind-dev/mcp-bridge";o(Ex,"isEphemeralEntry");o(Te,"resolveBridgeLaunch");o(Re,"currentBridgeEntry");o(vn,"launchToShellCommand");o(Li,"isNpxForm");o(Fi,"isLegacyHookForm");o(tm,"shellQuote")});import*as _e from"node:path";function im(e){let t=e.launch??Te({entryPath:Re(),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 Ax(e){switch(e.platform){case"darwin":return _e.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??_e.join(e.homeDir,"AppData","Roaming");return _e.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??_e.join(e.homeDir,".config");return _e.join(t,"Claude","claude_desktop_config.json")}}}function ji(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:_e.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:_e.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:Ax(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:_e.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:_e.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:_e.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function sm(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Ui(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:rm(e.env.XDG_CONFIG_HOME),appData:rm(e.env.APPDATA)}}function rm(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}var Da=b(()=>{"use strict";kn();o(im,"buildMaindServerEntry");o(Ax,"claudeDesktopConfigPath");o(ji,"getClientTargets");o(sm,"filterTargetsByFamily");o(Ui,"makeDefaultContext");o(rm,"nonEmpty")});import*as q from"node:fs/promises";import*as Hi from"node:path";async function ie(e){try{return await q.readFile(e,"utf8")}catch(t){if(Tx(t))return null;throw t}}async function Pa(e){await q.mkdir(e,{recursive:!0})}async function Y(e,t,n){let r=Hi.dirname(e);await Pa(r);let i=Hi.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await q.writeFile(i,t,{encoding:"utf8",mode:n});try{await q.rename(i,e)}catch(s){if(Rx(s))try{await q.copyFile(i,e),await q.unlink(i).catch(()=>{}),n!==void 0&&await q.chmod(e,n).catch(()=>{});return}catch(a){throw await q.unlink(i).catch(()=>{}),a}throw await q.unlink(i).catch(()=>{}),s}}async function om(e,t){let n=await ie(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function Tx(e){return am(e)&&e.code==="ENOENT"}function Rx(e){return!am(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function am(e){return typeof e=="object"&&e!==null&&"code"in e}var Ge=b(()=>{"use strict";o(ie,"readFileSafe");o(Pa,"ensureDir");o(Y,"atomicWriteFile");o(om,"hasLinePrefix");o(Tx,"isNoEnt");o(Rx,"isWindowsRenameFailure");o(am,"isNodeError")});import{existsSync as Kx}from"node:fs";import*as fm from"node:path";function $t(e,t={},n=Fa){let r=t.fileExists??Kx,i=t.expectedCommand??Vx,s={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);La(a)&&(s=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=zx(s,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(Fi(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(Li(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let d=qx(l);return d!==null&&!r(d)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${d}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function ja(e){return e.some(t=>t.status!=="ok")}function Bi(e){return e.some(t=>t.remedy==="run-install")}function Vx(e){return vn(Te({entryPath:Re(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function zx(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!La(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!La(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function qx(e){for(let t of Yx(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return fm.isAbsolute(t)?t:null;return null}function Yx(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 La(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Fa,Wi,Sn=b(()=>{"use strict";kn();Fa=[{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."}],Wi=[{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. 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."}];o($t,"inspectHookWiring");o(ja,"hasWiringDrift");o(Bi,"needsInstallRun");o(Vx,"defaultExpectedCommand");o(zx,"findCommand");o(qx,"extractScriptPath");o(Yx,"tokenize");o(La,"isObject")});import*as Ga from"node:path";import*as hm from"node:readline";async function gm(e,t){let n=Ga.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 ie(n)}catch(h){return{target:r,action:"merge",status:"failed",detail:`read: ${Ua(h)}`}}let s,a="create";if(i===null||i.trim().length===0)s={};else{a="merge";try{let h=JSON.parse(i);if(!Ha(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: ${Ua(h)}`}}}let c=Xx(s,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await Zx(e.out,`
|
|
105
|
-
Merge a ${
|
|
106
|
-
${
|
|
107
|
-
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...
|
|
108
|
-
`;if(
|
|
109
|
-
`,1)[0]??"").trim().slice(0,200)}function lE(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 dE(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=lE(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function En(e,t,n,r){for(let i of dE(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var zi=b(()=>{"use strict";o(Ki,"newResult");o(st,"line1");o(Vi,"signatureOf");o(lE,"calleeName");o(dE,"collectCallTargets");o(En,"addCallRefs")});function Tm(e,t){let n=Ki();for(let r of e.namedChildren)uE(r,t,n);return n}function Rm(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function uE(e,t,n){let r=Rm(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??fE(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=qi(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&En(n,s.nodeKey,a,Am);return}case"class_definition":pE(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let a=qi(r,t,s.text,s.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function pE(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=qi(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=Rm(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,p=qi(l,t,u,d,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&En(n,p.nodeKey,h,Am)}}function qi(e,t,n,r,i){return{nodeKey:ei(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:st(e.startPosition.row),endLine:st(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Vi(e),doc:null}}function fE(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var Am,Im=b(()=>{"use strict";Qn();zi();Am="call";o(Tm,"extractPython");o(Rm,"unwrapDecorated");o(uE,"handleTopLevel");o(pE,"addClass");o(qi,"makeNode");o(fE,"firstDottedName")});function Om(e,t){let n=Ki();for(let r of e.namedChildren)hE(r,t,n);return n}function mE(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function hE(e,t,n){let r=mE(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:yE(i)});return}case"function_declaration":case"generator_function_declaration":{Cm(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{gE(r,t,n);return}case"interface_declaration":Ka(r,t,n,"interface");return;case"type_alias_declaration":Ka(r,t,n,"type_alias");return;case"enum_declaration":Ka(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let s=i.childForFieldName("name");if(!s||s.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";Cm(i,t,n,c?"function":"variable",s,a)}return}default:return}}function Cm(e,t,n,r,i,s){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Yi(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=s??e.childForFieldName("body")??e;r==="function"&&u&&En(n,l.nodeKey,u,Nm)}function Ka(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Yi(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function gE(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Yi(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let s=e.childForFieldName("body");if(s)for(let a of s.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=Yi(a,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&En(n,u.nodeKey,d,Nm)}}function Yi(e,t,n,r,i){return{nodeKey:ei(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:st(e.startPosition.row),endLine:st(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Vi(e),doc:null}}function yE(e){return e.replace(/^["'`]|["'`]$/g,"")}var Nm,Dm=b(()=>{"use strict";Qn();zi();Nm="call_expression";o(Om,"extractTypescript");o(mE,"unwrapExport");o(hE,"handleTopLevel");o(Cm,"addFunctionLike");o(Ka,"addSimpleNamed");o(gE,"addClass");o(Yi,"makeNode");o(yE,"stripQuotes")});import{createRequire as _E}from"node:module";import{join as bE}from"node:path";function $m(e,t){return t?bE(t,Pm[e]):_E(import.meta.url).resolve(`tree-sitter-wasms/out/${Pm[e]}`)}var Pm,Mm,Lm=b(()=>{"use strict";Pm={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Mm="tree-sitter.wasm";o($m,"grammarPath")});import{join as wE}from"node:path";import Va from"web-tree-sitter";var vE,Ji,Fm=b(()=>{"use strict";Qn();ri();Im();Dm();zi();Lm();vE=["typescript","tsx","javascript","python"],Ji=class{static{o(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Va.init(this.assetDir?{locateFile:o(t=>wE(this.assetDir,t||Mm),"locateFile")}:void 0),this.parser=new Va,this.initialized=!0)}supports(t){return vE.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:[]};let a=s.rootNode,c=Qr(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:st(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?Tm(a,u):Om(a,u);return s.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Va.Language.load($m(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as kE}from"node:module";function Um(){return jm("node:sqlite")}function An(){if(br)return br;try{let{DatabaseSync:e}=Um(),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(),br={ok:!0}}finally{t.close()}}catch(e){br={ok:!1,reason:e instanceof Error?e.message:String(e)}}return br}function SE(e){let{DatabaseSync:t}=Um(),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>n.exec(r),"exec"),close:o(()=>n.close(),"close"),transaction:o(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function xE(e){let t=jm("better-sqlite3"),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>{n.exec(r)},"exec"),close:o(()=>{n.close()},"close"),transaction:o(r=>n.transaction(r),"transaction")}}function EE(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Xi(e){let t=EE(),n=o(i=>{let s=i==="node:sqlite"?SE(e):xE(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=An();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=An();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 jm,br,za=b(()=>{"use strict";jm=kE(import.meta.url);o(Um,"loadBuiltin");br=null;o(An,"probeBuiltinSqlite");o(SE,"openBuiltin");o(xE,"openBetter");o(EE,"backendOverride");o(Xi,"openSqliteDatabase")});function Zi(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 Hm,wr,Gm=b(()=>{"use strict";za();ur();wa();o(Zi,"toNodeRow");Hm=400,wr=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Xi(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(gf)}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){this.db.transaction(()=>{this.deleteFileGraph(t.path);let s=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)s.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),a.run(c.nodeKey,r.get(c.nodeKey)??c.name);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 replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)s.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?Zi(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Zi)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Zi)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Zi)}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=bf(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
128
|
+
`,xn="schema_version",Sn="last_index_commit",Na="last_indexed_at",Di="edges_dirty",Ia="resolve_config_fp",Mi="embed_recipe_version",Pi="embed_model",Li="embed_dim",Ca="last_synced_at",Wf="last_synced_commit"});function Oa(t){return t.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(e=>e.length>0)}function Gf(t){let e=new Set;e.add(t.name.toLowerCase()),e.add(t.qualifiedName.toLowerCase());for(let i of Oa(t.name))e.add(i);for(let i of Oa(t.qualifiedName))e.add(i);let n=[t.doc??"",t.signature??""].join(" ").trim(),r=[...e].join(" ");return n?`${r} ${n}`:r}function Bf(t){let e=new Set;for(let n of t.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){e.add(r.toLowerCase());for(let i of Oa(r))e.add(i)}}return e.size===0?null:[...e].map(n=>`${n}*`).join(" OR ")}var Da=b(()=>{"use strict";a(Oa,"splitIdentifier");a(Gf,"buildSearchText");a(Bf,"toFtsMatchQuery")});import{readFileSync as Kf}from"node:fs";import{posix as Vf}from"node:path";function zf(t){return{nodeKey:t.nodeKey,kind:t.kind,name:t.name,qualifiedName:t.qualifiedName,filePath:t.filePath,language:t.language,startLine:t.startLine,endLine:t.endLine}}function $t(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(1,Math.min(n,Math.floor(t)))}function qf(t){return t==="added"?0:t==="modified"?1:2}function cS(t,e,n,r){if(r)return{...t,change:"co_located",changedLineCount:0,staleIndex:!0};if(e==="added"||n?.wholeFile)return{...t,change:"added",changedLineCount:t.endLine-t.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...t,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let o of n.addedRanges){let c=Math.max(o.start,t.startLine),l=Math.min(o.end,t.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(o=>o>=t.startLine-1&&o<=t.endLine);return i>0||s?{...t,change:"modified",changedLineCount:i,staleIndex:!1}:{...t,change:"co_located",changedLineCount:0,staleIndex:!1}}var vr,Ma=b(()=>{"use strict";li();Wu();po();Bu();qu();mo();tp();te();up();Eo();Po();mr();Ra();yr();Uf();wr();Da();vr=class{static{a(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(e){this.store=e.store,this.parser=e.parser,this.repoRoot=e.repoRoot,this.embedder=e.embedder??null}async indexRepository(e={}){let n=e.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(xn),i=await this.store.countFiles()>0;(e.full||i&&r!==kn)&&await this.wipe();let s=await this.store.getAllFiles(),o;if(e.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=ko(this.repoRoot,{since:e.onlyChangedSince,includeUncommitted:!1});if(w===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");o=w}else o=op(this.repoRoot);let c=new Set(o.map(w=>w.path)),l=new Map(s.map(w=>[w.path,w])),d=s.length>0&&!e.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(Di,"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 k=cp(this.repoRoot,w.path);if(!k){u.filesSkipped++;continue}let x=l.get(w.path);if(x&&x.mtimeMs===k.mtimeMs&&x.size===k.size){u.filesSkipped++;continue}let S=this.readRepoFile(w.path);if(S===null){u.filesSkipped++;continue}let A=yi(S);if(x&&x.contentHash===A){await this.store.upsertFile({...x,mtimeMs:k.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let D=await this.parser.parse(w.path,S,w.language),F=new Map;for(let H of D.nodes)F.set(H.nodeKey,Gf(H));let j={path:w.path,language:w.language,contentHash:A,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await h(),await this.store.replaceFileNodes(j,D.nodes,F,{contains:D.edges,refs:D.refs,imports:D.imports,exports:D.exports}),u.filesParsed++,e.onProgress?.({path:w.path,done:m,total:o.length})}let g=Ku(this.repoRoot),y=await this.store.getMeta(Ia)!==g.fingerprint;if(p||y||await this.store.getMeta(Di)==="1"){let w=Qu(await this.store.getNameIndex()),k=new hn(g.config,w.files),x=ep(await this.store.getAllFacts(),w,k);await this.store.replaceCrossFileEdges(x),await this.store.setMeta(Ia,g.fingerprint),await this.store.setMeta(Di,"0")}if(this.embedder&&e.embed){let w=await this.store.getNodesByKinds([...uo]),k=await this.store.getEmbeddingContentHashes(),x=[];for(let A of w){let D=Hu(A),F=yi(`${this.embedder.recipeVersion}\0${D}`);k.get(A.nodeKey)!==F&&x.push({nodeKey:A.nodeKey,text:D,hash:F})}let S=64;for(let A=0;A<x.length;A+=S){let D=x.slice(A,A+S),F=await this.embedder.embedDocuments(D.map(H=>H.text));await this.store.upsertEmbeddings(D.map((H,$)=>({nodeKey:H.nodeKey,dim:this.embedder.dim,vec:F[$],contentHash:H.hash})));let j=Math.min(A+S,x.length);e.onProgress?.({path:"embedding symbols",done:j,total:x.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Mi,this.embedder.recipeVersion),await this.store.setMeta(Pi,this.embedder.model),await this.store.setMeta(Li,String(this.embedder.dim))}await this.store.setMeta(xn,kn),await this.store.setMeta(Na,String(n));let _=dr(this.repoRoot);return _&&await this.store.setMeta(Sn,_),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(e.now??Date.now())-n,u}async status(){await this.store.init();let e=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(Na);return{indexed:e>0,fileCount:e,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(Sn),schemaVersion:await this.store.getMeta(xn),languages:r}}async searchGraph(e,n={}){await this.store.init();let r=$t(n.limit,20,100),i=await this.store.searchFts(e,n.kind??null,r),s=[];for(let o of i){let c=await this.store.getNode(o.nodeKey);c&&s.push({...zf(c),score:o.score})}return s}async semanticQuery(e,n={}){if(await this.store.init(),!this.embedder)return[];let r=$t(n.limit,20,100),i=await this.embedder.embedQuery(e),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Gu(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({...zf(d),score:l.score})}return c}async tracePath(e,n={}){await this.store.init();let r=n.direction??"out",i=$t(n.maxDepth,3,5),s=$t(n.limit,100,1e3),o=n.kinds??null,c=[],l=new Set,d=new Set([e]),u=[e];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 _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=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(e){await this.store.init();let n=await this.store.getNode(e);if(!n)return null;let r="";try{r=Kf(Vf.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(e={}){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($t(e.topN,10,50))}}async changedSymbols(e={}){await this.store.init();let n=ko(this.repoRoot,e);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=$t(e.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(e={}){let n=e.paths??[];if(n.length===0){let r=gi(this.repoRoot,{since:e.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(dr(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return gp(this.repoRoot,n,e)}async checkDivergence(e={}){return pr(this.repoRoot,e)}async checkNumberCollisions(e={}){return Ct(this.repoRoot,e)}async checkNumberForPath(e,n={}){return Ot(this.repoRoot,e,n)}async checkSpecDrift(e={}){return Dt(this.repoRoot,e)}async reviewDetectors(e={}){return Ea(this.repoRoot,e)}async reviewDetectorScopes(e={}){return Ta(this.repoRoot,e)}async reviewChanges(e={}){await this.store.init();let n=gi(this.repoRoot,e);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=dp(this.repoRoot,e),i=r?.files??new Map,s=r?.coverage??"none",o=jf({paths:n,hunks:i,readUntracked:a(h=>this.readRepoFileHead(h,lp),"readUntracked")}),c=sp(n.keys()),l=$t(e.limit,64,e.attest?ai: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),_=g!==null&&y!==null&&yi(y)!==g.contentHash;_&&(p++,s==="full"&&(s="partial"));let w=n.get(h.path)??"modified",k=i.get(h.path);for(let x of m)d.push(cS(x,w,k,_))}return d.sort((h,m)=>qf(h.change)-qf(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:e.since?"ref":"uncommitted",headSha:dr(this.repoRoot),dirty:xo(this.repoRoot),baseSha:e.since?_i(this.repoRoot,e.since):null,mergeBaseSha:e.since?vo(this.repoRoot,e.since):null}}async close(){await this.store.close()}readRepoFileHead(e,n){let r=this.readRepoFile(e);return r===null?null:r.slice(0,n)}readRepoFile(e){try{return Kf(Vf.join(this.repoRoot,e),"utf8")}catch{return null}}async wipe(){for(let e of await this.store.getAllFiles())await this.store.deleteFile(e.path)}};a(zf,"toHit");a($t,"clampLimit");a(qf,"changeRank");a(cS,"classifyReviewSymbol")});var Yf=b(()=>{"use strict";te()});var lS,XL,Jf=b(()=>{"use strict";te();lS=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],XL=new RegExp(lS.join("|"),"g")});import{existsSync as Pa,readdirSync as dS,readFileSync as uS}from"node:fs";import{spawnSync as pS}from"node:child_process";import{dirname as fS,join as $i,posix as La}from"node:path";function Zf(t){let e=[],n={host:"127.0.0.1",port:t.config.source==="missing"?null:t.config.port,configSource:t.config.source,reachable:null,ledgerCount:null};if(t.config.source==="missing")return e.push({id:`db.config_missing:${t.dir}`,status:"open",project:t.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 ${t.dir}. Die Supabase-CLI w\xFCrde hier still auf ihren Default-Port ${$a} 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:t.dir,verdict:"blind",findings:e,db:n};t.config.source==="main_worktree"&&e.push({id:`db.config_missing_here:${t.dir}`,status:"open",project:t.dir,title:`config.toml fehlt in DIESEM Tree \u2014 Vergleich lief \xFCber den Haupt-Worktree (Port ${t.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 ${$a} 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=t.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:${t.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 ${t.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 e.push({id:`db.${p}:${t.dir}`,status:"warn",project:t.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:t.dir,verdict:"blind",findings:e,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),s=new Set(t.fileVersions),o=t.fileVersions.filter(p=>!i.has(p)).sort(Ue);o.length>0&&e.push({id:`ledger.behind:${t.dir}`,status:"open",project:t.dir,title:`lokales Schema hinter dem Repo \u2014 ${o.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${t.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:(t.projectRoot?`cd ${t.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(Ue),l=new Map,d=[];for(let p of c){let h=t.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)e.push({id:`ledger.sibling_wip:${t.dir}#${p}`,status:"info",project:t.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&&e.push({id:`ledger.phantom:${t.dir}`,status:"warn",project:t.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}),t.remote!==null)if(t.remote.ok===!1)e.push({id:`remote.unreadable:${t.dir}`,status:"warn",project:t.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${t.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(t.remote.versions),h=t.fileVersions.filter(g=>!p.has(g)).sort(Ue),m=t.remote.versions.filter(g=>!s.has(g)).sort(Ue);h.length>0&&e.push({id:`remote.behind:${t.dir}`,status:"warn",project:t.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&&e.push({id:`remote.ahead:${t.dir}`,status:"warn",project:t.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=e.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:t.dir,verdict:u,findings:e,db:n}}function Qf(t){return t.length===0?"no_opinion":t.includes("blind")?"blind":t.includes("drift")?"drift":"in_sync"}function tm(t,e){if(e==="enoent")return{ok:!1,reason:"psql_missing"};let n=t.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:t.split(`
|
|
129
|
+
`).filter(Boolean).slice(-1)[0]}}function Xf(t,e,n){let r=t(e,mS,n);return r.ok===!1?tm(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
130
|
+
`).map(i=>i.trim()).filter(Boolean)}}function nm(t){for(let e of t.split(/^\[/m)){if(!/^db\]/.test(e))continue;let n=/^\s*port\s*=\s*(\d+)/m.exec(e.slice(e.indexOf("]")+1));if(n)return Number(n[1])}return null}function hS(t){let e=R(t,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!e)return null;let n=fS(e);return n===t?null:n}function gS(t,e,n){let r=La.dirname(e),s=[{path:$i(t,r,"config.toml"),source:"worktree"}],o=hS(t);o&&s.push({path:$i(o,r,"config.toml"),source:"main_worktree"});for(let c of s)if(Pa(c.path))try{let l=nm(uS(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 yS(t,e){let n=new Map,r=R(t,["worktree","list","--porcelain"]);if(r===null)return n;let i=R(t,["rev-parse","--show-toplevel"])?.trim();for(let s of r.split(`
|
|
131
|
+
`)){if(!s.startsWith("worktree "))continue;let o=s.slice(9).trim();if(!o||o===i||!Pa(o))continue;let c=$i(o,e);if(Pa(c))try{for(let l of dS(c)){let d=yn(l);d!==null&&!n.has(d)&&n.set(d,o)}}catch{}}return n}function Fa(t,e={}){let n=e.runPsql??em,r=e.timeoutMs??15e3,i=[],s=It(t,e.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:e.remoteDbUrl!==void 0,skipped:i}};let o=[],c=[],l=[];for(let p of s){let h=gS(t,p.dir,i),m=h.source==="missing"?null:Xf(n,`postgresql://postgres:postgres@127.0.0.1:${h.port}/postgres`,r),g=e.remoteDbUrl!==void 0?Xf(n,e.remoteDbUrl,r):null,y=Zf({dir:p.dir,projectRoot:$i(t,La.dirname(La.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:h,ledger:m,siblingVersions:yS(t,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=Qf(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:e.remoteDbUrl!==void 0,skipped:i}}}var $a,em,mS,rm=b(()=>{"use strict";te();ur();$a=54322;a(Zf,"evaluateLedgerProject");a(Qf,"deriveLedgerVerdict");em=a((t,e,n)=>{let r=pS("psql",[t,"-tAc",e],{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"),mS="select version from supabase_migrations.schema_migrations order by version";a(tm,"classifyLedgerError");a(Xf,"readLedger");a(nm,"parseDbPort");a(hS,"mainWorktreeRoot");a(gS,"resolveConfig");a(yS,"gatherSiblingVersions");a(Fa,"checkMigrationLedgerDrift")});var im,En=b(()=>{"use strict";Ml();Ma();Eo();Aa();te();Ai();la();ia();aa();Po();Yf();Jf();No();mr();Ci();yr();ur();Ii();rm();Jo();Ra();mr();yr();Ci();Ii();pi();po();wr();mi();im="0.2.0"});import{execFileSync as _S}from"node:child_process";import{createHash as bS}from"node:crypto";import{mkdirSync as wS,readFileSync as vS,renameSync as kS,writeFileSync as xS}from"node:fs";import{dirname as sm,join as om}from"node:path";function Be(t=process.cwd()){try{let e=_S("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:t}catch{return t}}function Fi(t){return bS("sha256").update(t).digest("hex").slice(0,16)}function ji(t){return om(t,SS)}function am(t){return!!t&&typeof t.instructions=="string"&&t.instructions.trim().length>0}function cm(t,e,n,r=new Date().toISOString()){try{if(!am(n))return;let i={version:ja,cached_at:r,mcp_url:e.mcpUrl,key_fp:e.keyFp,result:n},s=ji(t);wS(sm(s),{recursive:!0}),lr(sm(s));let o=`${s}.${process.pid}.tmp`;xS(o,JSON.stringify(i,null,2),"utf8"),kS(o,s)}catch{}}function lm(t,e){try{let n=vS(ji(t),"utf8"),r=JSON.parse(n);return r.version!==ja||r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.cached_at!="string"||!am(r.result)?null:{version:ja,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function dm(t,e,n=new Date){let r=ES(e.cached_at,n),i=e.result.instructions??"",s={...e.result,instructions:`${r}
|
|
132
|
+
|
|
133
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:t,result:s})}function ES(t,e){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${TS(t,e)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function TS(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"at an unknown time";let r=e.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 ja,SS,Tn=b(()=>{"use strict";En();ja=1,SS=om(".maind","conventions-cache.json");a(Be,"resolveRepoRoot");a(Fi,"keyFingerprint");a(ji,"cachePath");a(am,"hasInstructions");a(cm,"writeConventionsCache");a(lm,"readConventionsCache");a(dm,"buildCachedInitializeResponse");a(ES,"fallbackMarker");a(TS,"relativeAge")});import{existsSync as Bi,mkdirSync as FS,readFileSync as um,writeFileSync as Wa,chmodSync as pm}from"node:fs";import{homedir as jS,hostname as US,platform as Ha,release as HS}from"node:os";import{randomUUID as WS}from"node:crypto";import{join as Ft}from"node:path";function be(){let t=jS(),e=process.env;if(Ha()==="darwin")return Ft(t,"Library","Application Support","maind");if(Ha()==="win32"){let r=e.APPDATA&&e.APPDATA.length>0?e.APPDATA:Ft(t,"AppData","Roaming");return Ft(r,"maind")}let n=e.XDG_CONFIG_HOME&&e.XDG_CONFIG_HOME.length>0?e.XDG_CONFIG_HOME:Ft(t,".config");return Ft(n,"maind")}function fm(t){Bi(t)||FS(t,{recursive:!0,mode:448})}function ne(){let t=be();fm(t);let e=Ft(t,GS);if(Bi(e)){let r=um(e,"utf8").trim();if(VS(r))return r}let n=WS();Wa(e,n+`
|
|
134
|
+
`,{encoding:"utf8",mode:384});try{pm(e,384)}catch{}return n}function VS(t){return KS.test(t)}function Ga(){return Ft(be(),BS)}function jt(t){let e=be();fm(e);let n=Ga();Wa(n,t+`
|
|
135
|
+
`,{encoding:"utf8",mode:384});try{pm(n,384)}catch{}}function K(){let t=Ga();if(!Bi(t))return null;let e=um(t,"utf8").trim();return e.length>0?e:null}function xr(){let t=Ga();Bi(t)&&Wa(t,"",{encoding:"utf8",mode:384})}function mm(){try{return`mcp-bridge-${US()}`}catch{return"mcp-bridge"}}function Ki(t){return{os:`${Ha()} ${HS()}`,ide:"mcp-bridge",ext_version:t,device_id:ne()}}var GS,BS,KS,re=b(()=>{"use strict";a(be,"configDir");a(fm,"ensureDir");GS="device-id",BS="api-key";a(ne,"ensureDeviceId");KS=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;a(VS,"isUuid");a(Ga,"apiKeyPath");a(jt,"writeApiKey");a(K,"readApiKey");a(xr,"clearApiKey");a(mm,"bridgeLabel");a(Ki,"clientMeta")});function Sr(){let t=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return t.length>0?t:zS}function Rn(t){return`${Sr()}/${t.replace(/^\/+/,"")}`}var zS,An=b(()=>{"use strict";zS="https://fn.maind.dev/functions/v1";a(Sr,"functionsOrigin");a(Rn,"functionsUrl")});import{mkdirSync as eE,readFileSync as tE,renameSync as nE,writeFileSync as rE}from"node:fs";import{join as iE}from"node:path";function gm(t=be()){return iE(t,oE)}function cE(t){return t.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,aE)}function Ut(t,e,n){try{let r=n.dir??be();eE(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:t,detail:e===null?null:cE(e),bridge_version:n.version},s=gm(r),o=`${s}.${process.pid}.tmp`;rE(o,JSON.stringify(i)+`
|
|
136
|
+
`,{encoding:"utf8",mode:384}),nE(o,s)}catch{}}function ym(t=be()){try{let e=JSON.parse(tE(gm(t),"utf8"));return e.v!==1||typeof e.at!="string"||!sE.includes(e.outcome)?null:{v:1,at:e.at,outcome:e.outcome,detail:typeof e.detail=="string"?e.detail:null,bridge_version:typeof e.bridge_version=="string"?e.bridge_version:"?"}}catch{return null}}var sE,oE,aE,Ba=b(()=>{"use strict";re();sE=["ok","paired","auth_failed","not_paired"],oE="connection-state.json",aE=200;a(gm,"connectionStatePath");a(cE,"redactDetail");a(Ut,"writeConnectionState");a(ym,"readConnectionState")});var U,st=b(()=>{"use strict";U="0.76.0"});import{execFileSync as lE}from"node:child_process";import{createHash as dE}from"node:crypto";function uE(t){return dE("sha256").update(t).digest("hex")}function pE(t){let e=t.trim();if(!e)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(e);if(n)e=e.slice(n[0].length),e=e.replace(/^[^@/]+@/,""),e=e.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{e=e.replace(/^[^@/]+@/,"");let r=e.indexOf(":");r>=0&&(e=`${e.slice(0,r)}/${e.slice(r+1)}`)}return e=e.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),e.length>0?e:null}function Ka(t){let e=pE(t);return e?uE(e):null}function z(){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(t&&fE.test(t))return t;let e;try{e=lE("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return e?Ka(e):null}var fE,ot=b(()=>{"use strict";a(uE,"sha256Hex");a(pE,"normalizeRemoteUrl");a(Ka,"projectKeyFromRemote");fE=/^[a-f0-9]{64}$/;a(z,"computeProjectKey")});import hE from"node:path";import{fileURLToPath as gE}from"node:url";function yE(t,e=hE.sep){return t.split(e).includes("_npx")}function Ie(t){let e=t.extraArgs??[],n=a(r=>({command:"npx",args:["-y",Rm,...e],env:{},fallbackReason:r}),"npx");return t.entryPath===null?n("bridge entry path could not be resolved"):yE(t.entryPath,t.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):t.nodePath?{command:t.nodePath,args:[t.entryPath,...e],env:t.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function Ce(){try{let t=gE(import.meta.url);return t.endsWith(".js")?t:null}catch{return null}}function In(t){let e=Object.entries(t.env).map(([n,r])=>`${n}=${Tm(r)}`);return[...e,t.command,...t.args].map((n,r)=>r<e.length?n:Tm(n)).join(" ")}function zi(t){return/(^|\s)npx(\s|$)/.test(t)&&t.includes(Rm)}function qi(t){return/(^|[\s/])maind-hook(\s|$)/.test(t)?!0:/claude-code-hook[/\\]build[/\\]/.test(t)}function Tm(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var Rm,Cn=b(()=>{"use strict";Rm="@maind-dev/mcp-bridge";a(yE,"isEphemeralEntry");a(Ie,"resolveBridgeLaunch");a(Ce,"currentBridgeEntry");a(In,"launchToShellCommand");a(zi,"isNpxForm");a(qi,"isLegacyHookForm");a(Tm,"shellQuote")});import*as we from"node:path";function Nm(t){let e=t.launch??Ie({entryPath:Ce(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:e.command,args:e.args,env:{...e.env,MAIND_CLIENT_FAMILY:t.clientFamily,MAIND_MCP_URL:t.mcpUrl}}}function _E(t){switch(t.platform){case"darwin":return we.join(t.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let e=t.appData??we.join(t.homeDir,"AppData","Roaming");return we.join(e,"Claude","claude_desktop_config.json")}default:{let e=t.xdgConfigHome??we.join(t.homeDir,".config");return we.join(e,"Claude","claude_desktop_config.json")}}}function Yi(t){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:we.join(t.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:we.join(t.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:_E(t),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:we.join(t.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:we.join(t.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:we.join(t.homeDir,".codex","config.toml"),kind:"toml"}]}function Im(t,e){return e===null?t:t.filter(n=>n.clientFamilyEnv===e)}function Ji(t){return{projectRoot:t.projectRoot,homeDir:t.homeDir,platform:t.platform,xdgConfigHome:Am(t.env.XDG_CONFIG_HOME),appData:Am(t.env.APPDATA)}}function Am(t){if(t===void 0)return null;let e=t.trim();return e.length>0?e:null}var Va=b(()=>{"use strict";Cn();a(Nm,"buildMaindServerEntry");a(_E,"claudeDesktopConfigPath");a(Yi,"getClientTargets");a(Im,"filterTargetsByFamily");a(Ji,"makeDefaultContext");a(Am,"nonEmpty")});import*as q from"node:fs/promises";import*as Xi from"node:path";async function ie(t){try{return await q.readFile(t,"utf8")}catch(e){if(bE(e))return null;throw e}}async function za(t){await q.mkdir(t,{recursive:!0})}async function Y(t,e,n){let r=Xi.dirname(t);await za(r);let i=Xi.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await q.writeFile(i,e,{encoding:"utf8",mode:n});try{await q.rename(i,t)}catch(s){if(wE(s))try{await q.copyFile(i,t),await q.unlink(i).catch(()=>{}),n!==void 0&&await q.chmod(t,n).catch(()=>{});return}catch(o){throw await q.unlink(i).catch(()=>{}),o}throw await q.unlink(i).catch(()=>{}),s}}async function Cm(t,e){let n=await ie(t);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(e))}function bE(t){return Om(t)&&t.code==="ENOENT"}function wE(t){return!Om(t)||process.platform!=="win32"?!1:t.code==="EEXIST"||t.code==="EPERM"||t.code==="EACCES"}function Om(t){return typeof t=="object"&&t!==null&&"code"in t}var Ke=b(()=>{"use strict";a(ie,"readFileSafe");a(za,"ensureDir");a(Y,"atomicWriteFile");a(Cm,"hasLinePrefix");a(bE,"isNoEnt");a(wE,"isWindowsRenameFailure");a(Om,"isNodeError")});import{existsSync as $E}from"node:fs";import*as Fm from"node:path";function Wt(t,e={},n=Xa){let r=e.fileExists??$E,i=e.expectedCommand??FE,s={};if(t!==null&&t.trim().length>0)try{let o=JSON.parse(t);Ja(o)&&(s=o)}catch{}return n.map(o=>{let c={event:o.event,subcommand:o.subcommand},l=jE(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(qi(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(zi(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=UE(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 Za(t){return t.some(e=>e.status!=="ok")}function es(t){return t.some(e=>e.remedy==="run-install")}function FE(t){return In(Ie({entryPath:Ce(),nodePath:process.execPath,extraArgs:[t],isElectron:process.versions.electron!==void 0}))}function jE(t,e,n){let r=t.hooks?.[e];if(!Array.isArray(r))return null;for(let i of r){if(!Ja(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!Ja(o))continue;let c=o.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function UE(t){for(let e of HE(t))if(e.endsWith(".js")||e.endsWith(".mjs")||e.endsWith(".cjs"))return Fm.isAbsolute(e)?e:null;return null}function HE(t){let e=[],n="",r=!1;for(let i of t){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&e.push(n),n="";continue}n+=i}return n.length>0&&e.push(n),e}function Ja(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Xa,Qi,On=b(()=>{"use strict";Cn();Xa=[{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."}],Qi=[{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. 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."}];a(Wt,"inspectHookWiring");a(Za,"hasWiringDrift");a(es,"needsInstallRun");a(FE,"defaultExpectedCommand");a(jE,"findCommand");a(UE,"extractScriptPath");a(HE,"tokenize");a(Ja,"isObject")});import*as tc from"node:path";import*as Um from"node:readline";async function Hm(t,e){let n=tc.join(t.homeDir,".claude","settings.json"),r=e.targetKey;if(t.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await ie(n)}catch(h){return{target:r,action:"merge",status:"failed",detail:`read: ${Qa(h)}`}}let s,o="create";if(i===null||i.trim().length===0)s={};else{o="merge";try{let h=JSON.parse(i);if(!ec(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: ${Qa(h)}`}}}let c=GE(s,e.event,e.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:e.skipDetail(c)};if(!t.full){if(!t.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(t.dryRun)return{target:r,action:"merge",status:o==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await BE(t.out,`
|
|
137
|
+
Merge a ${e.event} hook into ${n}?
|
|
138
|
+
${e.consentDescription}
|
|
139
|
+
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...e.matcher===void 0?{}:{matcher:e.matcher},hooks:[{type:"command",command:e.command,timeout:e.timeout}]},d=s.hooks?.[e.event]??[],u={...s,hooks:{...s.hooks??{},[e.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
140
|
+
`;if(t.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: ${Qa(h)}`}}return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:n}}async function Wm(t){let e=tc.join(t.homeDir,jm);return Hm(t,{event:"SessionStart",command:`cat ${e}`,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 ${jm} into every new Claude Code session.`})}function WE(t){return`hook(${t.subcommand}):~/.claude/settings.json`}async function nc(t,e){let n=t.launch??Ie({entryPath:Ce(),nodePath:process.execPath,extraArgs:[e.subcommand],isElectron:process.versions.electron!==void 0}),r=In(n);return Hm(t,{event:e.event,command:r,timeout:e.timeout,matcher:e.matcher,matchPattern:new RegExp(e.subcommand),targetKey:WE(e),skipDetail:a(i=>{let s=`${e.label} already runs maind ${e.subcommand}`;return qi(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}`:zi(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:e.consentDescription})}async function Gm(t){let e=[];for(let n of Xa)e.push(await nc(t,n));return e}function GE(t,e,n){let r=t.hooks?.[e];if(!Array.isArray(r))return null;for(let i of r){if(!ec(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!ec(o))continue;let c=o.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function BE(t,e){t.write(e);let n=Um.createInterface({input:process.stdin,output:t,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function ec(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qa(t){return t instanceof Error?t.message:String(t)}var jm,rc=b(()=>{"use strict";Ke();Cn();On();jm=".claude/maind-session-start-reminder.md";a(Hm,"mergeClaudeHook");a(Wm,"mergeSessionStartHook");a(WE,"targetKeyFor");a(nc,"mergeSubcommandHook");a(Gm,"mergeAllSubcommandHooks");a(GE,"findExistingHookCommand");a(BE,"promptYesNo");a(ec,"isObject");a(Qa,"errMessage")});import{existsSync as KE,readFileSync as VE}from"node:fs";import{join as zE}from"node:path";function ze(){return zE(be(),"config.json")}function Oe(){try{let t=ze();if(!KE(t))return null;let e=JSON.parse(VE(t,"utf8"));if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,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),(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 Dn=b(()=>{"use strict";re();a(ze,"bridgeConfigPath");a(Oe,"readBridgeConfig")});function ts(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function dt(t){return t+1}function ns(t){return(t.text.split(`
|
|
141
|
+
`,1)[0]??"").trim().slice(0,200)}function t0(t){if(!t)return null;switch(t.type){case"identifier":case"property_identifier":case"type_identifier":return t.text;case"member_expression":return t.childForFieldName("property")?.text??null;case"attribute":return t.childForFieldName("attribute")?.text??null;default:return null}}function n0(t,e){let n=new Set;for(let r of t.descendantsOfType(e)){let i=t0(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function ic(t,e,n,r){for(let i of n0(n,r))t.refs.push({fromKey:e,kind:"calls",targetName:i})}function Ar(t){if(!t)return null;switch(t.type){case"identifier":case"type_identifier":return{name:t.text,receiver:null};case"member_expression":{let e=t.childForFieldName("property")?.text;if(!e)return null;let n=t.childForFieldName("object");if(n?.type==="this")return{name:e,receiver:"this"};if(n?.type==="identifier")return{name:e,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:e,receiver:`this.${r}`};let i=n;for(;i?.type==="member_expression";)i=i.childForFieldName("object");return i?.type==="this"?{name:e,receiver:"this.*"}:i?.type==="identifier"?{name:e,receiver:`${i.text}.*`}:{name:e,receiver:"?"}}case"nested_identifier":{let e=t.text.split(".");return{name:e[e.length-1],receiver:e.length===2?e[0]:"?"}}default:return null}}function lt(t){if(!t)return null;let e=t.type==="type_annotation"?t.namedChildren[0]??null:t;if(!e)return null;switch(e.type){case"type_identifier":return e.text;case"nested_type_identifier":return e.text.replace(/\s+/g,"");case"generic_type":return lt(e.childForFieldName("name"));case"parenthesized_type":return lt(e.namedChildren[0]??null);case"union_type":{let n=e.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?lt(n[0]):"#"}default:return"#"}}function i0(t){let e=t?.type==="await_expression"?t.namedChildren[0]??null:t;return e?.type==="call_expression"&&e.childForFieldName("function")?.type==="member_expression"}function sc(t){if(t?.type!=="new_expression")return null;let e=t.childForFieldName("constructor");return e?.type==="identifier"||e?.type==="member_expression"?e.text:null}function Nr(t){let e=new Map;for(let n of t.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),s=lt(n.childForFieldName("type"))??sc(i)??(i0(i)?"#":null);s&&e.set(r.text,s)}for(let n of t.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=lt(n.childForFieldName("type"));i&&e.set(r.text,i)}return e}function ut(t,e,n,r,i={locals:Nr(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;t.refs.push({fromKey:e,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...r0]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")o(Ar(l.childForFieldName("function")));else if(l.type==="new_expression")o(Ar(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;o(Ar(d))}}var r0,rs=b(()=>{"use strict";a(ts,"newResult");a(dt,"line1");a(ns,"signatureOf");a(t0,"calleeName");a(n0,"collectCallTargets");a(ic,"addCallRefs");a(Ar,"calleeRef");r0=["jsx_opening_element","jsx_self_closing_element"];a(lt,"typeNameOf");a(i0,"isMethodCallResult");a(sc,"newTypeOf");a(Nr,"collectTypeHints");a(ut,"addTsRefs")});function Zm(t,e){let n=ts();for(let r of t.namedChildren)s0(r,e,n);return n}function Qm(t){return t.type==="decorated_definition"?t.childForFieldName("definition")??t:t}function s0(t,e,n){let r=Qm(t);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??a0(r);s&&n.imports.push({fromModuleKey:e.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=is(r,e,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:e.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=r.childForFieldName("body");o&&ic(n,s.nodeKey,o,Xm);return}case"class_definition":o0(r,e,n);return;case"expression_statement":{let s=r.namedChildren.find(o=>o.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let o=is(r,e,s.text,s.text,"variable");n.nodes.push(o),n.edges.push({srcKey:e.moduleKey,dstKey:o.nodeKey,kind:"contains"})}return}default:return}}function o0(t,e,n){let r=t.childForFieldName("name")?.text;if(!r)return;let i=is(t,e,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:e.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=t.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=t.childForFieldName("body");if(o)for(let c of o.namedChildren){let l=Qm(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=is(l,e,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&ic(n,p.nodeKey,h,Xm)}}function is(t,e,n,r,i){return{nodeKey:Te(e.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:e.filePath,language:e.language,startLine:dt(t.startPosition.row),endLine:dt(t.endPosition.row),startByte:t.startIndex,endByte:t.endIndex,signature:ns(t),doc:null}}function a0(t){return t.descendantsOfType("dotted_name")[0]?.text??null}var Xm,eh=b(()=>{"use strict";gn();rs();Xm="call";a(Zm,"extractPython");a(Qm,"unwrapDecorated");a(s0,"handleTopLevel");a(o0,"addClass");a(is,"makeNode");a(a0,"firstDottedName")});function nh(t,e){let n=ts(),r=e.language!=="typescript";for(let i of t.namedChildren)l0(i,e,n,r);return p0(t,e,n),n}function c0(t){return t.type==="export_statement"?t.childForFieldName("declaration")??t:t}function l0(t,e,n,r){if(t.type==="export_statement"&&d0(t,e,n,r))return;let i=c0(t),s=t.type==="export_statement"&&/^export\s+default\b/.test(t.text);switch(i.type){case"import_statement":u0(i,e,n);return;case"function_declaration":case"generator_function_declaration":{let o=th(i,e,n,"function",r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"class_declaration":case"abstract_class_declaration":{let o=m0(i,e,n,r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"interface_declaration":oc(i,e,n,"interface");return;case"type_alias_declaration":oc(i,e,n,"type_alias");return;case"enum_declaration":oc(i,e,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&&ut(n,e.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";th(o,e,n,d?"function":"variable",r,c,l)}return}default:ut(n,e.moduleKey,i,r);return}}function d0(t,e,n,r){if(t.childForFieldName("declaration"))return!1;let i=cc(t.childForFieldName("source")),s=t.namedChildren.find(l=>l.type==="export_clause"),o=t.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:e.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=t.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):ut(n,e.moduleKey,c,r),!0):!1}function u0(t,e,n){let r=cc(t.childForFieldName("source"));if(r===null)return;let i=t.namedChildren.find(c=>c.type==="import_clause"),s=[],o=a((c,l)=>{s.push({fromModuleKey:e.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:e.moduleKey,specifier:r}):n.imports.push(...s)}function p0(t,e,n){for(let r of t.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,s=i?.type==="string"?cc(i):null;if(s===null)continue;let c=f0(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:e.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:e.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:e.moduleKey,specifier:s,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:e.moduleKey,specifier:s})}}function f0(t){let e=t.parent??null,n=e?.type==="await_expression"?e.parent??null:e;return n?.type==="variable_declarator"?n:null}function th(t,e,n,r,i,s,o){let l=(s??t.childForFieldName("name"))?.text;if(!l)return null;let d=ss(t,e,l,l,r);if(n.nodes.push(d),n.edges.push({srcKey:e.moduleKey,dstKey:d.nodeKey,kind:"contains"}),r==="function"){let u=o??t.childForFieldName("body")??t;ut(n,d.nodeKey,u,i,{locals:Nr(t)})}else o&&ut(n,d.nodeKey,o,i);return d}function oc(t,e,n,r){let i=t.childForFieldName("name")?.text;if(!i)return;let s=ss(t,e,i,i,r);n.nodes.push(s),n.edges.push({srcKey:e.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function m0(t,e,n,r){let i=t.childForFieldName("name")?.text;if(!i)return null;let s=ss(t,e,i,i,"class");n.nodes.push(s),n.edges.push({srcKey:e.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=t.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:ac(p)})):[{kind:"extends",ref:ac(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=t.childForFieldName("body");if(!c)return s;let l=h0(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&ut(n,s.nodeKey,g,r,{locals:Nr(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,h=ss(d,e,u,p,"method");n.nodes.push(h),n.edges.push({srcKey:s.nodeKey,dstKey:h.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&ut(n,h.nodeKey,m,r,{locals:Nr(d),thisFields:l})}return s}function h0(t){let e=new Map;for(let n of t.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),i=lt(n.childForFieldName("type"))??sc(n.childForFieldName("value"));r&&i&&e.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=lt(r.childForFieldName("type"));i?.type==="identifier"&&s&&e.set(i.text,s)}return e}function ss(t,e,n,r,i){return{nodeKey:Te(e.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:e.filePath,language:e.language,startLine:dt(t.startPosition.row),endLine:dt(t.endPosition.row),startByte:t.startIndex,endByte:t.endIndex,signature:ns(t),doc:null}}function ac(t){if(!t)return null;switch(t.type){case"generic_type":return ac(t.childForFieldName("name"));case"nested_type_identifier":{let e=t.childForFieldName("name")?.text,n=t.childForFieldName("module");return e?{name:e,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return Ar(t);default:return null}}function cc(t){return!t||t.type!=="string"?null:t.text.replace(/^["'`]|["'`]$/g,"")}var rh=b(()=>{"use strict";gn();rs();a(nh,"extractTypescript");a(c0,"unwrapExport");a(l0,"handleTopLevel");a(d0,"handleExportForm");a(u0,"addImport");a(p0,"collectDynamicImports");a(f0,"enclosingDeclarator");a(th,"addFunctionLike");a(oc,"addSimpleNamed");a(m0,"addClass");a(h0,"classFieldTypes");a(ss,"makeNode");a(ac,"heritageRef");a(cc,"stringValue")});import{createRequire as g0}from"node:module";import{join as y0}from"node:path";function oh(t,e){return e?y0(e,ih[t]):g0(import.meta.url).resolve(`tree-sitter-wasms/out/${ih[t]}`)}var ih,sh,ah=b(()=>{"use strict";ih={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},sh="tree-sitter.wasm";a(oh,"grammarPath")});import{join as _0}from"node:path";import lc from"web-tree-sitter";var b0,os,ch=b(()=>{"use strict";gn();pi();eh();rh();rs();ah();b0=["typescript","tsx","javascript","python"],os=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(e={}){this.assetDir=e.assetDir}async init(){this.initialized||(await lc.init(this.assetDir?{locateFile:a(e=>_0(this.assetDir,e||sh),"locateFile")}:void 0),this.parser=new lc,this.initialized=!0)}supports(e){return b0.includes(e)}async parse(e,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:e,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let o=s.rootNode,c=tt(e),l={nodeKey:c,kind:"module",name:e.split("/").pop()??e,qualifiedName:"<module>",filePath:e,language:r,startLine:1,endLine:dt(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:e,language:r,source:n,moduleKey:c},u=r==="python"?Zm(o,d):nh(o,d);return s.delete(),{filePath:e,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(e){let n=this.grammars.get(e);return n||(n=await lc.Language.load(oh(e,this.assetDir)),this.grammars.set(e,n)),n}}});import{createRequire as w0}from"node:module";function dh(){return lh("node:sqlite")}function Mn(){if(Ir)return Ir;try{let{DatabaseSync:t}=dh(),e=new t(":memory:");try{e.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),e.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),e.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Ir={ok:!0}}finally{e.close()}}catch(t){Ir={ok:!1,reason:t instanceof Error?t.message:String(t)}}return Ir}function v0(t){let{DatabaseSync:e}=dh(),n=new e(t);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 k0(t){let e=lh("better-sqlite3"),n=new e(t);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 x0(){let t=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return t==="builtin"||t==="better"?t:null}function as(t){let e=x0(),n=a(i=>{let s=i==="node:sqlite"?v0(t):k0(t);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(e==="builtin"){let i=Mn();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(e==="better")return n("better-sqlite3");let r=Mn();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 lh,Ir,dc=b(()=>{"use strict";lh=w0(import.meta.url);a(dh,"loadBuiltin");Ir=null;a(Mn,"probeBuiltinSqlite");a(v0,"openBuiltin");a(k0,"openBetter");a(x0,"backendOverride");a(as,"openSqliteDatabase")});function _h(t,e){return{refs:e.refs.map(n=>[t,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:e.imports.map(n=>[t,n.specifier,n.importedName??null,n.localName??null]),exports:e.exports.map(n=>[t,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function bh(t,e,n,r){let i=new Map;for(let o of t)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 e)s(o)?.refs.push({fromKey:String(o.src_key),kind:String(o.kind),targetName:String(o.target_name),receiver:Bt(o.receiver),receiverType:Bt(o.receiver_type)});for(let o of n){let c=s(o);if(!c)continue;let l={fromModuleKey:tt(c.filePath),specifier:String(o.specifier),importedName:Bt(o.imported_name),localName:Bt(o.local_name)};c.imports.push(l)}for(let o of r){let c={exportedName:String(o.exported_name),localName:Bt(o.local_name),specifier:Bt(o.specifier),importedName:Bt(o.imported_name)};s(o)?.exports.push(c)}return[...i.values()]}var uh,ph,fh,mh,hh,gh,yh,Bt,wh=b(()=>{"use strict";gn();uh=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],ph="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",fh="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",mh="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",hh="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",gh="SELECT file_path, specifier, imported_name, local_name FROM file_imports",yh="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";a(_h,"factRows");Bt=a(t=>t==null?null:String(t),"str");a(bh,"assembleFacts")});function cs(t){return{nodeKey:t.node_key,kind:t.kind,name:t.name,qualifiedName:t.qualified_name,filePath:t.file_path,language:t.language,startLine:t.start_line,endLine:t.end_line,startByte:t.start_byte,endByte:t.end_byte,signature:t.signature,doc:t.doc}}var vh,Cr,kh=b(()=>{"use strict";dc();wr();wh();Da();a(cs,"toNodeRow");vh=400,Cr=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(e){let n=as(e);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Hf)}async close(){this.db.close()}async getMeta(e){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}async setMeta(e,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,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(e){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(e);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(e){this.upsertFileStmt().run(e.path,e.language,e.contentHash,e.mtimeMs,e.size,e.indexedAt)}async replaceFileNodes(e,n,r,i){this.db.transaction(()=>{this.deleteFileGraph(e.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=_h(e.path,i),u=this.db.prepare(ph);for(let m of d.refs)u.run(...m);let p=this.db.prepare(fh);for(let m of d.imports)p.run(...m);let h=this.db.prepare(mh);for(let m of d.exports)h.run(...m)}this.upsertFileStmt().run(e.path,e.language,e.contentHash,e.mtimeMs,e.size,e.indexedAt)})()}async deleteFile(e){this.db.transaction(()=>{this.deleteFileGraph(e),this.db.prepare("DELETE FROM files WHERE path = ?").run(e)})()}async getAllFacts(){let e=this.db.prepare("SELECT path, language FROM files").all();return bh(e,this.db.prepare(hh).all(),this.db.prepare(gh).all(),this.db.prepare(yh).all())}async replaceCrossFileEdges(e){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 e)r.run(i.srcKey,i.dstKey,i.kind)})()}async replaceOutgoingEdges(e,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let o of e)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(e){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(e);return n?cs(n):null}async getNodesByFile(e){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(e).map(cs)}async getNodesByKinds(e){return e.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${e.map(()=>"?").join(",")})`).all(...e).map(cs)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(cs)}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(e){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of e){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 e=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(e.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 e=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(e.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(e,n,r){let i=Bf(e);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
110
142
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
111
143
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
112
144
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
113
145
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
114
146
|
WHERE nodes_fts MATCH ?
|
|
115
|
-
ORDER BY score LIMIT ?`,
|
|
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(e,n,r,i){let o=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[e];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(e){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
|
|
116
148
|
(SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
|
|
117
149
|
(SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
|
|
118
150
|
(SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
|
|
119
151
|
FROM nodes n
|
|
120
152
|
WHERE n.kind = 'module'
|
|
121
153
|
ORDER BY imports_in DESC, symbol_count DESC
|
|
122
|
-
LIMIT ?`).all(
|
|
154
|
+
LIMIT ?`).all(e).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(e){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(e).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+=vh)for(let o of n.slice(s,s+vh))r.run(o),i.run(o);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(e);for(let s of uh)this.db.prepare(s).run(e)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
123
155
|
node_key, kind, name, qualified_name, file_path, language,
|
|
124
156
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
125
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)
|
|
@@ -129,144 +161,144 @@ ${t.consentDescription}
|
|
|
129
161
|
content_hash = excluded.content_hash,
|
|
130
162
|
mtime_ms = excluded.mtime_ms,
|
|
131
163
|
size = excluded.size,
|
|
132
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as AE}from"node:crypto";function Tn(e){return AE("sha256").update(e,"utf8").digest("hex")}function Wm(e){return{node_key_hash:Tn(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Tn(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Tn(e.signature):null}}function Bm(e){return{src_key_hash:Tn(e.srcKey),dst_key_hash:Tn(e.dstKey),kind:e.kind}}function Km(e,t,n){return{node_key_hash:Tn(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Vm=b(()=>{"use strict";o(Tn,"sha256");o(Wm,"toCloudNode");o(Bm,"toCloudEdge");o(Km,"toCloudEmbedding")});function qa(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function zm(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function RE(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Rn,In,TE,Ya=b(()=>{"use strict";ur();Vm();Rn=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},In=class{static{o(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(hn),lastSyncedAt:zm(await this.store.getMeta(_a))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Wm),n=(await this.store.getAllEdges()).map(Bm),r=await this.store.getMeta(mn)??fn,i=await this.store.getMeta(hn),s=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(y=>[y.language,y.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:a},l=0,u=qa(t,this.chunk),d=qa(n,this.chunk*2),p=Math.max(1,u.length+d.length);for(let y of u)await this.post("/api/codebase/push",{...c,nodes:y,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let y of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:y}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let h=t.map(y=>y.node_key_hash),m=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:h});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let g=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(_a,String(Date.now())),i&&await this.store.setMeta(yf,i),{nodes:t.length,edges:n.length,pruned:RE(m.nodes_deleted),embeddings:g,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>Km(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&s[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let c=qa(a,TE),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(xi),n=await this.store.getMeta(Ei),r=zm(await this.store.getMeta(Ai));if(!t||!n||!r)throw new Rn("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 Rn(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},TE=250;o(qa,"chunkArray");o(zm,"numOrNull");o(RE,"numOr0")});var qm={};oe(qm,{CodeIndexSync:()=>In,DEFAULT_DB_RELPATH:()=>Ja,SyncError:()=>Rn,createCodeIndexSync:()=>CE,createNodeCodeIndex:()=>Xa,openSqliteDatabase:()=>Xi,probeBuiltinSqlite:()=>An});import{mkdirSync as IE}from"node:fs";import{posix as Qi}from"node:path";function Xa(e){let t=e.dbPath??Qi.join(e.repoRoot,Ja);IE(Qi.dirname(t),{recursive:!0}),e.dbPath===void 0&&er(Qi.dirname(t));let n=new wr(t),r=new Ji;return new pr({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function CE(e){let t=e.dbPath??Qi.join(e.repoRoot,Ja),n=e.projectKey??pp(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 wr(t);return new In(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var Ja,Za=b(()=>{"use strict";Oo();Fm();va();Gm();Ya();si();Ya();za();Ja=".maind/code-index.sqlite";o(Xa,"createNodeCodeIndex");o(CE,"createCodeIndexSync")});import{execFileSync as Ym}from"node:child_process";import{existsSync as Jm,realpathSync as Xm}from"node:fs";import{createRequire as NE}from"node:module";import{basename as OE,dirname as DE,isAbsolute as Zm,join as PE,relative as Qm,resolve as es,sep as eh}from"node:path";function th(){let e=An();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return NE(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 nh(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=Ym("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 ih(e,t=fe(),n=process.cwd()){let r=Zm(e)?[e]:[es(t,e),es(n,e)];for(let i of r){let s=DE(i);if(!Jm(s))continue;let a;try{a=Xm(s)}catch{continue}let c=sh(a);if(c===null)continue;let l=Qm(c,PE(a,OE(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(eh).join("/")}}return null}function ts(e,t=fe(),n=process.cwd()){let r=Zm(e)?[e]:[es(t,e),es(n,e)];for(let i of r){if(!Jm(i))continue;let s;try{s=Xm(i)}catch{continue}let a=sh(s);if(a===null)continue;let c=Qm(a,s);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(eh).join("/")}}return null}function sh(e){try{let t=Ym("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 oh(){return Xa({repoRoot:fe()})}var rh,vr=b(()=>{"use strict";Za();o(th,"probeNativeStore");o(nh,"isNativeStoreUnavailable");rh="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";o(fe,"resolveRepoRoot");o(ih,"resolveRepoRootForPath");o(ts,"resolveRepoRootForDir");o(sh,"gitToplevelOf");o(oh,"defaultEngineFactory")});import{execFile as bh}from"node:child_process";import{randomUUID as KE}from"node:crypto";function XE(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return ec.test(t)?t:KE()}function tc(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function ZE(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 QE(e){return await new Promise(t=>{bh("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(e0(r))})})}function e0(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 t0(){return await new Promise(e=>{bh("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 n0(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function r0(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=ec.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(s=>{ec.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var _h,wh,VE,zE,qE,YE,JE,ec,os,nc=b(()=>{"use strict";xn();_h=45e3,wh=3e4,VE=5,zE=120,qE=3e4,YE=15*6e4,JE=1500,ec=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(XE,"resolveClientSessionId");o(tc,"autoAnnounceDisabled");o(ZE,"autoWorkingPathsEnabled");os=class{static{o(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??Ie)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??t0,this.gitBranchObject=t.gitBranchObject??QE,this.log=t.log??(i=>process.stderr.write(i+`
|
|
133
|
-
`)),this.machineLabel=
|
|
134
|
-
`,{mode:384}),
|
|
135
|
-
`)}function Z0(e,t){let n=o(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)a.has(l)&&c++;return c/s.size>=.8}function Q0(e,t,n){return B0.test(e)?{polarity:-1,magnitude:Pn.rework,kind:"rework"}:n&&K0.test(e)?{polarity:-1,magnitude:Pn.correction,kind:"correction"}:V0.test(e)?{polarity:1,magnitude:Pn.acceptance,kind:"acceptance"}:t!==null&&Z0(t,e)?{polarity:-1,magnitude:Pn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function eA(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:Wh,behaviour_measured:!0}}async function tA(e,t){for(let n of us(e))await new Promise(r=>{let i=Gh({input:Hh(n,{encoding:"utf-8"})});i.on("line",s=>{let a=s.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of fs(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(ms))continue;let u=l.name.slice(ms.length);u&&(t.maind_tool_calls??={},t.maind_tool_calls[u]=(t.maind_tool_calls[u]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function lc(e,t={}){let n=eA("");if(!e||!W0(e))return n;let r=t.turns??(await Er(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,a=null,c=!1,l=null;await new Promise(m=>{let g=Hh(e,{encoding:"utf-8"}),y=Gh({input:g}),_=o(w=>{let k=w.trim();if(!k)return;let x;try{x=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let W=x.sessionId??x.session_id;typeof W=="string"&&W&&(n.session_id=W)}x.type==="ai-title"&&typeof x.aiTitle=="string"&&x.aiTitle&&(n.ai_title=x.aiTitle),typeof x.slug=="string"&&x.slug&&(n.session_slug=x.slug);let S=x.message?.role,I=x.isSidechain===!0;if(S==="assistant")for(let W of fs(x.message?.content)){if(W.type!=="tool_use"||typeof W.name!="string"||!W.name.startsWith(ms))continue;let qt=W.name.slice(ms.length);qt&&(n.maind_tool_calls??={},n.maind_tool_calls[qt]=(n.maind_tool_calls[qt]??0)+1)}if(I)return;if(S==="assistant"){let W=fs(x.message?.content),qt=!1;for(let cl of W)cl.type==="tool_use"&&(n.tool_calls++,qt=!0,cl.name==="AskUserQuestion"&&n.agent_questions++);c=qt;return}if(S!=="user")return;let $=fs(x.message?.content),H=X0($);if(H.includes(z0)){n.interrupts++,i.push({polarity:-1,magnitude:Pn.interrupt,kind:"interrupt"});return}if($.some(W=>W.type==="tool_result"&&W.is_error===!0&&typeof W.content=="string"&&W.content.includes(q0))){n.tool_denials++,i.push({polarity:-1,magnitude:Pn.denial,kind:"denial"});return}if($.some(W=>W.type==="tool_result")||!H.trim())return;n.user_turns++,n.user_chars+=H.length;let K=xr(H);K&&(a=K);let L=Q0(H,l,c);l=H,L.kind==="correction"?n.corrections++:L.kind==="rework"?n.reworks++:L.kind==="repeat"?n.repeated_instructions++:L.kind==="acceptance"&&n.acceptances++,L.polarity!==0&&i.push(L),c=!1},"processLine");y.on("line",w=>{try{_(w)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await tA(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||J0(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 u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,p=0,h=[];return i.forEach((m,g)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,d=d*Y0+m.polarity*m.magnitude;let y=Number(d.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 ms,Wh,B0,K0,V0,z0,q0,Y0,Pn,Bh=b(()=>{"use strict";ds();ps();ms="mcp__maind__",Wh="2026-09-09",B0=/(\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,K0=/(\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,V0=/(\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,z0="[Request interrupted by user",q0="The user doesn't want to proceed with this tool use",Y0=.7,Pn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(J0,"bumpModel");o(fs,"asBlocks");o(X0,"textOf");o(Z0,"isRepeat");o(Q0,"classifyGenuine");o(eA,"emptyAnalysis");o(tA,"tallySubagentMaindCalls");o(lc,"analyzeSession")});function dc(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 uc(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 pc(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 Kh=b(()=>{"use strict";o(dc,"parseIngestResponse");o(uc,"describeSliceVerdict");o(pc,"ingestBody")});import{homedir as nA}from"node:os";import{join as rA}from"node:path";var iA,fc=b(()=>{"use strict";iA=rA(nA(),".codex","sessions")});var Vh=b(()=>{"use strict";fc()});import{isAbsolute as gc,relative as oA,resolve as zh,sep as yc}from"node:path";function qh(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function hs(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function _c(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=o(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let u=l,d=hs(u.from);typeof u.object_id!="string"||!mc.test(u.object_id)||d===null||c.push({object_id:u.object_id.toLowerCase(),from:d,to:hs(u.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=hs(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:hs(c.to)})}let s=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!mc.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"&&mc.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 Jh(e,t){if(!gc(e))return null;let n=oA(zh(t),zh(e));return!n||n==="."||n.startsWith("..")||gc(n)?null:yc==="/"?n:n.split(yc).join("/")}function aA(e,t){return t===""||e===t||e.startsWith(t+"/")}function bc(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Xh(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function wc(e,t){for(let n of Xh(t))if(aA(e,n.path_prefix))return n.object_id;return null}function cA(e,t){for(let n of Xh(t))if(bc(e,n.path_prefix))return n.object_id;return null}function hc(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Zh(e,t,n,r){let i=e.ts,s=r?.anchors??[],a=t.map(c=>wc(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(d=>hc(i,d));if(c.length)return c.sort((d,p)=>p.from-d.from||d.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(d=>hc(i,d));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,h)=>p.object_id.localeCompare(h.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>hc(i,d));if(u.length){let d=t[0]??n?.rel??null,p=(d===null?u:u.filter(h=>bc(h.path_prefix,d))).sort((h,m)=>m.path_prefix.length-h.path_prefix.length);for(let h of p){let m=cA(h.path_prefix,s);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function vc(e,t,n){let r=t?.anchors??[],i=o(g=>{if(!n.repoRoot)return[];let y=[];for(let _ of g.edited_paths){let w=Jh(_,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),s=o(g=>{for(let y of g){let _=wc(y,r);if(_)return{object_id:_,rel:y}}return null},"firstAnchoredEdit"),a=new Map;for(let g of e){let y=a.get(g.stream)??[];y.push(g),a.set(g.stream,y)}let c=[...a.entries()].sort(([g],[y])=>g===jt?-1:y===jt?1:0),l=[],u=o(g=>{let y=null;for(let _ of l){if(_.ts>g&&g>0)break;y=_.seg}return y},"mainSegmentAt"),d=new Map;for(let[g,y]of c){let _=y.map((k,x)=>({t:k,i:x,rels:i(k)})).sort((k,x)=>k.t.ts-x.t.ts||k.i-x.i),w=null;for(let k of _){let x=s(k.rels);if(x){w=x;break}}!w&&g!==jt&&_.length&&(w=u(_[0].t.ts));for(let k of _){let x=s(k.rels);x&&(w=x),g===jt&&l.push({ts:k.t.ts,seg:w});let S=k.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let $=Zh(S,k.rels,w,t),H=S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens>Yh?"above_200k":"standard",U=qh(S.model),K=`${$.object_id??""}|${$.source}|${U}|${H}`,L=d.get(K);L||(L={object_id:$.object_id,attribution_source:$.source,model:U,context_tier:H,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},d.set(K,L)),L.input_tokens+=S.input_tokens,L.output_tokens+=S.output_tokens,L.cache_read_tokens+=S.cache_read_tokens,L.cache_creation_tokens+=S.cache_creation_tokens,L.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,L.turns+=1,S.ts>0&&((L.firstMs===0||S.ts<L.firstMs)&&(L.firstMs=S.ts),S.ts>L.lastMs&&(L.lastMs=S.ts))}}let p=n.nowMs??Date.now(),h=[];for(let g of d.values()){let{firstMs:y,lastMs:_,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(_>0?_: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 kc(e,t){let n=new Map;for(let s of e){let a=new Set;for(let c of s.edited_paths){if(!gc(c))continue;let l=t(lA(c));l&&a.add(l)}for(let c of a)n.set(c,(n.get(c)??0)+1)}let r=null,i=0;for(let[s,a]of n)(a>i||a===i&&r!==null&&s.length>r.length)&&(r=s,i=a);return r}function lA(e){let t=e.split(yc).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Yh,mc,Qh=b(()=>{"use strict";ps();o(qh,"normalizeModelId");Yh=2e5,mc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(hs,"msOf");o(_c,"parseCostContext");o(Jh,"toRepoRelative");o(aA,"underPrefix");o(bc,"prefixesOverlap");o(Xh,"sortedAnchors");o(wc,"anchorFor");o(cA,"bestAnchorOverlapping");o(hc,"inWindow");o(Zh,"assignTurn");o(vc,"sliceSession");o(kc,"dominantCheckoutRoot");o(lA,"dirOf")});import{createReadStream as dA,existsSync as uA}from"node:fs";import{createInterface as pA}from"node:readline";function eg(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function hA(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
136
|
-
`)}function
|
|
137
|
-
`)}return""}async function xc(e,t={}){if(!e||!_A(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:sc(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:sc(),a=t.start??0;return await new Promise(c=>{let l=yA(e,{encoding:"utf-8",start:t.start??0}),u=bA({input:l});u.on("line",p=>{a+=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(),_=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=wA[m.attachment.type];w&&(s[vA(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(_==="user"){let w=kA(m.message?.content),k=xr(w);k&&(i=k);let x={session_id:g,ts:y,text:w,effort_directive:k};n.push({kind:"user",...x});return}if(_==="assistant"){let w=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,x=typeof m.requestId=="string"&&m.requestId?m.requestId:null,S=k??x,I=S!==null&&r.has(S);S!==null&&!I&&r.add(S);let $={session_id:g,ts:y,model:m.message?.model??null,input_tokens:I?0:gs(w?.input_tokens),output_tokens:I?0:gs(w?.output_tokens),cache_read_input_tokens:I?0:gs(w?.cache_read_input_tokens),cache_creation_input_tokens:I?0:gs(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",...$})}});let d=o(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...s},seenMessagesAtEnd:new Set(r)}),"finalResult");u.on("close",()=>c(d())),u.on("error",()=>c(d())),l.on("error",()=>c(d()))})}var wA,sg=b(()=>{"use strict";ds();oc();wA={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};o(vA,"modeFlagKey");o(gs,"num");o(kA,"extractUserText");o(xc,"streamTranscript")});var og=b(()=>{"use strict"});import{homedir as SA}from"node:os";import{join as xA}from"node:path";function Ac(e){return e.replace(/[/.]/g,"-")}var EA,Ec,ag=b(()=>{"use strict";EA=SA(),Ec=xA(EA,".claude","projects");o(Ac,"projectPathFromCwd")});var Mn=b(()=>{"use strict";oc();$h();Lh();Bh();Kh();ps();fc();Vh();Qh();ig();sg();ds();og();ag()});function Tc(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 MA(e){if(e.raw===null)return null;if(e.kind==="toml"){let t=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!t)return null;let n=/^\s*command\s*=\s*"([^"]*)"/m.exec(t[1]),r=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(t[1]);return n?{command:n[1],args:r?[...r[1].matchAll(/"([^"]*)"/g)].map(i=>i[1]):[]}:null}try{let n=JSON.parse(e.raw).mcpServers?.maind;return!n||typeof n.command!="string"?null:{command:n.command,args:Array.isArray(n.args)?n.args.filter(r=>typeof r=="string"):[]}}catch{return null}}function $n(e,t){let n=`npm i -g ${Ar}@${e}`;return t?`nvm use ${t} && ${n}`:n}function _s(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(d=>d.bridgeVersion).filter(d=>d!==null)],r=e.latestVersion??n.sort(Tc).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(d=>d.bridgeVersion!==null);if(e.nodeTrees.length>0){let d=e.pathWinner?.node??null,p=e.nodeTrees.find(m=>m.node===d);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:$n(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(g=>Tc(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:$n(r,m.node)})}let s=!1,a=new Map,c=o((d,p)=>{let h=a.get(d)??{version:e.installVersionOf(d),clients:[]};h.clients.push(p),a.set(d,h)},"noteInstall");for(let d of e.clientConfigs){let p=MA(d);if(p===null)continue;if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(g=>g.includes(Ar))){t.push({check:"client-config",level:"warn",message:`${d.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${$n(r)}, then set "command": "maind-mcp-bridge" (no args) in ${d.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:`${d.label} runs ${g}, which does not exist.`,fix:`re-run \`npx -y ${Ar}@${r} install\` to rewrite the entry`});continue}c(g,d.label)}else if(p.command.includes("/")||p.command.includes("\\")){if(!e.fileExists(p.command)){t.push({check:"client-config",level:"error",message:`${d.label} points at ${p.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${d.path} (after ${$n(r)})`});continue}}else if(p.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${d.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:$n(r,e.nvmDefault)});continue}m||(p.command.includes("/")||p.command.includes("\\")?c(p.command,d.label):p.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,d.label)),t.push({check:"client-config",level:"ok",message:`${d.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 ${Ar} install`}),e.latestVersion!==null)for(let[d,p]of a){let h=p.clients.join(", ");if(p.version===null)t.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${d} is.`});else if(Tc(p.version,e.latestVersion)<0){let m=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(d)?.[1]??null;t.push({check:"version",level:"warn",message:`${h} run bridge ${p.version} (${d}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:m?$n(e.latestVersion,m):`npx -y ${Ar}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${h} run bridge ${p.version} (published: ${e.latestVersion}).`})}for(let{dir:d,maind:p}of e.npxStaleDirs)t.push({check:"npx-cache",level:p?"error":"info",message:p?`a half-built better-sqlite3 was left in ${d} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${d} (another tool's npx entry, not maind's).`,fix:`rm -rf '${d.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!dg.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"}):PA.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&dg.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 u=e.connection;if(u===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):u.outcome==="ok"||u.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${u.outcome==="ok"?"succeeded":"was paired"} at ${u.at} (bridge ${u.bridge_version}).`}):t.push({check:"connection",level:"error",message:u.outcome==="auth_failed"?`the server rejected the last connection (${u.at}${u.detail?`: ${u.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${u.at}${u.detail?`: ${u.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"}),e.claudeSettings!==null){let d=$t(e.claudeSettings,{fileExists:o(h=>e.fileExists(h),"fileExists")}),p=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let h of d){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 ug(e){let t=e.filter(i=>i.level==="error"&&Rc.includes(i.check)).sort((i,s)=>Rc.indexOf(i.check)-Rc.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 pg(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,c)=>n[a.level]-n[c.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),i=e.filter(a=>a.level==="error").length,s=e.filter(a=>a.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
164
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as S0}from"node:crypto";function Pn(t){return S0("sha256").update(t,"utf8").digest("hex")}function xh(t){return{node_key_hash:Pn(t.nodeKey),name:t.name,qualified_name:t.qualifiedName,path_hash:Pn(t.filePath),kind:t.kind,language:t.language,start_line:t.startLine,end_line:t.endLine,signature_hash:t.signature?Pn(t.signature):null}}function Sh(t){return{src_key_hash:Pn(t.srcKey),dst_key_hash:Pn(t.dstKey),kind:t.kind}}function Eh(t,e,n){return{node_key_hash:Pn(t.nodeKey),embedding:Array.from(t.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:e}}var Th=b(()=>{"use strict";a(Pn,"sha256");a(xh,"toCloudNode");a(Sh,"toCloudEdge");a(Eh,"toCloudEmbedding")});function uc(t,e){let n=[];for(let r=0;r<t.length;r+=e)n.push(t.slice(r,r+e));return n}function Rh(t){if(t===null)return null;let e=Number(t);return Number.isFinite(e)?e:null}function T0(t){return typeof t=="number"&&Number.isFinite(t)?t:0}var Ln,$n,E0,pc=b(()=>{"use strict";wr();Th();Ln=class extends Error{static{a(this,"SyncError")}status;code;constructor(e,n,r){super(e),this.status=n,this.code=r,this.name="SyncError"}},$n=class{static{a(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(e,n){this.store=e,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(e,n){await this.post("/api/codebase/consent",{enabled:e,policy_version:n??null})}async remoteStatus(){let e=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${e.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(Sn),lastSyncedAt:Rh(await this.store.getMeta(Ca))}}async push(){await this.store.init();let e=(await this.store.getAllNodes()).map(xh),n=(await this.store.getAllEdges()).map(Sh),r=await this.store.getMeta(xn)??kn,i=await this.store.getMeta(Sn),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(y=>[y.language,y.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},l=0,d=uc(e,this.chunk),u=uc(n,this.chunk*2),p=Math.max(1,d.length+u.length);for(let y of d)await this.post("/api/codebase/push",{...c,nodes:y,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let y of u)await this.post("/api/codebase/push",{...c,nodes:[],edges:y}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});d.length===0&&u.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let h=e.map(y=>y.node_key_hash),m=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:h});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let g=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(Ca,String(Date.now())),i&&await this.store.setMeta(Wf,i),{nodes:e.length,edges:n.length,pruned:T0(m.nodes_deleted),embeddings:g,headCommit:i}}async pushEmbeddings(){await this.store.init();let e=await this.store.getEmbeddingContentHashes();if(e.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=>Eh(d,e.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=uc(o,E0),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 e=await this.store.getMeta(Mi),n=await this.store.getMeta(Pi),r=Rh(await this.store.getMeta(Li));if(!e||!n||!r)throw new Ln("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:e,model:n,dim:r}}headers(){let e={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(e["x-maind-device-id"]=this.cfg.deviceId),e}async post(e,n){let r=await this.fetchImpl(`${this.base}${e}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,e)}async get(e){let n=await this.fetchImpl(`${this.base}${e}`,{method:"GET",headers:this.headers()});return this.unwrap(n,e)}async unwrap(e,n){let r=await e.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!e.ok||!i||i.ok!==!0){let s=i?.error;throw new Ln(`${n} failed (HTTP ${e.status})${s?`: ${s}`:""}`,e.status,s)}return i}},E0=250;a(uc,"chunkArray");a(Rh,"numOrNull");a(T0,"numOr0")});var Ah={};oe(Ah,{CodeIndexSync:()=>$n,DEFAULT_DB_RELPATH:()=>fc,SyncError:()=>Ln,createCodeIndexSync:()=>A0,createNodeCodeIndex:()=>mc,openSqliteDatabase:()=>as,probeBuiltinSqlite:()=>Mn});import{mkdirSync as R0}from"node:fs";import{posix as ls}from"node:path";function mc(t){let e=t.dbPath??ls.join(t.repoRoot,fc);R0(ls.dirname(e),{recursive:!0}),t.dbPath===void 0&&lr(ls.dirname(e));let n=new Cr(e),r=new os;return new vr({store:n,parser:r,repoRoot:t.repoRoot,embedder:t.embedder})}function A0(t){let e=t.dbPath??ls.join(t.repoRoot,fc),n=t.projectKey??$p(t.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 Cr(e);return new $n(r,{endpoint:t.endpoint,apiKey:t.apiKey,projectKey:n,deviceId:t.deviceId,chunkSize:t.chunkSize,onProgress:t.onProgress})}var fc,hc=b(()=>{"use strict";Bo();ch();Ma();kh();pc();mi();pc();dc();fc=".maind/code-index.sqlite";a(mc,"createNodeCodeIndex");a(A0,"createCodeIndexSync")});import{execFileSync as Nh}from"node:child_process";import{existsSync as Ih,realpathSync as Ch}from"node:fs";import{createRequire as N0}from"node:module";import{basename as I0,dirname as C0,isAbsolute as Oh,join as O0,relative as Dh,resolve as ds,sep as Mh}from"node:path";function Ph(){let t=Mn();if(t.ok)return{ok:!0,backend:"node:sqlite"};try{return N0(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(e){let n=e instanceof Error?e.message:String(e);return{ok:!1,reason:`node:sqlite: ${t.reason}; better-sqlite3: ${n}`}}}function Lh(t){let e=t?.code??"",n=t instanceof Error?t.message:String(t);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${e} ${n}`)||e==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function fe(t=process.cwd()){try{let e=Nh("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:t}catch{return t}}function Fh(t,e=fe(),n=process.cwd()){let r=Oh(t)?[t]:[ds(e,t),ds(n,t)];for(let i of r){let s=C0(i);if(!Ih(s))continue;let o;try{o=Ch(s)}catch{continue}let c=jh(o);if(c===null)continue;let l=Dh(c,O0(o,I0(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Mh).join("/")}}return null}function us(t,e=fe(),n=process.cwd()){let r=Oh(t)?[t]:[ds(e,t),ds(n,t)];for(let i of r){if(!Ih(i))continue;let s;try{s=Ch(i)}catch{continue}let o=jh(s);if(o===null)continue;let c=Dh(o,s);if(!c.startsWith(".."))return{repoRoot:o,repoRelDir:c===""?"":c.split(Mh).join("/")}}return null}function jh(t){try{let e=Nh("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:null}catch{return null}}function Uh(){return mc({repoRoot:fe()})}var $h,Or=b(()=>{"use strict";hc();a(Ph,"probeNativeStore");a(Lh,"isNativeStoreUnavailable");$h="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(Fh,"resolveRepoRootForPath");a(us,"resolveRepoRootForDir");a(jh,"gitToplevelOf");a(Uh,"defaultEngineFactory")});import{execFile as Qh}from"node:child_process";import{randomUUID as G0}from"node:crypto";function Y0(t){let e=(t.MAIND_SESSION_ID??"").trim().toLowerCase();return yc.test(e)?e:G0()}function _c(t,e){let n=(t.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:e?.auto_announce===!1}function J0(t,e){let n=(t.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:e?.auto_working_paths===!0}async function X0(t){return await new Promise(e=>{Qh("git",["config","--get",`branch.${t}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return e(null);e(Z0(r))})})}function Z0(t){let e=(t??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)?e:null}async function Q0(){return await new Promise(t=>{Qh("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8"},(e,n)=>{if(e)return t(null);let r=n.trim();t(r.length>0&&r!=="HEAD"?r:null)})})}function eT(t){if(typeof t!="string")return null;let e=t.trim().slice(0,100);return e.length>0?e:null}function tT(t,e){let n=e,r=(t.MAIND_SESSION_ID??"").trim().toLowerCase(),i=yc.test(r)&&r===e?"env":"random";return{current:a(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:a(()=>!1,"tryUpgrade"),adopt:a(s=>{yc.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:a(()=>null,"activityAtMs")}}var Zh,eg,B0,K0,V0,z0,q0,yc,gs,bc=b(()=>{"use strict";Dn();Zh=45e3,eg=3e4,B0=5,K0=120,V0=3e4,z0=15*6e4,q0=1500,yc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Y0,"resolveClientSessionId");a(_c,"autoAnnounceDisabled");a(J0,"autoWorkingPathsEnabled");gs=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(e){let n=e.env??process.env,r=(e.readConfig??Oe)();this.projectKey=e.projectKey,this.postToolCall=e.postToolCall,this.now=e.now??Date.now,this.gitBranch=e.gitBranch??Q0,this.gitBranchObject=e.gitBranchObject??X0,this.log=e.log??(i=>process.stderr.write(i+`
|
|
165
|
+
`)),this.machineLabel=eT(r?.machine_label),this.enabled=this.projectKey!==null&&!_c(n,r),this.workingPathsEnabled=J0(n,r),this.deriveWorkingPaths=e.deriveWorkingPaths??null,this.snapshot=e.snapshot??null,this.identity=e.identity??tT(n,Y0(n)),this.sessionMeta=e.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<Zh||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let e=this.identity.activityAtMs();if(e===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(e<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<Zh||(this.lastActivityAt=e,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<B0||(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 e=new Promise(n=>setTimeout(n,q0).unref());await Promise.race([this.send("ended"),e])}async announce(e){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(e),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(V0*2**(this.consecutiveFailures-1),z0);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(e){if(this.projectKey===null)return;try{if(e==="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:e,ttl_minutes:K0,announce_source:"bridge"};if(e==="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(e==="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(e==="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(X0,"defaultGitBranchObject");a(Z0,"normalizeObjectId");a(Q0,"defaultGitBranch");a(eT,"normalizeMachineLabel");a(tT,"staticIdentity")});import{mkdirSync as tg,readdirSync as sg,readFileSync as nT,renameSync as ng,statSync as rT,unlinkSync as wc,writeFileSync as rg}from"node:fs";import{homedir as iT}from"node:os";import{join as Fn}from"node:path";function og(){return Fn(iT(),".maind","presence")}function ag(t,e){return Fn(t,e)}function cg(t){let e=t.baseDir??og(),n=ag(e,t.projectKey),r=t.pid??process.pid,i=t.ppid??process.ppid,s=t.cwd??process.cwd(),o=t.now??Date.now,c=null,l=a(d=>{if(c!==null&&c!==d)try{wc(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:t.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:[]};tg(n,{recursive:!0,mode:448});let m=Fn(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;rg(g,JSON.stringify(h),{mode:384}),ng(g,m),l(m),ig(n,o(),m)}catch{}},endSession(){try{c&&wc(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(o()).toISOString(),project_key:t.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};tg(n,{recursive:!0,mode:448});let h=Fn(n,`${u.sessionId}.json`),m=`${h}.tmp-${r}`;rg(m,JSON.stringify(p),{mode:384}),ng(m,h),l(h),ig(n,o(),h)}catch{}}}}function ig(t,e,n){try{for(let r of sg(t)){if(!r.endsWith(".json"))continue;let i=Fn(t,r);if(i!==n)try{e-rT(i).mtimeMs>sT&&wc(i)}catch{}}}catch{}}function jn(t,e=og()){try{let n=ag(e,t),r=[];for(let i of sg(n))if(i.endsWith(".json"))try{let s=JSON.parse(nT(Fn(n,i),"utf8")),o=oT(s);o&&r.push(o)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function oT(t){if(typeof t!="object"||t===null)return null;let e=t;return e.v!==1||typeof e.written_at!="string"||typeof e.project_key!="string"||typeof e.own_session_id!="string"||typeof e.own_pid!="number"||typeof e.own_ppid!="number"||typeof e.cwd!="string"?null:{v:1,written_at:e.written_at,project_key:e.project_key,own_session_id:e.own_session_id,own_pid:e.own_pid,own_ppid:e.own_ppid,cwd:e.cwd,branch:typeof e.branch=="string"?e.branch:null,peers:Array.isArray(e.peers)?e.peers:[],conflicts:Array.isArray(e.conflicts)?e.conflicts:[],...typeof e.announce_error=="string"?{announce_error:e.announce_error}:{}}}var sT,ys=b(()=>{"use strict";sT=120*6e4;a(og,"presenceSnapshotBaseDir");a(ag,"projectDir");a(cg,"createSnapshotStore");a(ig,"pruneStale");a(jn,"readSnapshots");a(oT,"parseSnapshot")});import{execFileSync as aT}from"node:child_process";import{createHash as cT,randomUUID as lT}from"node:crypto";import{existsSync as dT,mkdirSync as uT,readdirSync as pT,readFileSync as dg,renameSync as fT,statSync as vc,unlinkSync as ug,writeFileSync as mT}from"node:fs";import{homedir as hT}from"node:os";import{basename as gT,join as pt}from"node:path";function Un(t){return pt(t??pt(hT(),".maind","presence"),"identity")}function Mr(t,e){if(t){let n=gT(t).replace(/\.jsonl$/i,"");if(Dr.test(n))return n.toLowerCase()}return e&&Dr.test(e)?e.toLowerCase():null}function pg(t){let e=t.nowMs??Date.now();uT(t.dir,{recursive:!0,mode:448});let n=pt(t.dir,`${t.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!t.transcriptPath||!t.model)try{let l=JSON.parse(dg(n,"utf8"));l.session_id===t.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=t.transcriptPath??i.transcript_path,o=t.model??i.model,c={v:1,session_id:t.sessionId,transcript_stem:t.transcriptStem,cwd:t.cwd,agent_pid:t.agentPid,written_at:new Date(e).toISOString(),...s?{transcript_path:s}:{},...o?{model:o}:{}};mT(r,JSON.stringify(c,null,2)+`
|
|
166
|
+
`,{mode:384}),fT(r,n),vT(t.dir,e)}function fg(t,e,n,r=Date.now()){try{let i=vc(pt(t,`${e}.json`));return r-i.mtimeMs>n}catch{return!0}}function mg(t,e){try{ug(pt(t,`${e}.json`))}catch{}}function vT(t,e){try{for(let n of pT(t))if(n.endsWith(".json"))try{let r=vc(pt(t,n));e-r.mtimeMs>_T&&ug(pt(t,n))}catch{}}catch{}}function kT(t){return hg(t)?.file??null}function hg(t){let e=pt(t.dir,`${t.agentPid}.json`);try{if(!dT(e))return null;let n=vc(e);if(n.mtimeMs<t.bridgeStartMs-bT)return null;let r=JSON.parse(dg(e,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Dr.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==t.agentPid||!xT(i.cwd,t.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function lg(t){return t.replace(/\/+$/,"")}function xT(t,e){let n=lg(t),r=lg(e);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function ST(t,e){let n=Buffer.from(e.replace(/-/g,""),"hex"),r=cT("sha1").update(n).update(t,"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 ET(t){if(process.platform==="win32")return null;try{let e=aT("ps",["-o","lstart=","-p",String(t)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return e.length>0?e:null}catch{return null}}function TT(){try{return ne()}catch{return null}}var Dr,yT,_T,bT,wT,_s,bs=b(()=>{"use strict";re();Dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,yT=8,_T=48*60*6e4,bT=6e4,wT="9f3c72da-2f10-4b8f-9c31-ad291c0de291";a(Un,"identityDirPath");a(Mr,"transcriptStemOf");a(pg,"writeAgentIdentityFile");a(fg,"identityFileStale");a(mg,"deleteAgentIdentityFile");a(vT,"pruneIdentityDir");a(kT,"readAgentIdentityFile");a(hg,"readAgentIdentityEntry");a(lg,"normDir");a(xT,"sameSessionTree");a(ST,"uuidV5");a(ET,"processStartTime");_s=class{static{a(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];stem=null;constructor(e){this.env=e.env??process.env,this.agentPid=e.agentPid??process.ppid,this.cwd=e.cwd??process.cwd(),this.dir=e.identityDir??Un(),this.bridgeStartMs=e.bridgeStartMs??Date.now(),this.nowMs=e.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Dr.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=(e.deviceId??TT)(),s=(e.ppidStart??ET)(this.agentPid);if(i!==null&&s!==null&&e.projectKey!==null){this.id=ST(`${i}|${this.agentPid}|${s}|${e.projectKey}`,wT),this.source="derived";return}this.id=lT(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){return this.resync()!=="unchanged"}resync(){let e=this.readStem();if(e===null)return"unchanged";if(this.source==="client_native")return e===this.stem?"unchanged":(this.id=e,this.stem=e,this.aliases=this.envId!==null&&this.envId!==e?[this.envId]:[],"switched");if(e===this.id)return"unchanged";let n=this.id;return this.id=e,this.stem=e,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),"upgraded"}adopt(e){let n=e.trim().toLowerCase();if(!Dr.test(n)||n===this.id)return;let r=this.id;this.id=n,!(this.source==="client_native"&&r===this.stem)&&this.pushAlias(r)}pushAlias(e){e===this.id||this.aliases.includes(e)||(this.aliases.push(e),this.aliases.length>yT&&this.aliases.shift())}activityAtMs(){return hg({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let e=this.sideChannel();return e===null?null:e.transcript_stem.toLowerCase()}sideChannel(){return kT({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};a(TT,"defaultDeviceId")});function kc(){return{ultracode:!1,planMode:!1,autoMode:!1}}var xc=b(()=>{"use strict";a(kc,"newModeState")});import{createReadStream as RT,existsSync as AT}from"node:fs";import{stat as NT}from"node:fs/promises";import{createInterface as IT}from"node:readline";async function Sc(t){if(!t||!AT(t))return null;let e;try{e=await NT(t)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(o=>{let c=RT(t,{encoding:"utf-8"}),l=IT({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:e.mtimeMs})}),l.on("error",()=>o(null)),c.on("error",()=>o(null))})}var gg=b(()=>{"use strict";a(Sc,"summariseTranscript")});var yg=b(()=>{"use strict"});function Pr(t){if(!t)return null;let e=null;for(let n of t.matchAll(OT)){let r=n[1].toLowerCase();CT.has(r)&&(e=r)}return e}var CT,OT,ws=b(()=>{"use strict";CT=new Set(["low","medium","high","xhigh","max"]),OT=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;a(Pr,"detectEffortLevel")});import{createReadStream as DT,existsSync as MT,readdirSync as PT}from"node:fs";import{basename as wg,dirname as LT,join as _g}from"node:path";import{createInterface as $T}from"node:readline";function Hn(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function UT(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=jT[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&e.push(s)}return e}function vs(t){let e=wg(t).replace(/\.jsonl$/,""),n=_g(LT(t),e,"subagents"),r;try{r=PT(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>_g(n,i))}async function bg(t,e,n,r,i){MT(t)&&await new Promise(s=>{let o=DT(t,{encoding:"utf-8"}),c=$T({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??`${t}#${l}`,y=UT(p.message.content),_=r.get(g);if(_){for(let A of y)_.edited_paths.includes(A)||_.edited_paths.push(A);return}if(n.has(g))return;n.add(g);let w=p.message.usage??{},k=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,x=typeof p.message.model=="string"&&p.message.model?p.message.model:"",S={ts:Number.isFinite(k)?k:0,model:x||"<unknown>",synthetic:x===FT,input_tokens:Hn(w.input_tokens),output_tokens:Hn(w.output_tokens),cache_read_tokens:Hn(w.cache_read_input_tokens),cache_creation_tokens:Hn(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Hn(w.cache_creation?.ephemeral_1h_input_tokens),Hn(w.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:e,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 Ec(t){let e=0;for(let r of t)r.ts>0?e=r.ts:e>0&&(r.ts=e);let n=0;for(let r=t.length-1;r>=0;r--){let i=t[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function Lr(t){let e=new Set,n=new Map,r=[],i=t?vs(t):[];if(!t)return{turns:r,subagent_files:i};let s=[];await bg(t,Vt,e,n,s),Ec(s),r.push(...s);for(let o of i){let c=[],l=wg(o).replace(/\.jsonl$/,"");await bg(o,l,e,n,c),Ec(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Vt,FT,jT,ks=b(()=>{"use strict";Vt="main",FT="<synthetic>",jT={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};a(Hn,"num");a(UT,"editedPathsOf");a(vs,"subagentFilesOf");a(bg,"readStream");a(Ec,"fillTimestamps");a(Lr,"collectTurns")});import{createReadStream as vg,existsSync as HT}from"node:fs";import{createInterface as kg}from"node:readline";function qT(t,e,n,r,i){let s=`${n?"s":"m"}:${e}`,o=t.get(s);if(!o){t.set(s,{model:e,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 xs(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(e=>e!==null&&typeof e=="object"):[]}function YT(t){let e=[];for(let n of t)n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join(`
|
|
167
|
+
`)}function JT(t,e){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(t),i=n(e);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 XT(t,e,n){return WT.test(t)?{polarity:-1,magnitude:Wn.rework,kind:"rework"}:n&>.test(t)?{polarity:-1,magnitude:Wn.correction,kind:"correction"}:BT.test(t)?{polarity:1,magnitude:Wn.acceptance,kind:"acceptance"}:e!==null&&JT(e,t)?{polarity:-1,magnitude:Wn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function ZT(t){return{session_id:t,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:xg,behaviour_measured:!0}}async function QT(t,e){for(let n of vs(t))await new Promise(r=>{let i=kg({input:vg(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 xs(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Ss))continue;let d=l.name.slice(Ss.length);d&&(e.maind_tool_calls??={},e.maind_tool_calls[d]=(e.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Tc(t,e={}){let n=ZT("");if(!t||!HT(t))return n;let r=e.turns??(await Lr(t)).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=vg(t,{encoding:"utf-8"}),y=kg({input:g}),_=a(w=>{let k=w.trim();if(!k)return;let x;try{x=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let B=x.sessionId??x.session_id;typeof B=="string"&&B&&(n.session_id=B)}x.type==="ai-title"&&typeof x.aiTitle=="string"&&x.aiTitle&&(n.ai_title=x.aiTitle),typeof x.slug=="string"&&x.slug&&(n.session_slug=x.slug);let S=x.message?.role,A=x.isSidechain===!0;if(S==="assistant")for(let B of xs(x.message?.content)){if(B.type!=="tool_use"||typeof B.name!="string"||!B.name.startsWith(Ss))continue;let tn=B.name.slice(Ss.length);tn&&(n.maind_tool_calls??={},n.maind_tool_calls[tn]=(n.maind_tool_calls[tn]??0)+1)}if(A)return;if(S==="assistant"){let B=xs(x.message?.content),tn=!1;for(let El of B)El.type==="tool_use"&&(n.tool_calls++,tn=!0,El.name==="AskUserQuestion"&&n.agent_questions++);c=tn;return}if(S!=="user")return;let D=xs(x.message?.content),F=YT(D);if(F.includes(KT)){n.interrupts++,i.push({polarity:-1,magnitude:Wn.interrupt,kind:"interrupt"});return}if(D.some(B=>B.type==="tool_result"&&B.is_error===!0&&typeof B.content=="string"&&B.content.includes(VT))){n.tool_denials++,i.push({polarity:-1,magnitude:Wn.denial,kind:"denial"});return}if(D.some(B=>B.type==="tool_result")||!F.trim())return;n.user_turns++,n.user_chars+=F.length;let H=Pr(F);H&&(o=H);let $=XT(F,l,c);l=F,$.kind==="correction"?n.corrections++:$.kind==="rework"?n.reworks++:$.kind==="repeat"?n.repeated_instructions++:$.kind==="acceptance"&&n.acceptances++,$.polarity!==0&&i.push($),c=!1},"processLine");y.on("line",w=>{try{_(w)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await QT(t,n),n.effort_at_end=o;for(let m of r)m.synthetic||m.model==="<unknown>"||qT(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*zT+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 Ss,xg,WT,GT,BT,KT,VT,zT,Wn,Sg=b(()=>{"use strict";ws();ks();Ss="mcp__maind__",xg="2026-09-09",WT=/(\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,GT=/(\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,BT=/(\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,KT="[Request interrupted by user",VT="The user doesn't want to proceed with this tool use",zT=.7,Wn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};a(qT,"bumpModel");a(xs,"asBlocks");a(YT,"textOf");a(JT,"isRepeat");a(XT,"classifyGenuine");a(ZT,"emptyAnalysis");a(QT,"tallySubagentMaindCalls");a(Tc,"analyzeSession")});function Rc(t){let e=t!==null&&typeof t=="object"?t:{},n=typeof e.slices_stored=="boolean"?e.slices_stored:null;return{analyticsStored:e.analytics_stored===!0,spanStored:e.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof e.slices_reason=="string"?e.slices_reason:null,slicesCount:typeof e.slices_count=="number"&&Number.isFinite(e.slices_count)?e.slices_count:0}}function Ac(t,e){return!e||t.slicesStored===!0?null:t.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${t.slicesReason??"no reason given"} (${t.slicesCount} sent)`}function Nc(t,e,n,r="unknown",i){let s={session_analytics:{...t,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 e&&e.started_at&&(s.session_span=n?{...e,...n}:e),s}var Eg=b(()=>{"use strict";a(Rc,"parseIngestResponse");a(Ac,"describeSliceVerdict");a(Nc,"ingestBody")});import{homedir as eR}from"node:os";import{join as tR}from"node:path";var nR,Ic=b(()=>{"use strict";nR=tR(eR(),".codex","sessions")});var Tg=b(()=>{"use strict";Ic()});import{isAbsolute as Dc,relative as iR,resolve as Rg,sep as Mc}from"node:path";function Ag(t){return t.trim().replace(/\[[^\]]*\]$/,"")}function Es(t){if(typeof t!="string"||!t)return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function Pc(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e;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=Es(d.from);typeof d.object_id!="string"||!Cc.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:Es(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=Es(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:Es(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"||!Cc.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"&&Cc.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 Ig(t,e){if(!Dc(t))return null;let n=iR(Rg(e),Rg(t));return!n||n==="."||n.startsWith("..")||Dc(n)?null:Mc==="/"?n:n.split(Mc).join("/")}function sR(t,e){return e===""||t===e||t.startsWith(e+"/")}function Lc(t,e){return t===e||t===""||e===""||t.startsWith(e+"/")||e.startsWith(t+"/")}function Cg(t){return[...t].sort((e,n)=>n.path_prefix.length-e.path_prefix.length||e.object_id.localeCompare(n.object_id))}function $c(t,e){for(let n of Cg(e))if(sR(t,n.path_prefix))return n.object_id;return null}function oR(t,e){for(let n of Cg(e))if(Lc(t,n.path_prefix))return n.object_id;return null}function Oc(t,e){return t>=e.from&&(e.to===null||t<e.to)}function Og(t,e,n,r){let i=t.ts,s=r?.anchors??[],o=e.map(c=>$c(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Oc(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=>Oc(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=>Oc(i,u));if(d.length){let u=e[0]??n?.rel??null,p=(u===null?d:d.filter(h=>Lc(h.path_prefix,u))).sort((h,m)=>m.path_prefix.length-h.path_prefix.length);for(let h of p){let m=oR(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 Fc(t,e,n){let r=e?.anchors??[],i=a(g=>{if(!n.repoRoot)return[];let y=[];for(let _ of g.edited_paths){let w=Ig(_,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),s=a(g=>{for(let y of g){let _=$c(y,r);if(_)return{object_id:_,rel:y}}return null},"firstAnchoredEdit"),o=new Map;for(let g of t){let y=o.get(g.stream)??[];y.push(g),o.set(g.stream,y)}let c=[...o.entries()].sort(([g],[y])=>g===Vt?-1:y===Vt?1:0),l=[],d=a(g=>{let y=null;for(let _ of l){if(_.ts>g&&g>0)break;y=_.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let _=y.map((k,x)=>({t:k,i:x,rels:i(k)})).sort((k,x)=>k.t.ts-x.t.ts||k.i-x.i),w=null;for(let k of _){let x=s(k.rels);if(x){w=x;break}}!w&&g!==Vt&&_.length&&(w=d(_[0].t.ts));for(let k of _){let x=s(k.rels);x&&(w=x),g===Vt&&l.push({ts:k.t.ts,seg:w});let S=k.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let D=Og(S,k.rels,w,e),F=S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens>Ng?"above_200k":"standard",j=Ag(S.model),H=`${D.object_id??""}|${D.source}|${j}|${F}`,$=u.get(H);$||($={object_id:D.object_id,attribution_source:D.source,model:j,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,$)),$.input_tokens+=S.input_tokens,$.output_tokens+=S.output_tokens,$.cache_read_tokens+=S.cache_read_tokens,$.cache_creation_tokens+=S.cache_creation_tokens,$.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,$.turns+=1,S.ts>0&&(($.firstMs===0||S.ts<$.firstMs)&&($.firstMs=S.ts),S.ts>$.lastMs&&($.lastMs=S.ts))}}let p=n.nowMs??Date.now(),h=[];for(let g of u.values()){let{firstMs:y,lastMs:_,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(_>0?_: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 jc(t,e){let n=new Map;for(let s of t){let o=new Set;for(let c of s.edited_paths){if(!Dc(c))continue;let l=e(aR(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 aR(t){let e=t.split(Mc).join("/"),n=e.lastIndexOf("/");return n<=0?e:e.slice(0,n)}var Ng,Cc,Dg=b(()=>{"use strict";ks();a(Ag,"normalizeModelId");Ng=2e5,Cc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Es,"msOf");a(Pc,"parseCostContext");a(Ig,"toRepoRelative");a(sR,"underPrefix");a(Lc,"prefixesOverlap");a(Cg,"sortedAnchors");a($c,"anchorFor");a(oR,"bestAnchorOverlapping");a(Oc,"inWindow");a(Og,"assignTurn");a(Fc,"sliceSession");a(jc,"dominantCheckoutRoot");a(aR,"dirOf")});import{createReadStream as cR,existsSync as lR}from"node:fs";import{createInterface as dR}from"node:readline";function Mg(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(e=>typeof e=="object"&&e!==null):[]}function fR(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
168
|
+
`)}function $g(t){return{session_id:t,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 mR(t){let e=t.message?.role;if(e==="assistant")return{holder:Mg(t.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(e!=="user")return null;let n=Mg(t.message?.content),r=fR(n);return r.includes(uR)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(pR))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Uc(t){let e=$g("");if(!t||!lR(t))return e;let n=null,r=0,i=0,s=null,o="human",c=[];return await new Promise(l=>{let d=cR(t,{encoding:"utf-8"}),u=dR({input:d}),p=a(h=>{let m=h.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!e.session_id){let w=g.sessionId??g.session_id;typeof w=="string"&&w&&(e.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 _=mR(g);if(_!==null){if(e.event_count++,_.genuine&&e.turn_count++,n===null&&(n=y),r=y,s!==null){let w=y-s;o==="agent"?i+=w:w>=Pg*1e3&&(e.pause_count++,e.pause_seconds+=Math.round(w/1e3),c.length<Lg&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(w/1e3)}))}s=y,o=_.holder}},"processLine");u.on("line",h=>{try{p(h)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(e.started_at=new Date(n).toISOString(),e.ended_at=new Date(r).toISOString(),e.wall_seconds=Math.round((r-n)/1e3),e.agent_seconds=Math.round(i/1e3),e.wait_seconds=e.wall_seconds-e.agent_seconds,e.pauses=c,e.pauses_truncated=e.pause_count>c.length),e}var uR,pR,Pg,Lg,Fg=b(()=>{"use strict";uR="[Request interrupted by user",pR="The user doesn't want to proceed with this tool use",Pg=60,Lg=200;a(Mg,"asBlocks");a(fR,"textOf");a($g,"emptySpan");a(mR,"classify");a(Uc,"analyzeSpan")});import{createReadStream as hR,existsSync as gR}from"node:fs";import{createInterface as yR}from"node:readline";function bR(t){return t==="ultracode"?"ultracode":t==="plan"?"planMode":"autoMode"}function Ts(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function wR(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=[];for(let n of t)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&e.push(r)}return e.join(`
|
|
169
|
+
`)}return""}async function Hc(t,e={}){if(!t||!gR(t))return{events:[],bytesRead:e.start??0,effortAtEnd:e.initialEffort??null,modesAtEnd:e.initialModes?{...e.initialModes}:kc(),seenMessagesAtEnd:new Set(e.initialSeenMessages??[])};let n=[],r=new Set(e.initialSeenMessages??[]),i=e.initialEffort??null,s=e.initialModes?{...e.initialModes}:kc(),o=e.start??0;return await new Promise(c=>{let l=hR(t,{encoding:"utf-8",start:e.start??0}),d=yR({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(),_=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=_R[m.attachment.type];w&&(s[bR(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(_==="user"){let w=wR(m.message?.content),k=Pr(w);k&&(i=k);let x={session_id:g,ts:y,text:w,effort_directive:k};n.push({kind:"user",...x});return}if(_==="assistant"){let w=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,x=typeof m.requestId=="string"&&m.requestId?m.requestId:null,S=k??x,A=S!==null&&r.has(S);S!==null&&!A&&r.add(S);let D={session_id:g,ts:y,model:m.message?.model??null,input_tokens:A?0:Ts(w?.input_tokens),output_tokens:A?0:Ts(w?.output_tokens),cache_read_input_tokens:A?0:Ts(w?.cache_read_input_tokens),cache_creation_input_tokens:A?0:Ts(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 _R,jg=b(()=>{"use strict";ws();xc();_R={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(bR,"modeFlagKey");a(Ts,"num");a(wR,"extractUserText");a(Hc,"streamTranscript")});var Ug=b(()=>{"use strict"});import{homedir as vR}from"node:os";import{join as kR}from"node:path";function Gc(t){return t.replace(/[/.]/g,"-")}var xR,Wc,Hg=b(()=>{"use strict";xR=vR(),Wc=kR(xR,".claude","projects");a(Gc,"projectPathFromCwd")});var Gn=b(()=>{"use strict";xc();gg();yg();Sg();Eg();ks();Ic();Tg();Dg();Fg();jg();ws();Ug();Hg()});function Bc(t,e){let n=t.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),r=e.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 DR(t){if(t.raw===null)return null;if(t.kind==="toml"){let e=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(t.raw);if(!e)return null;let n=/^\s*command\s*=\s*"([^"]*)"/m.exec(e[1]),r=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(e[1]);return n?{command:n[1],args:r?[...r[1].matchAll(/"([^"]*)"/g)].map(i=>i[1]):[]}:null}try{let n=JSON.parse(t.raw).mcpServers?.maind;return!n||typeof n.command!="string"?null:{command:n.command,args:Array.isArray(n.args)?n.args.filter(r=>typeof r=="string"):[]}}catch{return null}}function Bn(t,e){let n=`npm i -g ${$r}@${t}`;return e?`nvm use ${e} && ${n}`:n}function As(t){let e=[],n=[t.runningVersion,...t.nodeTrees.map(u=>u.bridgeVersion).filter(u=>u!==null)],r=t.latestVersion??n.sort(Bc).at(-1)??t.runningVersion;t.latestVersion===null&&e.push({check:"version",level:"info",message:`doctor ${t.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=t.nodeTrees.filter(u=>u.bridgeVersion!==null);if(t.nodeTrees.length>0){let u=t.pathWinner?.node??null,p=t.nodeTrees.find(m=>m.node===u);if(t.pathWinner===null?e.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&&e.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${p.node} tree (${p.bridgeVersion??"?"}).`}),t.nvmDefault!==null){let m=t.nodeTrees.find(g=>g.node===t.nvmDefault);m&&m.bridgeVersion===null&&e.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:Bn(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(g=>Bc(g.bridgeVersion,r)<0))e.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:Bn(r,m.node)})}let s=!1,o=new Map,c=a((u,p)=>{let h=o.get(u)??{version:t.installVersionOf(u),clients:[]};h.clients.push(p),o.set(u,h)},"noteInstall");for(let u of t.clientConfigs){let p=DR(u);if(p===null)continue;if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(g=>g.includes($r))){e.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:`${Bn(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(!t.fileExists(g)){e.push({check:"client-config",level:"error",message:`${u.label} runs ${g}, which does not exist.`,fix:`re-run \`npx -y ${$r}@${r} install\` to rewrite the entry`});continue}c(g,u.label)}else if(p.command.includes("/")||p.command.includes("\\")){if(!t.fileExists(p.command)){e.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 ${Bn(r)})`});continue}}else if(p.command==="maind-mcp-bridge"&&t.pathWinner===null){e.push({check:"client-config",level:"error",message:`${u.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:Bn(r,t.nvmDefault)});continue}m||(p.command.includes("/")||p.command.includes("\\")?c(p.command,u.label):p.command==="maind-mcp-bridge"&&t.pathWinner&&c(t.pathWinner.path,u.label)),e.push({check:"client-config",level:"ok",message:`${u.label}: ${[p.command,...p.args].join(" ")}`})}if(s||e.push({check:"client-config",level:"warn",message:"no MCP client config names a `maind` server.",fix:`npx -y ${$r} install`}),t.latestVersion!==null)for(let[u,p]of o){let h=p.clients.join(", ");if(p.version===null)e.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${u} is.`});else if(Bc(p.version,t.latestVersion)<0){let m=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(u)?.[1]??null;e.push({check:"version",level:"warn",message:`${h} run bridge ${p.version} (${u}); published is ${t.latestVersion}. An installed bridge never updates itself.`,fix:m?Bn(t.latestVersion,m):`npx -y ${$r}@${t.latestVersion} install`})}else e.push({check:"version",level:"ok",message:`${h} run bridge ${p.version} (published: ${t.latestVersion}).`})}for(let{dir:u,maind:p}of t.npxStaleDirs)e.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=t.envApiKey??t.apiKey;(t.deviceId===null||!Bg.test(t.deviceId))&&e.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?e.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):OR.test(l)?e.push({check:"credentials",level:t.deviceId!==null&&Bg.test(t.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${t.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.`}):e.push({check:"credentials",level:"error",message:`the ${t.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:t.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=t.connection;if(d===null?e.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"?e.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):e.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"}),t.claudeSettings!==null){let u=Wt(t.claudeSettings,{fileExists:a(h=>t.fileExists(h),"fileExists")}),p=t.pathWinner?t.installVersionOf(t.pathWinner.path):null;for(let h of u){if(h.status==="missing")continue;if(h.status!=="ok"){e.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?t.installVersionOf(m):null;g!==null&&p!==null&&g!==p&&e.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: ${t.pathWinner?.path??"maind-mcp-bridge"} ${h.subcommand}`})}e.some(h=>h.check==="hooks")||e.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}return e}function Kg(t){let e=t.filter(i=>i.level==="error"&&Kc.includes(i.check)).sort((i,s)=>Kc.indexOf(i.check)-Kc.indexOf(s.check)),n=e[0];if(n===void 0)return null;let r=e.length>1?` ${e.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 Vg(t){let e={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...t].sort((o,c)=>n[o.level]-n[c.level]).flatMap(o=>[`${e[o.level]} [${o.check}] ${o.message}`,...o.fix?[` fix: ${o.fix}`]:[]]),i=t.filter(o=>o.level==="error").length,s=t.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(`
|
|
138
170
|
`)+`
|
|
139
|
-
`}var
|
|
140
|
-
`):process.stdout.write(
|
|
141
|
-
`).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await
|
|
142
|
-
`))!==-1;){let
|
|
171
|
+
`}var $r,OR,Bg,Kc,Vc=b(()=>{"use strict";On();$r="@maind-dev/mcp-bridge",OR=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,Bg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Bc,"compareVersions");a(DR,"maindEntry");a(Bn,"installFix");a(As,"diagnose");Kc=["connection","client-config","npx-cache","hooks"];a(Kg,"sessionStartLine");a(Vg,"renderFindings")});var Jg={};oe(Jg,{realProbe:()=>Is,resolveNvmAlias:()=>Yg,runDoctor:()=>BR});import{execFileSync as MR}from"node:child_process";import{existsSync as Yc,readFileSync as PR,readdirSync as zc,realpathSync as LR}from"node:fs";import{homedir as Fr,platform as Ns}from"node:os";import{delimiter as $R,dirname as zg,join as se}from"node:path";function zt(t){try{return Yc(t)?PR(t,"utf8"):null}catch{return null}}function FR(){try{let t=MR(Ns()==="win32"?"npm.cmd":"npm",["view",qg,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(t)?t:null}catch{return null}}function qc(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:se(Fr(),".nvm")}function jR(){let t=se(qc(),"versions","node"),e=[];try{e=zc(t).filter(n=>n.startsWith("v"))}catch{return[]}return e.map(n=>{let r=zt(se(t,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 Yg(t,e,n){let r=t.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...e].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(e.includes(s))return s;let o=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(o)).at(-1)??null}function UR(t){let e=zt(se(qc(),"alias","default"));return e===null?null:Yg(e,t.map(n=>n.node),n=>{let r=zt(se(qc(),"alias",n));return r===null?null:r})}function HR(){let t=Ns()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let e of(process.env.PATH??"").split($R))if(e)for(let n of t){let r=se(e,n);if(Yc(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function WR(){let t=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Ns()==="win32"?se(process.env.LOCALAPPDATA??se(Fr(),"AppData","Local"),"npm-cache"):se(Fr(),".npm"),e=se(t,"_npx"),n=[],r=[];try{r=zc(e)}catch{return[]}for(let i of r)try{let s=zc(se(e,i,"node_modules"));s.some(o=>o.startsWith(".better-sqlite3-"))&&n.push({dir:se(e,i),maind:s.includes("@maind-dev")})}catch{}return n}function GR(t){let e;try{e=zg(LR(t))}catch{return null}for(let n=0;n<6;n++){let r=zt(se(e,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===qg)return s.version??null}catch{}let i=zg(e);if(i===e)break;e=i}return null}function Is(t=process.cwd(),e={}){let n=jR(),r=zt(se(be(),"device-id")),i=Ji({projectRoot:t,homeDir:Fr(),platform:Ns(),env:process.env}),s=null;try{s=K()}catch{s=null}let o=(process.env.MAIND_API_KEY??"").trim();return{runningVersion:U,latestVersion:e.offline===!0?null:FR(),nodeTrees:n,nvmDefault:UR(n),pathWinner:HR(),clientConfigs:Yi(i).map(c=>({label:c.label,path:c.path,kind:c.kind,raw:zt(c.path)})),npxStaleDirs:WR(),connection:ym(),claudeSettings:zt(se(Fr(),".claude","settings.json")),fileExists:a(c=>Yc(c),"fileExists"),installVersionOf:GR,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:o.length>0?o:null}}async function BR(t){let e=As(Is());return t.includes("--json")?process.stdout.write(JSON.stringify({version:U,findings:e},null,2)+`
|
|
172
|
+
`):process.stdout.write(Vg(e)),e.some(n=>n.level==="error")?1:0}var qg,Jc=b(()=>{"use strict";Ba();re();Va();st();Vc();qg="@maind-dev/mcp-bridge";a(zt,"readOrNull");a(FR,"latestVersion");a(qc,"nvmDir");a(jR,"nodeTrees");a(Yg,"resolveNvmAlias");a(UR,"nvmDefault");a(HR,"pathWinner");a(WR,"npxStaleDirs");a(GR,"installVersionOf");a(Is,"realProbe");a(BR,"runDoctor")});async function Xg(t){return qt("get_session_briefing",{tools:["claude-code"]},t)}async function qt(t,e,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Xc,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:KR,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let d={...o,"mcp-session-id":l};await fetch(r,{method:"POST",headers:d,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(y=>y.text().catch(()=>"")).catch(()=>"");let u=await fetch(r,{method:"POST",headers:d,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:t,arguments:e}})});if(!u.ok)return null;let h=(u.headers.get("content-type")??"").startsWith("text/event-stream")?await VR(u):await u.text();if(h.trim().length===0)return null;let m=JSON.parse(h);if(m.error||m.result?.isError)return null;let g=m.result?.content?.find(y=>y.type==="text"&&typeof y.text=="string")?.text;return typeof g=="string"&&g.trim().length>0?g:null}catch{return null}finally{clearTimeout(s)}}async function VR(t){if(!t.body)return"";let e=t.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 e.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 Xc,KR,jr=b(()=>{"use strict";Xc="https://mcp.maind.dev/mcp",KR="2025-06-18";a(Xg,"fetchSessionBriefing");a(qt,"fetchToolText");a(VR,"readSseMessage")});function zR(t){return{"content-type":"application/json",authorization:`Bearer ${t}`,"x-maind-device-id":ne()}}async function Zg(t,e,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(t,{method:"POST",headers:zR(e),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 Cs,Zc=b(()=>{"use strict";re();An();Cs=process.env.MAIND_ENDPOINT??Rn("mcp-client-metrics-ingest");a(zR,"ingestHeaders");a(Zg,"postMetrics")});function Qg(t,e){return t===e||t===""||e===""?!0:t.startsWith(e+"/")||e.startsWith(t+"/")}function ty(t,e){let n=[];for(let r of t.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)-e;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 Kn(t,e){if(e.hostPids.length>0){let r=t.find(i=>e.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=t.find(r=>r.cwd===e.cwd);return n?{snap:n,via:"cwd"}:null}function Ur(t){return t<90?`${Math.max(1,Math.round(t))}s`:`${Math.round(t/60)}m`}function ny(t,e,n){let r=n.maxAgeMs??ey,i=n.nowMs-Date.parse(t.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,o=ty(t,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)Qg(e,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 ${Ur(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Ur(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Qg(e,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Ur(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${e}' overlaps parallel work (view as of ${Ur(s)} ago, advisory \u2014 never a lock):
|
|
143
175
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
144
176
|
`)+`
|
|
145
|
-
Verify live before large edits: check_path_conflicts({project_key: "${
|
|
146
|
-
${m}`:m}var
|
|
147
|
-
`),
|
|
177
|
+
Verify live before large edits: check_path_conflicts({project_key: "${t.project_key}", paths: ["${e}"]}) \u2014 then claim_paths for your own edit area.`}function ry(t,e){let n=typeof t?.own_session_id=="string"?t.own_session_id.toLowerCase():null,r=e!==null?e.toLowerCase():null;return r!==null&&n!==null&&n!==r?{id:r,announceError:null}:{id:t?.own_session_id??null,announceError:t?.announce_error??null}}function iy(t,e,n,r=ey,i=null){if(!t)return null;let s=n-Date.parse(t.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let o=s/1e3,c=ty(t,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.`:e!==null?`[maind] your coordination session: ${e} \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 ${Ur(o)} ago \u2014 before large edits: check_path_conflicts({project_key: "${t.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
178
|
+
${m}`:m}var ey,Qc=b(()=>{"use strict";a(Qg,"prefixConflict");ey=10*6e4;a(ty,"parsePeers");a(Kn,"selectOwnSnapshot");a(Ur,"ageDisplay");a(ny,"adviseOnPath");a(ry,"claimedIdentity");a(iy,"sessionStartSummary")});async function G(){if(process.stdin.isTTY)return{};let t=[];return await new Promise(e=>{let n=!1,r=a(s=>{n||(n=!0,clearTimeout(i),e(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>t.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(t).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function Vn(t){return typeof t.transcript_path=="string"?t.transcript_path:""}function De(t){let e=t.tool_input;if(e===null||typeof e!="object")return"";let n=e.file_path;return typeof n=="string"?n:""}var Me=b(()=>{"use strict";a(G,"readHookInput");a(Vn,"transcriptPathOf");a(De,"toolFilePathOf")});function zn(t){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t}})}function ft(t){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t}})}function sy(t){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:t}})}var qn=b(()=>{"use strict";a(zn,"denyPayload");a(ft,"advisoryPayload");a(sy,"postAdvisoryPayload")});import{realpathSync as qR}from"node:fs";import{basename as oy,dirname as ay,join as YR}from"node:path";function Yt(t){let e=ay(t),n=[oy(t)];for(;;)try{let r=qR(e);return YR(r,...n.reverse())}catch{let r=ay(e);if(r===e)return t;n.push(oy(e)),e=r}}var Os=b(()=>{"use strict";a(Yt,"realpathOfUnwritten")});import{mkdir as JR,readFile as XR,writeFile as ZR,rename as QR}from"node:fs/promises";import{existsSync as ly}from"node:fs";import{homedir as eA}from"node:os";import{join as dy}from"node:path";function cy(){return{config:null,sessions:{},pending_metrics:[]}}async function X(){if(!ly(Ds))return cy();try{let t=await XR(Ds,"utf-8"),e=JSON.parse(t);return{config:e.config??null,sessions:e.sessions??{},pending_metrics:Array.isArray(e.pending_metrics)?e.pending_metrics:[],thresholds:e.thresholds,thresholds_synced_at:e.thresholds_synced_at,guard_signals:e.guard_signals,repo_health_seen:e.repo_health_seen,write_health_seen:e.write_health_seen}}catch(t){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${t instanceof Error?t.message:String(t)}
|
|
179
|
+
`),cy()}}async function Pe(t){ly(Jt)||await JR(Jt,{recursive:!0,mode:448});let e=`${Ds}.tmp`;await ZR(e,JSON.stringify(t,null,2),{mode:384}),await QR(e,Ds)}function el(t){return t.thresholds??t.config?.thresholds??tA}var Jt,Ds,tA,Xt=b(()=>{"use strict";Jt=dy(eA(),".maind"),Ds=dy(Jt,"state.json"),tA={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};a(cy,"emptyState");a(X,"loadState");a(Pe,"saveState");a(el,"resolveThresholds")});import{existsSync as nA,realpathSync as rA,statSync as iA}from"node:fs";import{dirname as uy,isAbsolute as sA,join as oA}from"node:path";function lA(t,e){let n=t.filter(i=>py.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
|
|
148
180
|
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
149
|
-
${i.detail}${s}`});return`maind repo-health (${
|
|
181
|
+
${i.detail}${s}`});return`maind repo-health (${e}) \u2014 checked once per session, before your first edit here:
|
|
150
182
|
|
|
151
183
|
`+r.join(`
|
|
152
184
|
|
|
153
185
|
`)+`
|
|
154
186
|
|
|
155
|
-
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
|
|
187
|
+
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 dA(t,e,n){return t.repo_health_seen?.[e]?.[n]!==void 0}function uA(t,e,n,r=Date.now()){let i=t.repo_health_seen??{},s=i[e]??{};s[n]=new Date(r).toISOString(),i[e]=s,t.repo_health_seen=i}function tl(t){let e=uy(t);for(;;){try{if(iA(e).isDirectory())return e}catch{}let n=uy(e);if(n===e)return e;e=n}}async function pA(t,e,n){let r=await n.load();if(dA(r,t,e))return null;uA(r,t,e,n.now?.()),await n.save(r);let i;try{i=await n.check(e)}catch{return null}let s=i.filter(c=>py.includes(c.id)).length,o=await n.load();return o.pending_metrics.push({session_id:t,metric_key:aA,metric_value:1},{session_id:t,metric_key:cA,metric_value:s}),await n.save(o),lA(i,e)}async function fy(){try{let t=await G(),e=(t.tool_name??"").toString();if(e!=="Edit"&&e!=="Write")return 0;let n=typeof t.session_id=="string"?t.session_id:"";if(!n)return 0;let r=De(t);if(!r)return 0;let i=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),s=sA(r)?r:oA(i,r),o=nA(s)?rA(s):Yt(s),c=Be(tl(o)),l=await pA(n,c,{load:X,save:Pe,check:a(async d=>(await pr(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(ft(l)),0}catch{return 0}}var py,aA,cA,nl=b(()=>{"use strict";En();Tn();qn();Me();Os();Xt();py=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],aA="repo_health_hook_runs",cA="repo_health_hook_findings";a(lA,"formatRepoHealth");a(dA,"alreadySeen");a(uA,"markSeen");a(tl,"nearestExistingDir");a(pA,"repoHealthForEdit");a(fy,"runOnRepoHealth")});import{existsSync as fA,readFileSync as mA,realpathSync as hA}from"node:fs";import{isAbsolute as hy,join as gy,posix as gA,relative as yA,sep as _A}from"node:path";function my(t){if(t===null||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function xA(t,e){return{contracts:e.filter(r=>my(r.spec)===t||my(r.impl)===t).map(r=>r.id),theme:vA.test(t),acl:kA.test(t)}}function SA(t){return t.contracts.length===0&&!t.theme&&!t.acl}function EA(t,e,n,r,i=Date.now()){let s=t.write_health_seen??{},o=s[e]??{},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[e]=o,t.write_health_seen=s}return l}function TA(t,e){return t.length===0?null:`maind write-health \u2014 your edit to ${e} makes these checks relevant, and each finding below is reported once per session:
|
|
156
188
|
|
|
157
|
-
`+
|
|
189
|
+
`+t.map(n=>` \u2022 ${n.line}`).join(`
|
|
158
190
|
`)+`
|
|
159
191
|
|
|
160
|
-
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
|
|
161
|
-
`)}catch{}let
|
|
162
|
-
`)}}catch{}try{let r
|
|
163
|
-
`)}}catch{}return 0}function
|
|
164
|
-
`);return`${
|
|
192
|
+
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 RA(t,e){let n=yA(t,e);return!n||n.startsWith("..")||hy(n)?null:n.split(_A).join(gA.sep)}function AA(t){try{let e=mA(gy(t,xi),"utf8"),{manifest:n}=Ri(e);return n?.contracts??[]}catch{return[]}}async function yy(){try{let t=await G(),e=(t.tool_name??"").toString();if(e!=="Edit"&&e!=="Write")return 0;let n=typeof t.session_id=="string"?t.session_id:"",r=De(t);if(!n||!r)return 0;let i=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),s=hy(r)?r:gy(i,r),o=fA(s)?hA(s):Yt(s),c=Be(tl(o)),l=RA(c,o);if(l===null)return 0;let d=xA(l,AA(c));if(SA(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await Dt(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=Pt(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=Mt(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 X(),h=EA(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:bA,metric_value:1},{session_id:n,metric_key:wA,metric_value:h.length}),await Pe(p);let m=TA(h,l);return m!==null&&process.stdout.write(sy(m)),0}catch{return 0}}var bA,wA,vA,kA,_y=b(()=>{"use strict";En();Tn();qn();Me();nl();Os();Xt();bA="write_health_hook_runs",wA="write_health_hook_findings",vA=/\.(tsx?|jsx?|css)$/,kA=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;a(my,"declPath");a(xA,"routesForPath");a(SA,"routesAreEmpty");a(EA,"takeUnreported");a(TA,"formatWriteHealth");a(RA,"repoRelative");a(AA,"readContracts");a(yy,"runOnWriteHealth")});var Iy={};oe(Iy,{agentHostPidCandidates:()=>qe,closeTrackedSession:()=>Ey,effectiveConfig:()=>Zt,grandparentPid:()=>Ry,recordGuardSignals:()=>Sy,runFlush:()=>BA,runHookStatus:()=>KA,runOnFileEdit:()=>HA,runOnFileWrite:()=>UA,runOnRepoHealth:()=>fy,runOnSessionStart:()=>PA,runOnToolUse:()=>FA,runOnWriteHealth:()=>yy,runSessionEndMetrics:()=>il,runSyncConfig:()=>zA,writeIdentitySideChannel:()=>rl});import{execFileSync as wy}from"node:child_process";import{existsSync as Ls,readFileSync as vy,realpathSync as NA}from"node:fs";import{writeFile as IA}from"node:fs/promises";import{homedir as ky}from"node:os";import{isAbsolute as Ps,join as Hr,relative as xy}from"node:path";function Sy(t,e,n,r=Date.now()){if(!n.includes("maind"))return;let i=n.includes("search_lessons")||n.includes("get_session_briefing")||n.includes("get_lesson")||n.includes("get_conventions")||n.includes("activate_skill")||n.includes("suggest_skills")||n.includes("codebase_change_briefing"),s=n.includes("review_changes");if(!i&&!s)return;let o=t.guard_signals??{},c=o[e]??{},l=new Date(r).toISOString();i&&(c.consulted_at=l),s&&(c.reviewed_at=l),o[e]=c,t.guard_signals=o}function Ey(t,e,n=Date.now()){MA(t,n);let r=t.sessions[e];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return t.pending_metrics.push({session_id:e,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:e,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:e,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete t.sessions[e],!0}function MA(t,e){if(t.guard_signals)for(let[n,r]of Object.entries(t.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0);e-i>Ms&&delete t.guard_signals[n]}if(t.repo_health_seen)for(let[n,r]of Object.entries(t.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));e-i>Ms&&delete t.repo_health_seen[n]}if(t.write_health_seen)for(let[n,r]of Object.entries(t.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));e-i>Ms&&delete t.write_health_seen[n]}for(let[n,r]of Object.entries(t.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&e-i>Ms&&delete t.sessions[n]}}function Zt(t){if(t.config)return t.config;let e=K();return e===null?null:{api_key:e,endpoint:Cs}}function Ty(t,e){let n=t.sessions[e];return n||(n={session_id:e,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},t.sessions[e]=n),n}async function PA(){try{let r=Kg(As(Is(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
|
|
193
|
+
`)}catch{}let t=await X();if(Zt(t)===null)return 0;let e=await G(),n=Ny(e);if(n===null)return 0;Ty(t,n),await Pe(t);try{rl(e,n)}catch{}try{let r=z();if(r!==null){let i=jn(r),s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Kn(i,{hostPids:qe(),cwd:s}),c=ry(o?.snap??null,Mr(Vn(e)||null,n)),l=iy(o?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
|
|
194
|
+
`)}}catch{}try{let r=Wt(LA());if(Za(r)&&es(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).
|
|
195
|
+
`)}}catch{}return 0}function LA(){try{let t=Hr(ky(),".claude","settings.json");return Ls(t)?vy(t,"utf8"):null}catch{return null}}function rl(t,e,n,r=Un()){let i=n??qe();if(i.length===0)return;let s=Mr(Vn(t)||null,e);if(s===null)return;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),c=Vn(t)||void 0,l=typeof t.model=="string"&&t.model.trim().length>0?t.model.trim():void 0;for(let d of i)pg({dir:r,agentPid:d,sessionId:e,transcriptStem:s,cwd:o,transcriptPath:c,model:l})}function Ry(){try{if(process.platform==="win32")return null;let t=wy("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),e=Number.parseInt(t.trim(),10);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function qe(){let t=[],e=process.ppid;Number.isFinite(e)&&e>1&&t.push(e);let n=Ry();return n!==null&&n>1&&n!==e&&t.push(n),t}async function FA(){let t=await X();if(Zt(t)===null)return 0;let e=await G(),n=Ny(e)??"unknown",r=Ty(t,n);r.tool_call_count+=1;try{let o=qe().filter(c=>fg(Un(),c,$A));n!=="unknown"&&o.length>0&&rl(e,n,o)}catch{}let i=(e.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Sy(t,n,i);let s=e.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let o=await Sc(r.transcript_path);o&&(r.token_count=o.total_tokens,await GA(t,r))}return await Pe(t),0}function jA(t,e){let n=t.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
196
|
+
`);return`${e.prefix}${t.number} is already taken:
|
|
165
197
|
${n}
|
|
166
198
|
|
|
167
|
-
Next free number in ${
|
|
199
|
+
Next free number in ${e.dir}: ${e.prefix}${t.suggestion}. Write the file under that number instead.
|
|
168
200
|
|
|
169
|
-
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
|
|
170
|
-
`)}s==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${
|
|
171
|
-
`):process.stderr.write(`[maind] \u26D4 Token usage at ~${
|
|
172
|
-
`)}async function
|
|
173
|
-
`)}}async function
|
|
174
|
-
`),n.ok?0:1}async function
|
|
201
|
+
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 UA(){try{let t=await G();if((t.tool_name??"")!=="Write")return 0;let e=De(t);if(!e)return 0;let n=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),r=Ps(e)?e:Hr(n,e);if(Ls(r))return 0;let i=Be(n),s=xy(i,Yt(r));if(s.length===0||s.startsWith("..")||Ps(s))return 0;let o=await Ot(i,s);return!o.taken||o.namespace===null||process.stdout.write(zn(jA(o,o.namespace))),0}catch{return 0}}async function HA(){try{let t=await G(),e=(t.tool_name??"").toString();if(e!=="Edit"&&e!=="Write")return 0;let n=De(t);if(!n)return 0;let r=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),i=Ps(n)?n:Hr(r,n),s=z();if(s===null)return 0;let o=jn(s);if(o.length===0)return 0;let c=Kn(o,{hostPids:qe(),cwd:r});if(c===null)return 0;let l=Be(r),d=Ls(i)?NA(i):Yt(i),u=xy(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||Ps(u))return 0;let p=ny(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?WA(r):null,nowMs:Date.now()});return p===null||process.stdout.write(ft(p)),0}catch{return 0}}function WA(t){try{let n=wy("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function GA(t,e){let n=el(t),r=e.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"),e.last_advisory_status===s||(e.last_advisory_status=s,s==="ok"))return;let o=Math.round(i*100),c={session_id:e.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 IA(Hr(Jt,`handoff_advisory_${e.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)}
|
|
202
|
+
`)}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.
|
|
203
|
+
`):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.
|
|
204
|
+
`)}async function il(t){try{let e=await X(),n=Zt(e);if(n===null)return;let r=t??Object.keys(e.sessions)[0];r&&e.sessions[r]&&(Ey(e,r),await Pe(e)),await Ay(n,OA)}catch(e){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${e instanceof Error?e.message:String(e)}
|
|
205
|
+
`)}}async function BA(){let t=await X(),e=Zt(t);if(e===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await Ay(e,DA);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
206
|
+
`),n.ok?0:1}async function Ay(t,e){let n=await X();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=Zg(t.endpoint,t.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),e)),o=await Promise.race([i,s]);if(o.ok){let c=await X();return c.pending_metrics=c.pending_metrics.slice(r.length),await Pe(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 KA(){let t=await X(),e=Zt(t),n=VA(),r=Za(n.findings);if(process.stdout.write(JSON.stringify({paired:e!==null,source:t.config?"maind-hook init (legacy)":"bridge credential",endpoint:e?.endpoint??null,api_key_prefix:e?e.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(t.sessions).length,pending_metrics:t.pending_metrics.length,thresholds:el(t),thresholds_synced_at:t.thresholds_synced_at??t.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})),...es(n.findings)?{remedy:by}:{}}},null,2)+`
|
|
175
207
|
`),r){process.stderr.write(`
|
|
176
208
|
[maind] Claude Code hook wiring is incomplete:
|
|
177
209
|
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
178
|
-
`);
|
|
179
|
-
`)}return 0}function
|
|
210
|
+
`);es(n.findings)&&process.stderr.write(` ${by}
|
|
211
|
+
`)}return 0}function VA(){let t=Hr(ky(),".claude","settings.json"),e=null;try{Ls(t)&&(e=vy(t,"utf8"))}catch{}return{settingsPath:t,findings:Wt(e)}}async function zA(){let t=await X(),e=Zt(t);if(e===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=e.thresholds_endpoint??CA,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.api_key}`}})}catch(o){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${o instanceof Error?o.message:String(o)}
|
|
180
212
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
181
|
-
`);let
|
|
213
|
+
`);let o=await r.text().catch(()=>"");return o&&process.stderr.write(o.slice(0,500)+`
|
|
182
214
|
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
183
215
|
`),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
|
|
184
|
-
`),1):(
|
|
185
|
-
`),0)}function
|
|
186
|
-
`)}).catch(()=>{}),
|
|
187
|
-
`)}return await
|
|
188
|
-
`,384)}var
|
|
189
|
-
`),1;let i={homeDir:
|
|
190
|
-
`);let
|
|
216
|
+
`),1):(t.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},t.thresholds_synced_at=new Date().toISOString(),await Pe(t),process.stdout.write(JSON.stringify({ok:!0,thresholds:t.thresholds,synced_at:t.thresholds_synced_at},null,2)+`
|
|
217
|
+
`),0)}function Ny(t){let e=typeof t.session_id=="string"?t.session_id.trim():"";return e.length>0?e:null}var CA,OA,DA,Ms,$A,by,sl=b(()=>{"use strict";Gn();En();Tn();re();On();ys();ot();Zc();Qc();bs();Me();qn();Os();Xt();An();Vc();Jc();nl();_y();CA=process.env.MAIND_THRESHOLDS_ENDPOINT??Rn("get-context-thresholds"),OA=1500,DA=1e4,Ms=7*24*60*60*1e3;a(Sy,"recordGuardSignals");a(Ey,"closeTrackedSession");a(MA,"gcState");a(Zt,"effectiveConfig");a(Ty,"getOrCreateSession");a(PA,"runOnSessionStart");a(LA,"readSettingsRaw");a(rl,"writeIdentitySideChannel");$A=6e4;a(Ry,"grandparentPid");a(qe,"agentHostPidCandidates");a(FA,"runOnToolUse");a(jA,"denyReason");a(UA,"runOnFileWrite");a(HA,"runOnFileEdit");a(WA,"currentGitBranch");a(GA,"maybeEmitAdvisory");a(il,"runSessionEndMetrics");a(BA,"runFlush");a(Ay,"flushPending");a(KA,"runHookStatus");by="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(VA,"readHookWiring");a(zA,"runSyncConfig");a(Ny,"sessionIdOf")});function Cy(t){return t.ownSnapshotAgeMs!==null&&t.ownSnapshotAgeMs<=18e5||t.sawMaindCall?"connected":t.presenceUsable?"not_connected":"unknown"}var Oy=b(()=>{"use strict";a(Cy,"resolveConnection")});function My(t,e,n,r=Date.now()){let i=e===null?null:Pc(e),s=Fc(t,i,{repoRoot:n,nowMs:r});return s.length===0?null:{slices:s,context_ok:i!==null}}var Dy,ol=b(()=>{"use strict";Gn();Dy=2e3;a(My,"buildCostPayload")});function Ly(t,e=null){if(!t||t.announce_error!=null)return null;let n=t.own_session_id;if(typeof n!="string"||!Py.test(n))return null;let r=n.toLowerCase();return e!==null&&Py.test(e)&&r!==e.toLowerCase()?null:r}var Py,$y=b(()=>{"use strict";Py=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Ly,"snapshotSessionId")});async function Fy(t){let e=t.now??Date.now,n=t.fetchContext(t.projectKey),{turns:r}=await Lr(t.transcriptPath),i=t.resolveRoot?jc(r,t.resolveRoot):null,s=i&&t.projectKeyOf?t.projectKeyOf(i):null,o=i!==null&&s!==null&&s!==t.projectKey;o&&n.catch(()=>{});let[c,l,d]=await Promise.all([Tc(t.transcriptPath,{turns:r}),Uc(t.transcriptPath),o?t.fetchContext(s):n]),u=i??t.repoRoot;if(t.sessionId&&(c.session_id=t.sessionId,l.session_id=t.sessionId),c.maind_connected=t.connection(c.maind_connected==="connected",e()),!c.session_id)return{posted:!1,contextOk:d!==null,sentSlices:!1};let p=My(r,d,u,e()),h=Nc(c,l,{client_session_id:t.coordSessionId,client:"claude-code"},"live_bridge",p);return await t.post(h,p!==null),{posted:!0,contextOk:p?.context_ok??d!==null,sentSlices:p!==null}}var jy=b(()=>{"use strict";Gn();ol();a(Fy,"ingestSessionEnd")});var Wy={};oe(Wy,{runOnSessionEnd:()=>nN});import{execFileSync as al}from"node:child_process";function YA(t,e){try{let n=z(),r=n!==null&&!_c(process.env,Oe()),i=null;if(n!==null){let s=Kn(jn(n),{hostPids:qe(),cwd:process.cwd()});if(s){let o=Date.parse(s.snap.written_at);i=Number.isFinite(o)?Math.max(0,e-o):null}}return Cy({ownSnapshotAgeMs:i,sawMaindCall:t,presenceUsable:r})}catch{return t?"connected":"unknown"}}function JA(t){let e=/^[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=Kn(jn(r),{hostPids:qe(),cwd:process.cwd()}),s=Ly(i?.snap,t);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(n)?n:null}function XA(){try{let t=al("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return t.length>0?t:null}catch{return null}}function ZA(t){let e=Uy.get(t);if(e!==void 0)return e;let n=null;try{let r=al("git",["-C",t,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return Uy.set(t,n),n}function QA(t){let e=Hy.get(t);if(e!==void 0)return e;let n=null;try{let r=al("git",["-C",t,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=Ka(r))}catch{n=null}return Hy.set(t,n),n}async function eN(t,e,n,r){if(n===null)return null;try{return await qt("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:t,deviceId:e,projectKey:n,bridgeVersion:U,timeoutMs:Dy})}catch{return null}}async function tN(t,e,n,r,i){let s=fetch(qA,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`,"x-maind-device-id":e,"x-maind-bridge-version":U},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=Ac(Rc(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
|
|
218
|
+
`)}).catch(()=>{}),o=new Promise(c=>setTimeout(c,r));await Promise.race([s,o])}async function nN(){try{for(let i of qe())mg(Un(),i)}catch{}let t=K();if(!t)return 0;let e=await G(),n=typeof e.session_id=="string"&&e.session_id?e.session_id:null,r=Vn(e);if(r)try{let i=ne(),s=JA(Mr(r,n)),o=z();await Fy({apiKey:t,deviceId:i,sessionId:n,transcriptPath:r,projectKey:o,coordSessionId:s,repoRoot:XA(),resolveRoot:ZA,projectKeyOf:QA,fetchContext:a(c=>eN(t,i,c,s),"fetchContext"),post:a((c,l)=>tN(t,i,c,1500,l),"post"),connection:YA})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
219
|
+
`)}return await il(n),0}var qA,Uy,Hy,Gy=b(()=>{"use strict";Gn();Dn();re();jr();Zc();Qc();Me();sl();bc();ys();ot();bs();st();Oy();ol();$y();jy();qA=Cs;a(YA,"connectionVerdict");a(JA,"presenceSessionId");a(XA,"sessionRepoRoot");Uy=new Map;a(ZA,"gitRootOf");Hy=new Map;a(QA,"projectKeyOfRoot");a(eN,"fetchCostContext");a(tN,"postWithTimeout");a(nN,"runOnSessionEnd")});function ve(t=process.env,e=Oe()){let n=t.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:e?.guard_mode??"off",stopGate:e?.guard_stop_gate===!0}}async function Yn(t,e=ze()){let n={};try{let i=await ie(e);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,...t};await Y(e,JSON.stringify(r,null,2)+`
|
|
220
|
+
`,384)}var Qt=b(()=>{"use strict";Dn();Ke();a(ve,"resolveGuardConfig");a(Yn,"writeGuardConfig")});function rN(t){let e={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<t.length;n++)switch(t[n]){case"--mode":{let i=t[++n];if(i!=="warn"&&i!=="block")return null;e.mode=i;break}case"--stop-gate":e.stopGate=!0;break;case"--full":case"--yes":e.full=!0;break;case"--dry-run":e.dryRun=!0;break;default:return null}return e}async function By(t,e,n=process.stdout){let r=rN(t);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
221
|
+
`),1;let i={homeDir:e,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of Qi)s.push(await nc(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
222
|
+
`);let o=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
191
223
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
192
|
-
`),0):(await
|
|
224
|
+
`),0):(await Yn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
193
225
|
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
194
226
|
flip: maind-mcp-bridge guard mode <warn|block>
|
|
195
227
|
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
196
228
|
check: maind-mcp-bridge guard status
|
|
197
229
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
198
|
-
`),
|
|
199
|
-
`),c?1:0)}var
|
|
200
|
-
`;await
|
|
201
|
-
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let
|
|
202
|
-
`),1):(await
|
|
203
|
-
`),0)}case"off":return await
|
|
230
|
+
`),o&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
231
|
+
`),c?1:0)}var Ky=b(()=>{"use strict";On();rc();Qt();a(rN,"parseGuardInstallFlags");a(By,"runGuardInstall")});import{existsSync as Vy}from"node:fs";import{mkdir as iN,readFile as sN,readdir as oN,rename as aN,stat as cN,unlink as lN,writeFile as dN}from"node:fs/promises";import{join as $s}from"node:path";function zy(t){return $s(Wr,t.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function Ye(t){try{let e=zy(t);if(!Vy(e))return{};let n=JSON.parse(await sN(e,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function me(t,e){await iN(Wr,{recursive:!0,mode:448});let n=zy(t),r=`${n}.tmp`;await dN(r,JSON.stringify({...e,updated_at:new Date().toISOString()},null,2),{mode:384}),await aN(r,n)}async function qy(t=7*24*60*60*1e3,e=Date.now()){try{if(!Vy(Wr))return;for(let n of await oN(Wr)){if(!n.endsWith(".json"))continue;let r=$s(Wr,n);try{let i=await cN(r);e-i.mtimeMs>t&&await lN(r)}catch{}}}catch{}}var Jn,Wr,Xn=b(()=>{"use strict";Xt();Jn=$s(Jt,"guard"),Wr=$s(Jn,"sessions");a(zy,"sessionFile");a(Ye,"loadGuardSession");a(me,"saveGuardSession");a(qy,"sweepOldGuardSessions")});import{existsSync as uN}from"node:fs";import{appendFile as pN,mkdir as fN,open as mN}from"node:fs/promises";import{join as hN}from"node:path";async function le(t){try{await fN(Jn,{recursive:!0,mode:448});let e=JSON.stringify({ts:new Date().toISOString(),...t})+`
|
|
232
|
+
`;await pN(Zn,e,{mode:384})}catch{}}async function Yy(t=256*1024){let e={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};try{if(!uN(Zn))return e;let n=await mN(Zn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-t),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
|
|
233
|
+
`);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 e&&(e[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return e}var Zn,Qn=b(()=>{"use strict";Xn();Zn=hN(Jn,"events.jsonl");a(le,"appendGuardEvent");a(Yy,"readGuardEventCounts")});var Xy={};oe(Xy,{runGuard:()=>wN});import{existsSync as gN,readFileSync as yN}from"node:fs";import{homedir as Jy}from"node:os";import{join as _N}from"node:path";async function wN(t){let e=t[0],n=t.slice(1);switch(e){case"install":return By(n,Jy());case"status":return kN();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
234
|
+
`),1):(await Yn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
235
|
+
`),0)}case"off":return await Yn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
204
236
|
`),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>
|
|
205
|
-
`),1):(await
|
|
206
|
-
`),0)}case"skip":return
|
|
207
|
-
`),1;let r=n.trim().slice(0,500),i=await
|
|
208
|
-
logged (auditable) in ${
|
|
209
|
-
`),0}async function
|
|
210
|
-
`);let s=r.filter(
|
|
237
|
+
`),1):(await Yn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
238
|
+
`),0)}case"skip":return vN(n);default:return process.stdout.write(bN),e===void 0||e==="--help"||e==="-h"?0:1}}async function vN(t){let e=null,n=null;for(let s=0;s<t.length;s++)t[s]==="--session"?e=t[++s]??null:t[s]==="--reason"&&(n=t[++s]??null);if(!e||!n||n.trim().length===0)return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"
|
|
239
|
+
`),1;let r=n.trim().slice(0,500),i=await Ye(e);return await me(e,{...i,override_reason:r}),await le({event:"override",session_id:e,reason:r,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${e} \u2014 the gate opens on the next attempt.
|
|
240
|
+
logged (auditable) in ${Zn}
|
|
241
|
+
`),0}async function kN(){let t=ve(),e=_N(Jy(),".claude","settings.json"),n=null;try{gN(e)&&(n=yN(e,"utf8"))}catch{}let r=Wt(n,{},Qi),i=await Yy();process.stdout.write(JSON.stringify({mode:t.mode,stop_gate:t.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",hook_wiring:r.map(o=>({event:o.event,subcommand:o.subcommand,status:o.status,detail:o.detail})),events:i,events_file:Zn},null,2)+`
|
|
242
|
+
`);let s=r.filter(o=>o.status!=="ok");if(t.mode==="off"&&process.stderr.write("\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"),s.length>0&&t.mode!=="off"){process.stderr.write(`
|
|
211
243
|
[maind] guard hook wiring is incomplete:
|
|
212
|
-
`);for(let
|
|
213
|
-
`);s.some(
|
|
214
|
-
`);
|
|
215
|
-
`),0):(process.stdout.write(
|
|
244
|
+
`);for(let o of s)process.stderr.write(` \u2022 ${o.detail}
|
|
245
|
+
`);s.some(o=>o.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var bN,Zy=b(()=>{"use strict";On();Qt();Ky();Qn();Xn();bN=["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)",' skip --session <id> --reason "<why>"'," record a logged override for one session (block-gate exit valve)",""].join(`
|
|
246
|
+
`);a(wN,"runGuard");a(vN,"runGuardSkip");a(kN,"runGuardStatus")});var r_={};oe(r_,{BRIEFING_CACHE_FILE:()=>e_,formatInjection:()=>n_,resolveBriefingInjection:()=>t_,runGuardInject:()=>ON});import{existsSync as xN}from"node:fs";import{mkdir as SN,readFile as EN,rename as TN,writeFile as RN}from"node:fs/promises";import{dirname as AN,join as NN}from"node:path";async function t_(t,e,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??e_,s=n.fetcher??Xg,o=await DN(i);if(o!==null&&r-Date.parse(o.fetched_at)<IN&&o.project_key===t)return{text:o.text,via:"cache"};let l=await s({apiKey:e,deviceId:PN(),projectKey:t,bridgeVersion:U,timeoutMs:CN});return l!==null?(await MN(i,{fetched_at:new Date(r).toISOString(),project_key:t,text:l}),{text:l,via:"fetch"}):o!==null?{text:o.text,via:"stale-cache"}:{text:null,via:"none"}}async function ON(){try{if(ve().mode==="off")return 0;let e=await G(),n=typeof e.session_id=="string"&&e.session_id.trim().length>0?e.session_id.trim():null;if(n===null)return 0;await qy();let r=typeof e.source=="string"?e.source:"startup";if(r==="resume"||r==="compact"){let d=await Ye(n);return await me(n,{...d,carryover:!0}),0}let i=K();if(i===null)return 0;let s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=z(),c=await t_(o,i),l=await Ye(n);return c.text===null?(await me(n,{...l,inject_failed:!0}),await le({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.
|
|
247
|
+
`),0):(process.stdout.write(n_(c.text,c.via)),await me(n,{...l,injected:!0}),await le({event:"inject_ok",session_id:n,cwd:s,project_key:o??void 0,detail:c.via}),0)}catch{return 0}}function n_(t,e){let n=e==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=t;return Buffer.byteLength(r,"utf8")>Qy&&(r=r.slice(0,Qy)+`
|
|
216
248
|
\u2026 [maind guard: briefing truncated at 10KB]`),`[maind guard] Session briefing, injected deterministically (ADR-284)${n} \u2014 the session-start get_session_briefing consultation is satisfied by this block:
|
|
217
249
|
|
|
218
250
|
`+r+`
|
|
219
|
-
`}async function
|
|
251
|
+
`}async function DN(t){try{if(!xN(t))return null;let e=JSON.parse(await EN(t,"utf8"));return typeof e.fetched_at!="string"||typeof e.text!="string"||Number.isNaN(Date.parse(e.fetched_at))?null:{fetched_at:e.fetched_at,project_key:typeof e.project_key=="string"?e.project_key:null,text:e.text}}catch{return null}}async function MN(t,e){try{await SN(AN(t),{recursive:!0,mode:448});let n=`${t}.tmp`;await RN(n,JSON.stringify(e,null,2),{mode:384}),await TN(n,t)}catch{}}function PN(){try{return ne()}catch{return null}}var e_,IN,CN,Qy,i_=b(()=>{"use strict";re();Me();ot();st();Qt();Qn();Xn();jr();e_=NN(Jn,"briefing-cache.json"),IN=12*60*60*1e3,CN=3e3,Qy=10*1024;a(t_,"resolveBriefingInjection");a(ON,"runGuardInject");a(n_,"formatInjection");a(DN,"readCache");a(MN,"writeCache");a(PN,"safeDeviceId")});var c_={};oe(c_,{decideGate:()=>a_,runGuardGate:()=>$N});function a_(t){let{mode:e,session:n}=t;return e==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||t.consulted?{kind:"allow"}:e==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:s_(n)}:(n.deny_count??0)>=o_?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. "+s_(n)}:{kind:"deny",reason:LN(t.sessionId,n)}}function s_(t){return`[maind guard | warn] ${t.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 LN(t,e){return`[maind guard | block] Edit denied \u2014 ${e.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:
|
|
220
252
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
221
|
-
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${
|
|
222
|
-
After ${
|
|
223
|
-
`,{mode:384}),await
|
|
224
|
-
`).filter(r=>r.trim());if(
|
|
253
|
+
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
254
|
+
After ${o_} denies this gate downgrades itself to warn.`}async function $N(){try{let t=ve();if(t.mode==="off")return 0;let e=await G(),n=(e.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof e.session_id=="string"&&e.session_id.trim().length>0?e.session_id.trim():null;if(r===null)return 0;let i=await Ye(r),s=(await X()).guard_signals?.[r]?.consulted_at!==void 0,o=a_({mode:t.mode,session:i,consulted:s,sessionId:r}),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=z()??void 0;return o.kind==="deny"?(process.stdout.write(zn(o.reason)),await me(r,{...i,deny_count:(i.deny_count??0)+1}),await le({event:"deny",session_id:r,cwd:c,project_key:l}),0):o.kind==="warn"?(process.stdout.write(ft(o.context)),await me(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await le({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await me(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var o_,l_=b(()=>{"use strict";Me();qn();Xt();ot();Qt();Qn();Xn();o_=3;a(a_,"decideGate");a(s_,"warnText");a(LN,"denyText");a($N,"runGuardGate")});var u_={};oe(u_,{decideStopGate:()=>d_,runGuardStop:()=>jN});function d_(t){return{block:t.enabled&&t.editsSeen>0&&!t.reviewed&&!t.stopHookActive&&!t.alreadyBlocked}}async function jN(){try{let t=ve();if(t.mode==="off"||!t.stopGate)return 0;let e=await G(),n=typeof e.session_id=="string"&&e.session_id.trim().length>0?e.session_id.trim():null;if(n===null)return 0;let r=await Ye(n),i=(await X()).guard_signals?.[n]?.reviewed_at!==void 0;return d_({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:e.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:FN})),await me(n,{...r,stop_blocked:!0}),await le({event:"stop_block",session_id:n})),0}catch{return 0}}var FN,p_=b(()=>{"use strict";Me();Xt();Qt();Qn();Xn();a(d_,"decideStopGate");FN="[maind guard] Stop gate (strict, opt-in): this session edited files but review_changes never ran. Run the review over the edit batches \u2014 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(jN,"runGuardStop")});import{appendFile as UN,mkdir as HN,readFile as m_,rename as h_,writeFile as g_}from"node:fs/promises";import{homedir as y_}from"node:os";import{join as __}from"node:path";function b_(t,e,n,r){if(e==="off"||t.length===0)return null;let i={},s=new Map,o=1/0,c=-1/0;for(let d of t){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:e,counts:Object.fromEntries(l),event_count:Math.min(t.length,1e5),citations:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function en(){return __(y_(),".maind","gateway","attest-spool.jsonl")}async function cl(t){let e=K();if(e===null)return!1;let n=await qt("gateway_attest",{...t},{apiKey:e,deviceId:ne(),projectKey:t.project_key??null,bridgeVersion:U,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function w_(t){try{await HN(__(y_(),".maind","gateway"),{recursive:!0}),await UN(en(),JSON.stringify(t)+`
|
|
255
|
+
`,{mode:384}),await WN()}catch{}}async function WN(){try{let e=(await m_(en(),"utf8")).split(`
|
|
256
|
+
`).filter(r=>r.trim());if(e.length<=f_)return;let n=`${en()}.${process.pid}.tmp`;await g_(n,e.slice(-f_).join(`
|
|
225
257
|
`)+`
|
|
226
|
-
`,{mode:384}),await
|
|
227
|
-
`).filter(r=>r.trim())}catch{return}if(
|
|
258
|
+
`,{mode:384}),await h_(n,en())}catch{}}async function v_(){let t;try{t=(await m_(en(),"utf8")).split(`
|
|
259
|
+
`).filter(r=>r.trim())}catch{return}if(t.length===0)return;let e=[],n=!1;for(let r of t){if(n){e.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await cl(i)||(n=!0,e.push(r))}try{let r=`${en()}.${process.pid}.tmp`;await g_(r,e.length>0?e.join(`
|
|
228
260
|
`)+`
|
|
229
|
-
`:"",{mode:384}),await
|
|
230
|
-
`,384)}async function
|
|
231
|
-
`),2;let n=
|
|
232
|
-
`);continue}let
|
|
233
|
-
`);continue}if(!(
|
|
261
|
+
`:"",{mode:384}),await h_(r,en())}catch{}}var f_,k_=b(()=>{"use strict";re();jr();st();f_=256;a(b_,"aggregateWindow");a(en,"attestSpoolPath");a(cl,"postAttestation");a(w_,"spoolAttestation");a(WN,"capSpool");a(v_,"flushAttestSpool")});function Gr(t=process.env,e=Oe()){let n=t.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:e?.gateway_mode??"warn"}function Fs(t=process.env,e=Oe()){let n=t.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:e?.gateway_attest===!0}async function x_(t,e=ze()){let n={};try{let i=await ie(e);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,...t};await Y(e,JSON.stringify(r,null,2)+`
|
|
262
|
+
`,384)}async function S_(t,e=ze()){await x_({gateway_mode:t},e)}async function E_(t,e=ze()){await x_({gateway_attest:t},e)}function T_(t=process.env,e=Oe()){let n=t.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:e?.gateway_sha_proof??"warn"}var ll=b(()=>{"use strict";Dn();Ke();a(Gr,"resolveGatewayMode");a(Fs,"resolveGatewayAttest");a(x_,"writeGatewayConfigPatch");a(S_,"writeGatewayMode");a(E_,"writeGatewayAttest");a(T_,"resolveShaProofMode")});function A_(t){if(typeof t!="object"||t===null)return[];let e=t.conventions;if(!Array.isArray(e))return[];let n=[];for(let r of e){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"&&GN.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 BN(t,e,n){return t.tool!==e?!1:t.servers===null?!0:t.servers.includes("*")||t.servers.includes(n)}function N_(t,e,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)BN(s,t,e)&&(i===null||R_[s.severity]>R_[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function I_(t,e){let n=`${e.conventionId} v${e.conventionVersion}`,r=e.summary?` ("${e.summary}")`:"";return`maind gateway: tool '${t}' 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 GN,R_,dl=b(()=>{"use strict";GN=new Set(["required","recommended","info"]);a(A_,"extractGatewayRules");R_={required:2,recommended:1,info:0};a(BN,"ruleMatches");a(N_,"decideToolCall");a(I_,"policyDenyText")});import{mkdirSync as KN,readFileSync as VN,renameSync as zN,writeFileSync as qN}from"node:fs";import{homedir as YN}from"node:os";import{dirname as JN,join as XN}from"node:path";function C_(){return XN(YN(),".maind","gateway","policy-cache.json")}function js(t,e,n=new Date().toISOString()){try{let r={version:ul,cached_at:n,mcp_url:t.mcpUrl,key_fp:t.keyFp,rules:e},i=C_();KN(JN(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;qN(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),zN(s,i)}catch{}}function Us(t){try{let e=VN(C_(),"utf8"),n=JSON.parse(e);return n.version!==ul||n.mcp_url!==t.mcpUrl||n.key_fp!==t.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:ul,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var ul,pl=b(()=>{"use strict";ul=1;a(C_,"policyCachePath");a(js,"writePolicyCache");a(Us,"readPolicyCache")});function Br(t=process.env){let e=t.MAIND_MCP_URL??Xc,n=K();return{mcpUrl:e,keyFp:n?Fi(n):"anon"}}async function Hs(t=6e3){let e=K();if(e===null)return null;let n=null;try{n=z()}catch{n=null}let r=await qt("get_conventions",{},{apiKey:e,deviceId:ne(),projectKey:n,bridgeVersion:U,clientFamily:"gateway",timeoutMs:t});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return A_(i)}var fl=b(()=>{"use strict";Tn();re();jr();ot();st();dl();a(Br,"policyIdentity");a(Hs,"fetchGatewayRules")});function Kr(t){let e=Array.isArray(t.args)?t.args.map(String):[],n=e.indexOf("gateway");if(n===-1||e.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(t.command??""),...e.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function ZN(t){if(Kr(t))return!1;let e=typeof t.command=="string"?t.command:"",n=Array.isArray(t.args)?t.args:[],r=[e,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function QN(t){return typeof t.command!="string"||t.command.length===0?{action:"skip",reason:"not-stdio"}:typeof t.url=="string"?{action:"skip",reason:"not-stdio"}:Kr(t)?{action:"skip",reason:"already-wrapped"}:ZN(t)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function O_(t,e,n){let r=String(t.command),i=Array.isArray(t.args)?t.args.map(String):[],s=typeof t.env=="object"&&t.env!==null?t.env:void 0,o=s||e.env?{...s??{},...e.env??{}}:void 0,c={...t,command:e.command,args:[...e.args,"gateway","--label",n,"--",r,...i]};return o&&(c.env=o),c}function D_(t){if(!Kr(t))return null;let e=t.args.map(String),n=e.indexOf("--",e.indexOf("gateway")+1);return n===-1||n+1>=e.length?null:{...t,command:e[n+1],args:e.slice(n+2)}}function M_(t){return Object.entries(t).map(([e,n])=>{let r=QN(n);return r.action==="wrap"?{key:e,action:"wrap"}:{key:e,action:"skip",reason:r.reason}})}var P_=b(()=>{"use strict";a(Kr,"isGatewayWrapped");a(ZN,"isMaindProxyEntry");a(QN,"classifyServer");a(O_,"wrapServerEntry");a(D_,"unwrapServerEntry");a(M_,"planRewrites")});var H_={};oe(H_,{runGatewayInstall:()=>sI,runGatewayUninstall:()=>oI});import{existsSync as eI,readFileSync as tI}from"node:fs";import{homedir as nI}from"node:os";import{join as L_}from"node:path";import{createInterface as rI}from"node:readline";function $_(t){let e={yes:!1,dryRun:!1};for(let n of t)if(n==="--yes")e.yes=!0;else if(n==="--dry-run")e.dryRun=!0;else return null;return e}function F_(){return[{label:"Claude Code (project .mcp.json)",path:L_(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:L_(nI(),".claude.json")}]}async function j_(t){let e=rI({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>e.question(`${t} [y/N] `,r));return n.trim().toLowerCase()==="y"||n.trim().toLowerCase()==="yes"}finally{e.close()}}function U_(t){let e=iI(t);if(e===null)return null;try{let n=JSON.parse(e);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 iI(t){try{return eI(t)?tI(t,"utf8"):null}catch{return null}}async function sI(t){let e=$_(t);if(e===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
263
|
+
`),2;let n=Ie({entryPath:Ce(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of F_()){let s=U_(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
264
|
+
`);continue}let o=M_(s.servers);for(let c of o){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
265
|
+
`);continue}if(!(e.yes||await j_(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
234
266
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
235
267
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
236
|
-
`);continue}s.servers[c.key]=
|
|
237
|
-
`)}!
|
|
268
|
+
`);continue}s.servers[c.key]=O_(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${e.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
269
|
+
`)}!e.dryRun&&o.some(c=>c.action==="wrap")&&await Y(i.path,JSON.stringify(s.raw,null,2)+`
|
|
238
270
|
`,384)}return process.stderr.write(r>0?`
|
|
239
|
-
${
|
|
271
|
+
${e.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
240
272
|
`:`
|
|
241
273
|
Nothing to wrap.
|
|
242
|
-
`),0}async function
|
|
243
|
-
`),2;let n=0;for(let r of
|
|
244
|
-
`);continue}i.servers[
|
|
245
|
-
`)}!
|
|
274
|
+
`),0}async function oI(t){let e=$_(t);if(e===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
275
|
+
`),2;let n=0;for(let r of F_()){let i=U_(r.path);if(i===null)continue;let s=!1;for(let[o,c]of Object.entries(i.servers)){if(!Kr(c)||!(e.yes||await j_(`Unwrap MCP server '${o}' in ${r.label}?`)))continue;let d=D_(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${o} \u2014 wrapped shape unrecognized, left untouched
|
|
276
|
+
`);continue}i.servers[o]=d,s=!0,n+=1,process.stderr.write(` ${e.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${o}
|
|
277
|
+
`)}!e.dryRun&&s&&await Y(r.path,JSON.stringify(i.raw,null,2)+`
|
|
246
278
|
`,384)}return process.stderr.write(n>0?`
|
|
247
|
-
${
|
|
279
|
+
${e.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
248
280
|
`:`
|
|
249
281
|
Nothing wrapped \u2014 nothing to restore.
|
|
250
|
-
`),0}var
|
|
251
|
-
`),0}return
|
|
252
|
-
`),2):(await
|
|
253
|
-
`:
|
|
282
|
+
`),0}var W_=b(()=>{"use strict";Ke();Cn();P_();a($_,"parseFlags");a(F_,"targets");a(j_,"confirm");a(U_,"loadConfig");a(iI,"readFileSafeSync");a(sI,"runGatewayInstall");a(oI,"runGatewayUninstall")});var G_={};oe(G_,{runGatewayAttest:()=>cI,runGatewayMode:()=>aI,runGatewayPolicy:()=>uI});async function aI(t){let e=t[0];if(e===void 0){let n=Gr(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
283
|
+
`),0}return e!=="off"&&e!=="warn"&&e!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
284
|
+
`),2):(await S_(e),process.stdout.write(`maind: gateway mode set to '${e}'. `+(e==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
285
|
+
`:e==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
254
286
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
255
|
-
`)),0)}async function
|
|
287
|
+
`)),0)}async function cI(t){let e=t[0];if(e===void 0){let n=Fs(),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)":""}.
|
|
256
288
|
`+(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.
|
|
257
|
-
`)),0}return
|
|
258
|
-
`),2):(await
|
|
289
|
+
`)),0}return e!=="on"&&e!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
290
|
+
`),2):(await E_(e==="on"),process.stdout.write(e==="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.
|
|
259
291
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
260
|
-
`),0)}function
|
|
261
|
-
`;let
|
|
262
|
-
`}return
|
|
263
|
-
`):(
|
|
264
|
-
`))}let i=
|
|
292
|
+
`),0)}function lI(t){if(t.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
293
|
+
`;let e="";for(let n of t){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";e+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
|
|
294
|
+
`}return e}function dI(t,e=Date.now()){let n=Date.parse(t.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((e-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 uI(t){let e=t.includes("--refresh"),n=Gr(),r=Br();if(e){let s=await Hs();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
295
|
+
`):(js(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
|
|
296
|
+
`))}let i=Us(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
265
297
|
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
266
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
267
|
-
`),process.stdout.write(
|
|
268
|
-
`),0)}var
|
|
269
|
-
`,{mode:384})}catch{}}function
|
|
298
|
+
`),0):(process.stdout.write(`maind: policy from cache (${dI(i)}, ${r.mcpUrl}):
|
|
299
|
+
`),process.stdout.write(lI(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.
|
|
300
|
+
`),0)}var B_=b(()=>{"use strict";ll();pl();fl();a(aI,"runGatewayMode");a(cI,"runGatewayAttest");a(lI,"renderRules");a(dI,"cacheAge");a(uI,"runGatewayPolicy")});var Y_={};oe(Y_,{gatewayEventsFile:()=>z_,parseGatewayArgs:()=>q_,runGateway:()=>_I});import{spawn as pI}from"node:child_process";import{appendFile as fI,mkdir as mI}from"node:fs/promises";import{homedir as K_}from"node:os";import{basename as hI,join as V_}from"node:path";import{createInterface as gI}from"node:readline";function z_(){return V_(K_(),".maind","gateway","events.jsonl")}async function yI(t){try{let e=z_();await mI(V_(K_(),".maind","gateway"),{recursive:!0}),await fI(e,JSON.stringify(t)+`
|
|
301
|
+
`,{mode:384})}catch{}}function q_(t){let e=new Set,n=null,r=0;for(;r<t.length;){let i=t[r];if(i==="--deny-tool"){let s=t[r+1];if(!s)return null;e.add(s),r+=2;continue}if(i==="--label"){let s=t[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=t[r+1];return s?{denyTools:e,label:n,command:s,args:t.slice(r+2)}:null}return null}return null}async function _I(t){if(t[0]==="install"||t[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:A}=await Promise.resolve().then(()=>(W_(),H_));return t[0]==="install"?S(t.slice(1)):A(t.slice(1))}if(t[0]==="mode"||t[0]==="policy"||t[0]==="attest"){let{runGatewayAttest:S,runGatewayMode:A,runGatewayPolicy:D}=await Promise.resolve().then(()=>(B_(),G_));return t[0]==="mode"?A(t.slice(1)):t[0]==="attest"?S(t.slice(1)):D(t.slice(1))}let e=q_(t);if(e===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
270
302
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
271
303
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
272
304
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -276,54 +308,54 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
276
308
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
277
309
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
278
310
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
279
|
-
`),2;let{denyTools:n,label:r,command:i,args:s}=
|
|
280
|
-
`),process.exitCode=1});let k=
|
|
281
|
-
`),g(
|
|
282
|
-
`),g(
|
|
283
|
-
`),g(
|
|
284
|
-
`),g(
|
|
285
|
-
`)}),k.on("close",()=>{w.stdin.end()});let x=await new Promise(S=>{w.on("exit",(
|
|
286
|
-
`),await le({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(
|
|
287
|
-
`),
|
|
288
|
-
`);let g=r.params?.name;process.stdout.write(
|
|
289
|
-
`);return}i=
|
|
290
|
-
`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let
|
|
291
|
-
`);return}let s=this.localRouter!==null&&r?.method==="tools/list",
|
|
292
|
-
`);return}if(
|
|
293
|
-
`);return}if(i!==null){let d
|
|
294
|
-
`);return}if(
|
|
295
|
-
`)}}}async handle401(
|
|
296
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
297
|
-
`).trim();i=[],
|
|
298
|
-
`)},"flushEvent");try{for(;;){let{value:
|
|
299
|
-
`))!==-1;){let
|
|
300
|
-
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await
|
|
301
|
-
`))!==-1;){let
|
|
302
|
-
`)}
|
|
303
|
-
`)}
|
|
304
|
-
`).map(
|
|
305
|
-
`),null));if(p){if(p.status==="approved")return
|
|
306
|
-
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return
|
|
307
|
-
`),null;if(p.status==="expired"||p.status==="consumed")return
|
|
308
|
-
`),null}}return
|
|
309
|
-
`),null}
|
|
311
|
+
`),2;let{denyTools:n,label:r,command:i,args:s}=e,o=r??hI(i),c=Gr(),l=T_(),d=l==="off"?null:Vr(),u=c==="off"?[]:Us(Br())?.rules??[];c!=="off"&&Hs().then(S=>{S!==null&&(u=S,js(Br(),S))}).catch(()=>{});let p=[],h=Fs()&&K()!==null&&c!=="off",m=null;try{m=z()}catch{m=null}let g=a(S=>{yI(S),h&&p.push(S)},"record"),y=a(async()=>{if(!h)return;let S=b_(p.splice(0),c,o,m);S!==null&&(await cl(S)||await w_(S))},"attestAndReset");h&&v_().catch(()=>{});let _=setInterval(()=>{y()},30*6e4);_.unref();let w=pI(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)}
|
|
312
|
+
`),process.exitCode=1});let k=gI({input:process.stdin,terminal:!1});k.on("line",S=>{let A=Al(S);if(A.kind==="request"&&A.method==="tools/call"&&A.toolName){if(n.has(A.toolName)&&A.id!==void 0){process.stdout.write(nn(A.id,A.toolName)+`
|
|
313
|
+
`),g(Gs("deny",o,A.toolName,Date.now()));return}let D=N_(A.toolName,o,u,c);if(D.kind==="deny"&&A.id!==void 0){process.stdout.write(nn(A.id,A.toolName,I_(A.toolName,D.rule))+`
|
|
314
|
+
`),g(Bs("policy_deny",o,A.toolName,Date.now(),D.rule.conventionId,D.rule.conventionVersion));return}(D.kind==="warn"||D.kind==="deny")&&g(Bs("policy_warn",o,A.toolName,Date.now(),D.rule.conventionId,D.rule.conventionVersion));let F=zr(S,d);if(F.length>0){let j=F.find(B=>B.verdict==="fabricated");if(j!==void 0&&l==="enforce"&&c==="enforce"&&A.id!==void 0&&j!==void 0&&A.id!==void 0){process.stdout.write(nn(A.id,A.toolName,rn(j,!0))+`
|
|
315
|
+
`),g(Ks("sha_deny",o,A.toolName,Date.now()));return}let $=j??F[0];process.stderr.write(`[maind gateway] ${rn($,!1)}
|
|
316
|
+
`),g(Ks("sha_warn",o,A.toolName,Date.now()))}g(Gs("tool_call",o,A.toolName,Date.now()))}w.stdin.write(S+`
|
|
317
|
+
`)}),k.on("close",()=>{w.stdin.end()});let x=await new Promise(S=>{w.on("exit",(A,D)=>{S(A??(D?1:0))})});return clearInterval(_),await y(),x}var J_=b(()=>{"use strict";Vs();k_();ll();dl();zs();pl();fl();re();ot();a(z_,"gatewayEventsFile");a(yI,"logEvent");a(q_,"parseGatewayArgs");a(_I,"runGateway")});var wl={};oe(wl,{MAX_ENTRIES:()=>ml,TTL_MS:()=>yl,crossSessionDir:()=>_l,decideCrossSession:()=>Q_,parseSessionDb:()=>Z_,pruneDb:()=>bl,runGuardCrossCheck:()=>RI,runGuardCrossObserve:()=>TI,staleReason:()=>hl});import{mkdir as bI,readFile as wI,readdir as vI,stat as X_,unlink as kI,writeFile as xI}from"node:fs/promises";import{homedir as SI}from"node:os";import{join as gl}from"node:path";function _l(){return gl(SI(),".maind","cross-session")}function Z_(t){let e={files:{},warned:{}};if(typeof t!="object"||t===null)return e;let n=t,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 bl(t,e){let n=Object.entries(t.files).filter(([,r])=>e-r.t<=yl);return n.length>ml&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-ml)),{files:Object.fromEntries(n),warned:t.warned}}function Q_(t,e){return t===void 0||e===void 0?{kind:"allow"}:e>t?{kind:"stale",baseline:t,current:e}:{kind:"allow"}}function hl(t,e){return`Cross-session guard: '${t}' changed on disk after this session last read it (mtime ${Math.floor(e.current/1e3)} > recorded ${Math.floor(e.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 eb(t){let e=_l();return await bI(e,{recursive:!0}),gl(e,`${t}.json`)}async function tb(t,e){try{let n=await wI(await eb(t),"utf8");return bl(Z_(JSON.parse(n)),e)}catch{return{files:{},warned:{}}}}async function nb(t,e){try{await xI(await eb(t),JSON.stringify(e),{mode:384})}catch{}}async function EI(t){try{let e=_l();for(let n of await vI(e)){if(!n.endsWith(".json"))continue;let r=gl(e,n),i=await X_(r).catch(()=>null);i&&t-i.mtimeMs>yl&&await kI(r).catch(()=>{})}}catch{}}async function rb(t){try{return(await X_(t)).mtimeMs}catch{return}}async function TI(t,e=Date.now()){try{if(ve().mode==="off")return 0;let r=t??await G(),i=typeof r.session_id=="string"?r.session_id:"",s=De(r);if(!i||!s)return 0;let o=await rb(s);if(o===void 0)return 0;let c=await tb(i,e);return c.files[s]={m:o,t:e},delete c.warned[s],await nb(i,bl(c,e)),await EI(e),0}catch{return 0}}async function RI(t,e=Date.now()){try{let n=ve();if(n.mode==="off")return 0;let r=t??await G(),i=typeof r.session_id=="string"?r.session_id:"",s=De(r);if(!i||!s)return 0;let o=await tb(i,e),c=Q_(o.files[s]?.m,await rb(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(zn(hl(s,c))+`
|
|
318
|
+
`),await le({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(ft(hl(s,c))+`
|
|
319
|
+
`),o.warned[s]=c.current,await nb(i,o),await le({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var yl,ml,vl=b(()=>{"use strict";Me();qn();Qt();Qn();yl=48*3600*1e3,ml=500;a(_l,"crossSessionDir");a(Z_,"parseSessionDb");a(bl,"pruneDb");a(Q_,"decideCrossSession");a(hl,"staleReason");a(eb,"dbPath");a(tb,"loadDb");a(nb,"saveDb");a(EI,"sweepStaleSessionFiles");a(rb,"fileMtime");a(TI,"runGuardCrossObserve");a(RI,"runGuardCrossCheck")});var xl={};oe(xl,{INDEX_REFRESH_WORKER:()=>ob,acquireLock:()=>cb,releaseLock:()=>kl,runIndexRefreshWorker:()=>PI,runOnIndexRefresh:()=>MI});import{spawn as AI}from"node:child_process";import{existsSync as NI,mkdirSync as II,rmdirSync as ib,statSync as CI}from"node:fs";import{join as sb}from"node:path";function ab(t){return sb(t,".maind","index-refresh.lock")}function DI(t){return sb(t,".maind","code-index.sqlite")}function cb(t,e=Date.now()){let n=ab(t);try{if(e-CI(n).mtimeMs<OI)return!1;ib(n)}catch{}try{return II(n,{recursive:!1}),!0}catch{return!1}}function kl(t){try{ib(ab(t))}catch{}}async function MI(){try{let t=await G(),e=fe(typeof t.cwd=="string"?t.cwd:process.cwd());if(!NI(DI(e))||!cb(e))return 0;let n=process.argv[1];if(n===void 0)return kl(e),0;AI(process.execPath,[n,ob,e],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function PI(){let t=process.argv[3]??fe();try{let{createNodeCodeIndex:e}=await Promise.resolve().then(()=>(hc(),Ah)),n=e({repoRoot:t});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{kl(t)}return 0}var OI,ob,Sl=b(()=>{"use strict";Me();Or();OI=30*6e4,ob="index-refresh-run";a(ab,"lockPath");a(DI,"indexDbPath");a(cb,"acquireLock");a(kl,"releaseLock");a(MI,"runOnIndexRefresh");a(PI,"runIndexRefreshWorker")});import{randomUUID as LI}from"node:crypto";import{createInterface as RS}from"node:readline";var lb=[["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 db(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();if(e.length===0)return null;for(let[n,r]of lb)if(e.includes(n))return r;return null}a(db,"mapClientInfoNameToFamily");function Rl(t){let e;try{e=JSON.parse(t)}catch{return null}if(!Ws(e)||e.method!=="initialize")return null;let n=e.params;if(!Ws(n))return null;let r=n.clientInfo;if(!Ws(r))return null;let i=r.name,s=db(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(Rl,"tryExtractInitializeClient");function Ws(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}a(Ws,"isRecord");Vs();zs();Tn();var AS="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")}},Gi=class{static{a(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;connectionOkRecorded=!1;presenceFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(e){this.apiKey=e.apiKey,this.keyFp=Fi(e.apiKey),this.deviceId=e.deviceId,this.bridgeVersion=e.bridgeVersion;let n=e.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=NS(n),this.clientFamilyLocked=this.clientFamily!==null;let r=e.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=IS(r),this.clientVersionLocked=this.clientVersion!==null;let i=(e.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=e.localRouter??null,this.presence=e.presence??null,this.onConnectionOutcome=e.onConnectionOutcome??null,this.shaRepoRoot=Vr(),this.mcpUrl=e.mcpUrl??process.env.MAIND_MCP_URL??AS}async run(){let e=RS({input:process.stdin,crlfDelay:1/0});for await(let n of e){if(this.terminated)return;let r=n.trim();r.length!==0&&await this.forwardFrame(r)}}async forwardFrame(e,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let u=Rl(e);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Hi(e)&&(this.initFrame=e);let r=DS(e),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=zr(e,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),h=p??u[0];if(p!==void 0&&Ol(p)&&r.id!==null){let m=rn(p,!0);process.stderr.write(`[maind] ${m}
|
|
320
|
+
`);let g=r.params?.name;process.stdout.write(nn(r.id,typeof g=="string"?g:"unknown",m)+`
|
|
321
|
+
`);return}i=rn(h,!1),process.stderr.write(`[maind] ${i}
|
|
322
|
+
`)}}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+`
|
|
323
|
+
`);return}let s=this.localRouter!==null&&r?.method==="tools/list",o=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:o,body:e})}catch(u){let p=Ui(e);if(this.serveInitializeFromCache(e,p))return;Wi(p,-32603,`bridge network error: ${PS(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,e);return}if(c.ok&&!this.connectionOkRecorded&&(this.connectionOkRecorded=!0,this.recordOutcome("ok",null)),c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!Hi(e)){let u=await c.text().catch(()=>"");if(MS(u)&&await this.recoverSession()){await this.forwardFrame(e,!0);return}let p=Ui(e);Wi(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Ui(e),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(e,u))return;Wi(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 Ua(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
324
|
+
`);return}if(Hi(e)){let u=d.startsWith("text/event-stream")?await Ua(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
325
|
+
`);return}if(i!==null){let u=d.startsWith("text/event-stream")?await Ua(c):await c.text(),p=OS(u,i);p.trim().length>0&&process.stdout.write(p+`
|
|
326
|
+
`);return}if(d.startsWith("text/event-stream"))await CS(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
327
|
+
`)}}}async handle401(e,n){let r=await e.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,new kr(LS(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let o=Ui(n);Wi(o,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(e,n){try{this.onConnectionOutcome?.(e,n)}catch{}}async postPresenceToolCall(e,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:e,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 $S(s)}buildHeaders(e){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),e&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let e;try{e=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=e.headers.get("mcp-session-id");if(await e.text().catch(()=>""),!e.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=Be()),this.repoRoot}cacheInitializeResult(e){try{let n=JSON.parse(e);n&&n.result&&cm(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(e,n){if(!Hi(e))return!1;let r=lm(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(dm(n,r)+`
|
|
328
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${ji(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function NS(t){if(t===null)return null;let e=t.trim().toLowerCase();return e.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(e)?e:null}a(NS,"normalizeClientFamily");function IS(t){if(t===null)return null;let e=t.trim();return e.length===0?null:e.slice(0,64)}a(IS,"normalizeClientVersion");async function CS(t){if(!t.body)return;let e=t.body.getReader(),n=new TextDecoder,r="",i=[],s=a(()=>{if(i.length===0)return;let o=i.join(`
|
|
329
|
+
`).trim();i=[],o.length>0&&process.stdout.write(o+`
|
|
330
|
+
`)},"flushEvent");try{for(;;){let{value:o,done:c}=await e.read();if(c)break;r+=n.decode(o,{stream:!0});let l;for(;(l=r.indexOf(`
|
|
331
|
+
`))!==-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(CS,"pipeSseToStdout");function OS(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return t;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?t:(r.content.push({type:"text",text:`[maind] ${e}`}),JSON.stringify(n))}catch{return t}}a(OS,"appendNoteToToolResult");function DS(t){try{let e=JSON.parse(t);return{id:e.id??null,method:e.method,params:e.params}}catch{return null}}a(DS,"parseRpc");async function Ua(t){if(!t.body)return"";let e=t.body.getReader(),n=new TextDecoder,r="",i=[],s=[],o=a(()=>{if(s.length===0)return;let c=s.join(`
|
|
332
|
+
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await e.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
333
|
+
`))!==-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(`
|
|
334
|
+
`)}a(Ua,"collectSseText");function Ui(t){try{return JSON.parse(t).id??null}catch{return null}}a(Ui,"tryExtractId");function Hi(t){try{return JSON.parse(t).method==="initialize"}catch{return!1}}a(Hi,"isInitializeRequest");function MS(t){let e=t.toLowerCase();return e.includes("session not found")||e.includes("session expired")||e.includes("no valid session")||e.includes("reinitialize")||e.includes("session")&&e.includes("expired")}a(MS,"isSessionLossBody");function PS(t){return t instanceof Error?t.message:String(t)}a(PS,"stringifyErr");function Wi(t,e,n){let r={jsonrpc:"2.0",id:t,error:{code:e,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
335
|
+
`)}a(Wi,"emitJsonRpcError");function LS(t){return t.includes("device_mismatch")?"device_mismatch":t.includes("device_revoked")?"device_revoked":t.includes("device_required")?"device_required":"auth_failed"}a(LS,"extractHint");function $S(t){try{let e=t.trim();if(e.length===0)return null;let n=e;if(!e.startsWith("{")){let s=e.split(`
|
|
336
|
+
`).map(o=>o.trim()).filter(o=>o.startsWith("data:"));if(s.length===0)return null;n=s[s.length-1].slice(5).trim()}let i=JSON.parse(n).result?.content?.[0]?.text;return typeof i!="string"?null:JSON.parse(i)}catch{return null}}a($S,"parsePresenceToolResult");re();re();An();import{spawn as qS}from"node:child_process";import{platform as YS}from"node:os";async function Nn(t,e=process.stderr){let n=Sr(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=Ki(t),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 QS(l.verification_uri_complete).catch(()=>{}),ZS(l,e);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await XS(u);let p=await JS(i,l.device_code).catch(h=>(e.write(`[maind-mcp-bridge] poll error (will retry): ${String(h)}
|
|
337
|
+
`),null));if(p){if(p.status==="approved")return jt(p.api_key),e.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
338
|
+
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return e.write(`[maind-mcp-bridge] sign-in denied by user
|
|
339
|
+
`),null;if(p.status==="expired"||p.status==="consumed")return e.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
340
|
+
`),null}}return e.write(`[maind-mcp-bridge] sign-in timed out
|
|
341
|
+
`),null}a(Nn,"runDeviceFlow");async function JS(t,e){let n=await fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:e})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}a(JS,"pollOnce");function XS(t){return new Promise(e=>setTimeout(e,t))}a(XS,"sleep");function ZS(t,e){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: ${hm(t.verification_uri,56)} \u2502`,` \u2502 Code: ${hm(t.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(t.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",""];e.write(n.join(`
|
|
310
342
|
`)+`
|
|
311
|
-
`)}
|
|
312
|
-
`))}
|
|
313
|
-
`;let
|
|
343
|
+
`)}a(ZS,"printAuthInstructions");function hm(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}a(hm,"pad");async function QS(t){let e,n;switch(YS()){case"darwin":e="open",n=[t];break;case"win32":e="cmd",n=["/c","start","",t];break;default:e="xdg-open",n=[t];break}return new Promise((r,i)=>{try{let s=qS(e,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}a(QS,"openExternalBrowser");Ba();st();ot();st();import*as Hh from"node:os";function _m(t){let e={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<t.length;n++){let r=t[n];switch(r){case"-h":case"--help":e.help=!0;break;case"--full":e.full=!0;break;case"--no-preamble":e.noPreamble=!0;break;case"--no-hook":e.noHook=!0;break;case"--non-interactive":e.nonInteractive=!0;break;case"--telemetry":e.telemetry=!0;break;case"--skip-codex":e.skipCodex=!0;break;case"--dry-run":e.dryRun=!0;break;case"--auto-working-paths":e.autoWorkingPaths=!0;break;case"--project-root":{let i=t[n+1];if(i===void 0||i.startsWith("--"))throw new Ne("--project-root requires a path argument");e.projectRoot=i,n++;break}case"--token":{let i=t[n+1];if(i===void 0||i.startsWith("--"))throw new Ne("--token requires a token argument");e.token=i,n++;break}case"--one-click-token":{let i=t[n+1];if(i===void 0||i.startsWith("--"))throw new Ne("--one-click-token requires a token argument");e.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=t[n+1];if(i===void 0||i.startsWith("--"))throw new Ne("--one-click-exchange-url requires a URL argument");e.oneClickExchangeUrl=i,n++;break}case"--client":{let i=t[n+1];if(i===void 0||i.startsWith("--"))throw new Ne("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");e.client=i,n++;break}default:throw new Ne(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return e.full&&(e.nonInteractive=!0),e}a(_m,"parseInstallFlags");var Ne=class extends Error{static{a(this,"InstallFlagError")}constructor(e){super(e),this.name="InstallFlagError"}};function bm(){let t=["","@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 (claude-code, cursor, ...)"," --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.",""];process.stdout.write(t.join(`
|
|
344
|
+
`))}a(bm,"printInstallHelp");var Vi=class{static{a(this,"InstallReport")}results=[];add(e){this.results.push(e)}results_(){return this.results}summary(){let e=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"?e++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:e,needsDecision:n,failed:r}}hasFailures(){return this.results.some(e=>e.status==="failed")}hasUserDecisionPending(){return this.results.some(e=>e.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
|
|
345
|
+
`;let e=["Target","Action","Status","Detail"],n=Math.max(e[0].length,...this.results.map(d=>d.target.length)),r=Math.max(e[1].length,...this.results.map(d=>d.action.length)),i=Math.max(e[2].length,...this.results.map(d=>d.status.length)),s=Math.max(e[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(e[0],n)} | ${o(e[1],r)} | ${o(e[2],i)} | ${o(e[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(`
|
|
314
346
|
`)+`
|
|
315
|
-
`}print(
|
|
316
|
-
`),
|
|
347
|
+
`}print(e){let n=this.summary();e.write(`
|
|
348
|
+
`),e.write(this.toMarkdownTable()),e.write(`
|
|
317
349
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
318
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as
|
|
350
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as wm from"node:fs/promises";import*as at from"node:path";import*as vm from"node:readline";var mE=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function km(t){let e=at.resolve(t),n=e;for(;;){if(await Sm(n))return n;let r=at.dirname(n);if(r===n)return e;n=r}}a(km,"detectProjectRoot");async function xm(t){let n=at.resolve(t),r=[];for(;;){await Sm(n)&&r.push(n);let i=at.dirname(n);if(i===n)break;n=i}return r}a(xm,"findAllProjectRoots");async function Sm(t){for(let e of mE)try{return await wm.access(at.join(t,e)),!0}catch{}return!1}a(Sm,"hasAnyMarker");async function Em(t,e){if(t.length===0)return null;if(t.length===1)return t[0];if(!e)return null;process.stdout.write(`
|
|
319
351
|
Multiple project roots found between cwd and the filesystem root:
|
|
320
|
-
`),
|
|
352
|
+
`),t.forEach((s,o)=>{process.stdout.write(` [${o+1}] ${s}
|
|
321
353
|
`)}),process.stdout.write(`
|
|
322
|
-
Which one should receive the MCP config and preamble files? [1-${
|
|
323
|
-
`),null):
|
|
324
|
-
`;if(n)return{target:
|
|
354
|
+
Which one should receive the MCP config and preamble files? [1-${t.length}, default 1]: `);let n=vm.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 t[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>t.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
|
|
355
|
+
`),null):t[i-1]}a(Em,"disambiguateProjectRoot");Va();Cn();Ke();var Er="maind";async function Pm(t,e,n=!1){if(t.kind!=="json")return{target:t.key,action:"merge",status:"failed",detail:`expected json target, got ${t.kind}`};let r;try{r=await ie(t.path)}catch(u){return qa(t,"read",u)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{i=JSON.parse(r)}catch(u){return qa(t,"parse",u)}}if(!ct(i))return{target:t.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let o=t.key==="claude-code-user"&&vE(i),c,l=!1;if(o){let u=i[Er];ct(u)&&Mm(u,e)&&(l=!0),c={...i,[Er]:Dm(u,e)}}else{let u=ct(i.mcpServers)?i.mcpServers:{},p=u[Er];ct(p)&&Mm(p,e)&&(l=!0),c={...i,mcpServers:{...u,[Er]:Dm(p,e)}}}if(l&&r!==null)return{target:t.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let d=JSON.stringify(c,null,2)+`
|
|
356
|
+
`;if(n)return{target:t.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:t.path};try{await Y(t.path,d)}catch(u){return qa(t,"write",u)}return{target:t.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:t.path}}a(Pm,"mergeJsonConfig");function Dm(t,e){let n=ct(t)&&ct(t.env)?t.env:{},r={...e.env};for(let[i,s]of Object.entries(n))!(i in r)&&typeof s=="string"&&(r[i]=s);return{command:e.command,args:[...e.args],env:r}}a(Dm,"mergeEntry");function vE(t){return!("mcpServers"in t||!(Er in t))}a(vE,"hasRootShape");function Mm(t,e){if(!ct(t)||t.command!==e.command||!kE(t.args,e.args)||!ct(t.env))return!1;for(let n of Object.keys(e.env))if(t.env[n]!==e.env[n])return!1;return!0}a(Mm,"serverEntriesEqual");function kE(t,e){if(!Array.isArray(t)||t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}a(kE,"arrayEquals");function ct(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}a(ct,"isObject");function qa(t,e,n){let r=n instanceof Error?n.message:String(n);return{target:t.key,action:"merge",status:"failed",detail:`${e}: ${r}`}}a(qa,"failed");Ke();import{parse as xE,stringify as SE}from"smol-toml";async function Lm(t,e,n=!1){if(t.kind!=="toml")return{target:t.key,action:"merge",status:"failed",detail:`expected toml target, got ${t.kind}`};let r;try{r=await ie(t.path)}catch(g){return Zi(t,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=xE(r);if(!Ht(g))return{target:t.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return Zi(t,"parse",g)}}let o=Ht(i.mcp_servers)?i.mcp_servers:{},c=o.maind;if(Ht(c)&&EE(c,e))return{target:t.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Ht(c)&&Ht(c.env)?c.env:{},d={...e.env};for(let[g,y]of Object.entries(l))!(g in d)&&typeof y=="string"&&(d[g]=y);let u={command:e.command,args:[...e.args],env:d},p={...i,mcp_servers:{...o,maind:u}},h;try{h=SE(p),h.endsWith(`
|
|
325
357
|
`)||(h+=`
|
|
326
|
-
`)}catch(g){return
|
|
358
|
+
`)}catch(g){return Zi(t,"write",g)}let m=h.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:t.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:t.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:t.path};try{await Y(t.path,h)}catch(g){return Zi(t,"write",g)}return{target:t.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:t.path}}a(Lm,"mergeTomlConfig");function EE(t,e){if(!Ht(t)||t.command!==e.command||!Array.isArray(t.args)||t.args.length!==e.args.length)return!1;for(let n=0;n<t.args.length;n++)if(t.args[n]!==e.args[n])return!1;if(!Ht(t.env))return!1;for(let n of Object.keys(e.env))if(t.env[n]!==e.env[n])return!1;return!0}a(EE,"tomlServerEntryEqual");function Ht(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}a(Ht,"isObject");function Zi(t,e,n){let r=n instanceof Error?n.message:String(n);return{target:t.key,action:"merge",status:"failed",detail:`${e}: ${r}`}}a(Zi,"failed");import*as Ve from"node:path";var TE="__STACK__";var RE="__INTENT__";var Ya="https://mcp.maind.dev/mcp",AE=`?stack=${TE}&intent=${RE}`;function NE(t,e){let n=new URLSearchParams;e.stack&&e.stack.length>0&&n.set("stack",e.stack.join(",")),e.intent&&n.set("intent",e.intent),e.project&&n.set("project",e.project),e.verbosity&&n.set("verbosity",e.verbosity);let r=n.toString();return r?t.includes("?")?`${t}&${r}`:`${t}?${r}`:t}a(NE,"buildStackAwareEndpoint");var ij=NE(Ya,{stack:["nextjs","supabase"],intent:"mixed"}),Rr=`## maind MCP integration \u2014 Mandatory consultation
|
|
327
359
|
|
|
328
360
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
329
361
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -392,10 +424,10 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
392
424
|
If no path is discoverable, provide a guided fallback:
|
|
393
425
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
394
426
|
|
|
395
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
427
|
+
Full tool set + provenance via \`get_conventions\`.`;function IE(t){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
396
428
|
|
|
397
429
|
- My stack: \`__STACK__\`
|
|
398
|
-
- MCP endpoint: \`${
|
|
430
|
+
- MCP endpoint: \`${t}\`
|
|
399
431
|
|
|
400
432
|
Please set this up strictly in order. Do not skip steps silently.
|
|
401
433
|
|
|
@@ -444,7 +476,7 @@ bridge creates and stores a device-bound key during first launch.
|
|
|
444
476
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
445
477
|
"env": {
|
|
446
478
|
"MAIND_CLIENT_FAMILY": "claude-code",
|
|
447
|
-
"MAIND_MCP_URL": "${
|
|
479
|
+
"MAIND_MCP_URL": "${t}"
|
|
448
480
|
}
|
|
449
481
|
}
|
|
450
482
|
}
|
|
@@ -457,7 +489,7 @@ bridge creates and stores a device-bound key during first launch.
|
|
|
457
489
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
458
490
|
"env": {
|
|
459
491
|
"MAIND_CLIENT_FAMILY": "claude-code",
|
|
460
|
-
"MAIND_MCP_URL": "${
|
|
492
|
+
"MAIND_MCP_URL": "${t}"
|
|
461
493
|
}
|
|
462
494
|
}
|
|
463
495
|
}
|
|
@@ -470,7 +502,7 @@ bridge creates and stores a device-bound key during first launch.
|
|
|
470
502
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
471
503
|
"env": {
|
|
472
504
|
"MAIND_CLIENT_FAMILY": "claude-desktop",
|
|
473
|
-
"MAIND_MCP_URL": "${
|
|
505
|
+
"MAIND_MCP_URL": "${t}"
|
|
474
506
|
}
|
|
475
507
|
}
|
|
476
508
|
}
|
|
@@ -482,7 +514,7 @@ command = "npx"
|
|
|
482
514
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
483
515
|
[mcp_servers.maind.env]
|
|
484
516
|
MAIND_CLIENT_FAMILY = "codex"
|
|
485
|
-
MAIND_MCP_URL = "${
|
|
517
|
+
MAIND_MCP_URL = "${t}"
|
|
486
518
|
|
|
487
519
|
# GitHub Copilot / VS Code workspace MCP (PROJECT_ROOT/.mcp.json)
|
|
488
520
|
{
|
|
@@ -492,7 +524,7 @@ MAIND_MCP_URL = "${e}"
|
|
|
492
524
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
493
525
|
"env": {
|
|
494
526
|
"MAIND_CLIENT_FAMILY": "copilot",
|
|
495
|
-
"MAIND_MCP_URL": "${
|
|
527
|
+
"MAIND_MCP_URL": "${t}"
|
|
496
528
|
}
|
|
497
529
|
}
|
|
498
530
|
}
|
|
@@ -506,7 +538,7 @@ MAIND_MCP_URL = "${e}"
|
|
|
506
538
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
507
539
|
"env": {
|
|
508
540
|
"MAIND_CLIENT_FAMILY": "cursor",
|
|
509
|
-
"MAIND_MCP_URL": "${
|
|
541
|
+
"MAIND_MCP_URL": "${t}"
|
|
510
542
|
}
|
|
511
543
|
}
|
|
512
544
|
}
|
|
@@ -520,7 +552,7 @@ MAIND_MCP_URL = "${e}"
|
|
|
520
552
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
521
553
|
"env": {
|
|
522
554
|
"MAIND_CLIENT_FAMILY": "windsurf",
|
|
523
|
-
"MAIND_MCP_URL": "${
|
|
555
|
+
"MAIND_MCP_URL": "${t}"
|
|
524
556
|
}
|
|
525
557
|
}
|
|
526
558
|
}
|
|
@@ -532,7 +564,7 @@ MAIND_MCP_URL = "${e}"
|
|
|
532
564
|
"command": "npx",
|
|
533
565
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
534
566
|
"env": {
|
|
535
|
-
"MAIND_MCP_URL": "${
|
|
567
|
+
"MAIND_MCP_URL": "${t}"
|
|
536
568
|
}
|
|
537
569
|
}
|
|
538
570
|
|
|
@@ -576,7 +608,7 @@ not share a session across those framed messages.
|
|
|
576
608
|
PowerShell 5.1-compatible example:
|
|
577
609
|
|
|
578
610
|
\`\`\`powershell
|
|
579
|
-
$env:MAIND_MCP_URL = "${
|
|
611
|
+
$env:MAIND_MCP_URL = "${t}"
|
|
580
612
|
$i1 = '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"setup-verify","version":"1.0"}}}'
|
|
581
613
|
$i2 = '{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}'
|
|
582
614
|
$i3 = '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_session_briefing","arguments":{"tools":["search_lessons"],"stack":["__STACK__"]}}}'
|
|
@@ -588,12 +620,12 @@ written config.
|
|
|
588
620
|
|
|
589
621
|
--- Preamble block ---
|
|
590
622
|
|
|
591
|
-
${
|
|
623
|
+
${Rr}`}a(IE,"buildAiPromptBody");function Tr(t,e,n){let r=n?`
|
|
592
624
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
593
625
|
set -euo pipefail
|
|
594
626
|
|
|
595
|
-
CONFIG_FILE="${
|
|
596
|
-
MAIND_MCP_URL="${
|
|
627
|
+
CONFIG_FILE="${t}"
|
|
628
|
+
MAIND_MCP_URL="${e}"${r}
|
|
597
629
|
|
|
598
630
|
mkdir -p "$(dirname "$CONFIG_FILE")"
|
|
599
631
|
|
|
@@ -623,11 +655,11 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
623
655
|
config.mcpServers.maind = server;
|
|
624
656
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
625
657
|
console.log("WROTE " + file);
|
|
626
|
-
NODE`}
|
|
658
|
+
NODE`}a(Tr,"buildJsonConfigInstaller");function CE(t){return`#!/usr/bin/env bash
|
|
627
659
|
set -euo pipefail
|
|
628
660
|
|
|
629
661
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
630
|
-
MAIND_MCP_URL="${
|
|
662
|
+
MAIND_MCP_URL="${t}"
|
|
631
663
|
MAIND_CLIENT_FAMILY="codex"
|
|
632
664
|
|
|
633
665
|
mkdir -p "$(dirname "$CONFIG_FILE")"
|
|
@@ -676,46 +708,46 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
676
708
|
|
|
677
709
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
678
710
|
console.log("WROTE " + file);
|
|
679
|
-
NODE`}
|
|
711
|
+
NODE`}a(CE,"buildCodexTomlInstaller");function OE(t=Ya){let e=`${t}${AE}`;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:IE(e)},{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:`{
|
|
680
712
|
"mcpServers": {
|
|
681
713
|
"maind": {
|
|
682
714
|
"command": "npx",
|
|
683
715
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
684
716
|
"env": {
|
|
685
717
|
"MAIND_CLIENT_FAMILY": "claude-code",
|
|
686
|
-
"MAIND_MCP_URL": "${
|
|
718
|
+
"MAIND_MCP_URL": "${e}"
|
|
687
719
|
}
|
|
688
720
|
}
|
|
689
721
|
}
|
|
690
|
-
}`,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:
|
|
722
|
+
}`,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:Tr(".mcp.json",e,"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:`{
|
|
691
723
|
"mcpServers": {
|
|
692
724
|
"maind": {
|
|
693
725
|
"command": "npx",
|
|
694
726
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
695
727
|
"env": {
|
|
696
728
|
"MAIND_CLIENT_FAMILY": "claude-desktop",
|
|
697
|
-
"MAIND_MCP_URL": "${
|
|
729
|
+
"MAIND_MCP_URL": "${e}"
|
|
698
730
|
}
|
|
699
731
|
}
|
|
700
732
|
}
|
|
701
|
-
}`,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:
|
|
733
|
+
}`,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:Tr("$HOME/Library/Application Support/Claude/claude_desktop_config.json",e,"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]
|
|
702
734
|
command = "npx"
|
|
703
735
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
704
736
|
|
|
705
737
|
[mcp_servers.maind.env]
|
|
706
738
|
MAIND_CLIENT_FAMILY = "codex"
|
|
707
|
-
MAIND_MCP_URL = "${
|
|
739
|
+
MAIND_MCP_URL = "${e}"`,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:CE(e)}]},{id:"copilot",label:"GitHub Copilot",description:"Browser-pairing VS Code workspace config for Copilot agent mode. 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:".mcp.json",lang:"json",template:`{
|
|
708
740
|
"mcpServers": {
|
|
709
741
|
"maind": {
|
|
710
742
|
"command": "npx",
|
|
711
743
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
712
744
|
"env": {
|
|
713
745
|
"MAIND_CLIENT_FAMILY": "copilot",
|
|
714
|
-
"MAIND_MCP_URL": "${
|
|
746
|
+
"MAIND_MCP_URL": "${e}"
|
|
715
747
|
}
|
|
716
748
|
}
|
|
717
749
|
}
|
|
718
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the workspace .mcp.json used by VS Code Copilot. 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-copilot.sh",lang:"bash",template:
|
|
750
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the workspace .mcp.json used by VS Code Copilot. 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-copilot.sh",lang:"bash",template:Tr(".mcp.json",e,"copilot")}]},{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
|
|
719
751
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
720
752
|
# CLAUDE.md (Claude Code)
|
|
721
753
|
# AGENTS.md (Codex, Windsurf, newer Cursor \u2014 cross-agent standard)
|
|
@@ -732,7 +764,7 @@ set -e
|
|
|
732
764
|
|
|
733
765
|
read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
|
|
734
766
|
|
|
735
|
-
${
|
|
767
|
+
${Rr}
|
|
736
768
|
MAIND_PREAMBLE_EOF
|
|
737
769
|
|
|
738
770
|
mkdir -p .github
|
|
@@ -777,22 +809,22 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
777
809
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
778
810
|
"env": {
|
|
779
811
|
"MAIND_CLIENT_FAMILY": "cursor",
|
|
780
|
-
"MAIND_MCP_URL": "${
|
|
812
|
+
"MAIND_MCP_URL": "${e}"
|
|
781
813
|
}
|
|
782
814
|
}
|
|
783
815
|
}
|
|
784
|
-
}`,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:
|
|
816
|
+
}`,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:Tr("$HOME/.cursor/mcp.json",e,"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:`{
|
|
785
817
|
"mcpServers": {
|
|
786
818
|
"maind": {
|
|
787
819
|
"command": "npx",
|
|
788
820
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
789
821
|
"env": {
|
|
790
822
|
"MAIND_CLIENT_FAMILY": "windsurf",
|
|
791
|
-
"MAIND_MCP_URL": "${
|
|
823
|
+
"MAIND_MCP_URL": "${e}"
|
|
792
824
|
}
|
|
793
825
|
}
|
|
794
826
|
}
|
|
795
|
-
}`,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:
|
|
827
|
+
}`,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:Tr("$HOME/.codeium/windsurf/mcp_config.json",e,"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";
|
|
796
828
|
|
|
797
829
|
const mcp = new MultiServerMCPClient({
|
|
798
830
|
maind: {
|
|
@@ -800,7 +832,7 @@ const mcp = new MultiServerMCPClient({
|
|
|
800
832
|
command: "npx",
|
|
801
833
|
args: ["-y", "@maind-dev/mcp-bridge"],
|
|
802
834
|
env: {
|
|
803
|
-
MAIND_MCP_URL: "${
|
|
835
|
+
MAIND_MCP_URL: "${e}",
|
|
804
836
|
},
|
|
805
837
|
},
|
|
806
838
|
});
|
|
@@ -811,17 +843,17 @@ const tools = await mcp.getTools();
|
|
|
811
843
|
"command": "npx",
|
|
812
844
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
813
845
|
"env": {
|
|
814
|
-
"MAIND_MCP_URL": "${
|
|
846
|
+
"MAIND_MCP_URL": "${e}"
|
|
815
847
|
}
|
|
816
|
-
}`}]}
|
|
817
|
-
`:
|
|
818
|
-
`;return await Y(
|
|
848
|
+
}`}]}a(OE,"buildSnippetTemplates");var sj=OE(Ya);Ke();var DE="## maind MCP integration";function ME(t){return[{key:"preamble:CLAUDE.md",path:Ve.join(t.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Ve.join(t.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Ve.join(t.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Ve.join(t.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Ve.join(t.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Ve.join(t.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}a(ME,"buildPreambleTargets");async function $m(t,e=!1){let n=ME(t),r=[];for(let i of n)r.push(await PE(i,e));return r}a($m,"writePreambleFiles");async function PE(t,e){try{if(t.mayNeedParentDir&&!e&&await za(Ve.dirname(t.path)),await Cm(t.path,DE))return{target:t.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await ie(t.path);if(e)return{target:t.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:t.path};let i=r===null||r.length===0?`${Rr}
|
|
849
|
+
`:LE(r)+`${Rr}
|
|
850
|
+
`;return await Y(t.path,i),{target:t.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:t.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:t.key,action:"append",status:"failed",detail:r}}}a(PE,"writeOnePreambleFile");function LE(t){return t.endsWith(`
|
|
819
851
|
|
|
820
|
-
`)?
|
|
821
|
-
`)?
|
|
822
|
-
`:
|
|
852
|
+
`)?t:t.endsWith(`
|
|
853
|
+
`)?t+`
|
|
854
|
+
`:t+`
|
|
823
855
|
|
|
824
|
-
`}
|
|
856
|
+
`}a(LE,"ensureTrailingBlankLine");rc();Dn();Ke();import*as Bm from"node:readline";var Gt="config:auto_working_paths",qE=`
|
|
825
857
|
Enable presence enrichment (auto working_paths)?
|
|
826
858
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
827
859
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -830,34 +862,34 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
830
862
|
absolute paths. Server-side these paths are account-private (org members never
|
|
831
863
|
see them) and revocable any time on the dashboard consent page or via
|
|
832
864
|
{"auto_working_paths": false} in the bridge config.
|
|
833
|
-
[y/N]: `;async function
|
|
834
|
-
`;if(
|
|
835
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=
|
|
836
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return
|
|
837
|
-
`),2;let
|
|
865
|
+
[y/N]: `;async function Km(t){let e=t.configPath??ze(),n={};try{let o=await ie(e);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:Gt,action:"skip",status:"skipped",detail:`already decided (${n.auto_working_paths?"enabled":"disabled"}) in ${e}`};let r;if(t.explicitFlag)r=!0;else if(t.isInteractive){if(t.dryRun)return{target:Gt,action:"merge",status:"would-merge",detail:`${e} (would prompt for consent in real run)`};r=await(t.promptFn??YE)(t.out,qE)}else return{target:Gt,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Gt,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)+`
|
|
866
|
+
`;if(t.dryRun)return{target:Gt,action:"merge",status:"would-merge",detail:e};try{await Y(e,s,384)}catch(o){return{target:Gt,action:"merge",status:"failed",detail:`write: ${o instanceof Error?o.message:String(o)}`}}return{target:Gt,action:"merge",status:"merged",detail:`${e} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}a(Km,"applyWorkingPathsConsent");async function YE(t,e){t.write(e);let n=Bm.createInterface({input:process.stdin,output:t,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}a(YE,"promptYesNoDefaultNo");re();async function Vm(t){let e=t.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs??1e4);try{let i=await e(t.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t.token,device_id:t.deviceId,label:t.label,client_meta:t.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(Vm,"exchangeOneClickToken");async function Ym(t){let e="browser-pair";if(t.token!==null)try{let s=JE(t.token);return t.dryRun?{apiKey:s,result:{target:e,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(xr(),jt(s),{apiKey:s,result:{target:e,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(s){return{apiKey:null,result:{target:e,action:"token",status:"failed",detail:zm(s)}}}let n=null;if(t.oneClickToken!==null&&t.oneClickExchangeUrl!==null){if(t.dryRun)return{apiKey:null,result:{target:e,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let s=Ki(t.bridgeVersion),o=await Vm({token:t.oneClickToken,url:t.oneClickExchangeUrl,deviceId:s.device_id,label:mm(),clientMeta:{...s}});if(o.ok)return xr(),jt(o.apiKey),{apiKey:o.apiKey,result:{target:e,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${o.plan})`}};n=o.reason,qm(t).write(`[maind-mcp-bridge] one-click exchange failed (${o.reason}) \u2014 falling back to browser pairing.
|
|
867
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=K();if(i!==null)return{apiKey:i,result:{target:e,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(t.dryRun)return{apiKey:null,result:{target:e,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await Nn(t.bridgeVersion,qm(t));return s===null?{apiKey:null,result:{target:e,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:s.apiKey,result:{target:e,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${s.plan})${r}`}}}catch(s){return{apiKey:null,result:{target:e,action:"pair",status:"failed",detail:zm(s)}}}}a(Ym,"pairOrUseToken");function JE(t){let e=t.trim();if(e.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(e))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 e}a(JE,"validateTokenShape");function zm(t){return t instanceof Error?t.message:String(t)}a(zm,"errMessage");function qm(t){return t.out??process.stdout}a(qm,"out");An();var XE="install-completed",ZE=3e3;async function Jm(t){if(!t.enabled||t.apiKey===null)return;let e=Rn(XE),n={installer_version:t.installerVersion,wall_clock_ms:t.wallClockMs,os_family:process.platform,node_major:e0(process.version),summary:{total:t.summary.total,ok:t.summary.ok,needs_decision:t.summary.needsDecision,failed:t.summary.failed},step_status_counts:QE(t.steps),client_family_filter:t.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),ZE);try{await fetch(e,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${t.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(i)}}a(Jm,"postInstallTelemetry");function QE(t){let e={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of t)e[n.status]=(e[n.status]??0)+1;return e}a(QE,"countStatuses");function e0(t){let e=/^v?(\d+)\./.exec(t);return e===null?0:Number.parseInt(e[1],10)}a(e0,"parseNodeMajor");Or();var D0="https://mcp.maind.dev/mcp";async function Wh(t){let e=Date.now(),n;try{n=_m(t)}catch(k){if(k instanceof Ne)return process.stderr.write(`error: ${k.message}
|
|
868
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return bm(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=Hh.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
869
|
+
`),2;let o;if(n.projectRoot!==null)o=n.projectRoot;else{let k=await xm(process.cwd());if(k.length===0)o=await km(process.cwd());else if(k.length===1)o=k[0];else{let x=await Em(k,i);if(x===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
|
|
838
870
|
`);for(let S of k)process.stderr.write(` candidate: ${S}
|
|
839
|
-
`);return 2}
|
|
840
|
-
`),process.stdout.write(`maind install \u2014 project root: ${
|
|
871
|
+
`);return 2}o=x}}let c=new Vi,l=(process.env.MAIND_MCP_URL??"").trim()||D0;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
872
|
+
`),process.stdout.write(`maind install \u2014 project root: ${o}
|
|
841
873
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
842
874
|
|
|
843
|
-
`);let
|
|
844
|
-
pairing failed: ${
|
|
875
|
+
`);let d=await Ym({bridgeVersion:U,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(d.result),d.result.status==="failed")return process.stderr.write(`
|
|
876
|
+
pairing failed: ${d.result.detail??"unknown"}
|
|
845
877
|
Skipping remaining steps.
|
|
846
|
-
`),c.print(process.stdout),2;let
|
|
878
|
+
`),c.print(process.stdout),2;let u=Ji({projectRoot:o,homeDir:s,platform:process.platform,env:process.env}),p=Yi(u);if(p=Im(p,n.client),n.skipCodex&&(p=p.filter(k=>k.key!=="codex-cli")),p.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
|
|
847
879
|
`:`error: no client targets selected (did you skip all of them?)
|
|
848
|
-
`),c.print(process.stdout),2;for(let k of p){let x=
|
|
880
|
+
`),c.print(process.stdout),2;for(let k of p){let x=Nm({mcpUrl:l,clientFamily:k.clientFamilyEnv}),S;k.kind==="json"?S=await Pm(k,x,n.dryRun):S=await Lm(k,x,n.dryRun),c.add(S)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let k=await $m({projectRoot:o,homeDir:s},n.dryRun);for(let x of k)c.add(x)}let h={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await Wm(h));for(let k of await Gm(h))c.add(k);c.add(await Km({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let m=Ph();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 Jm({enabled:n.telemetry||n.full,installerVersion:U,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-e,apiKey:d.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let g=c.exitCode(),y=((Date.now()-e)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
849
881
|
DRY RUN finished in ${y}s. No files were modified. Re-run without --dry-run to apply.
|
|
850
882
|
`):process.stdout.write(`
|
|
851
883
|
Finished in ${y}s. Restart your MCP client so it picks up the new server entry.
|
|
852
|
-
`);let _=
|
|
884
|
+
`);let _=Ie({entryPath:Ce(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),w=_.fallbackReason===null?`${In(_)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${w}
|
|
853
885
|
`),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.
|
|
854
|
-
`),g}o(ch,"runInstall");vr();import{readFileSync as $E}from"node:fs";import{join as lh}from"node:path";function ns(e){return e?Math.ceil(e.length/4):0}o(ns,"estimateTokens");var dh=1e6,rs=class{static{o(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function uh(e){try{let t=$E(e,"utf8");return t.length>dh?t.slice(0,dh):t}catch{return""}}o(uh,"readFileCapped");function LE(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}o(LE,"distinctFilePaths");function ph(e,t,n,r){try{let i=ns(n);if(e==="codebase_search"){let s=LE(t);if(s.length===0)return 0;let a=0;for(let c of s)a+=ns(uh(lh(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let s=t?.filePath;if(typeof s!="string"||s.length===0)return 0;let a=ns(uh(lh(r,s)));return Math.max(0,a-i)}return 0}catch{return 0}}o(ph,"measureLocalToolSaved");gn();vr();import{createHash as FE}from"node:crypto";function is(e){return FE("sha256").update(e,"utf8").digest("hex")}o(is,"nodeKeyHash");var jE=["module","class","interface","function","method","type_alias","enum","variable"],Qa=[{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:jE,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. CALLS/EXTENDS are best-effort name heuristics.",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 four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) 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 keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",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:"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."}}}}],hh=new Set(Qa.map(e=>e.name));function J(e){return typeof e=="string"&&e.length>0?e:void 0}o(J,"str");var UE=10;function HE(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=UE&&r++,c>i&&(i=c);for(let u of a.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=a.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>s&&(s=u)}}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}}o(HE,"aggregateHistoryContext");function Ft(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Ft,"num");function fh(e){if(e===void 0)return{repoRoot:fe(),scanDirs:void 0};let t=ts(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(fh,"anchorRepo");function mh(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}o(mh,"dirNotFound");async function gh(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,s=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=J(n.for_path);if(i!==void 0){let d=ih(i);if(d===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 At(d.repoRoot,d.repoRelPath,{minFiles:r}),h=p.namespace,m=o(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:d.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(d=>typeof d=="string"):void 0;if(s!==void 0&&s.length>0){let d=new Map,p=[];for(let x of s){let S=ts(x);if(S===null){p.push(x);continue}let I=d.get(S.repoRoot)??new Set;I.add(S.repoRelDir),d.set(S.repoRoot,I)}if(d.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[x,S]of d){let I=[...S],$=I.includes(""),H=await Et(x,{dirs:$?void 0:I,minFiles:r});h.push({repo_root:x,dirs:$?null:I}),m.push(...H.findings),g.push(...H.facts.namespaces.map(U=>({repo_root:x,dir:U.dir,prefix:U.prefix,file_count:U.fileCount}))),y.push(...H.facts.skipped)}let _=m.filter(x=>x.status==="open"),w=m.filter(x=>x.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:w.length,findings:_,preexisting:w.map(x=>`${x.namespace.prefix}${x.number}`),namespaces:g,skipped:y,scanned:h,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=fe(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.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:J(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=o(p=>r.findings.filter(h=>h.status===p),"of"),s=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="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.",d=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:a.length,preexisting_count:c.length,findings:[...s,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${s.length-d.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.`)+" "+u}}case"check_theme_class_drift":{let r=J(n.dir),i,s;if(r!==void 0){let d=ts(r);if(d===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=d.repoRoot,s=d.repoRelDir===""?void 0:[d.repoRelDir]}else i=fe(),s=void 0;let a=It(i,{dirs:s,baseRef:J(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=fh(J(n.dir));if(r===null)return mh("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Rt(r.repoRoot,{dirs:r.scanDirs,baseRef:J(n.base_ref),includeBaseline:n.include_baseline!==!1}),s="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+s}}case"check_migration_ledger_drift":{let r=fh(J(n.dir));if(r===null)return mh("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Ea(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:J(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 a=o(p=>i.findings.filter(h=>h.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=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:u.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:d,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. 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 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=J(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:J(n.kind),limit:Ft(n.limit)})).map(s=>({...s,nodeKeyHash:is(s.nodeKey)}))}case"codebase_trace":{let r=J(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:Ft(n.max_depth),limit:Ft(n.limit)})}case"codebase_snippet":{let r=J(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:is(r)}}case"codebase_map":return e.getArchitecture({topN:Ft(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ft(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:is(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:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ft(n.limit)}),i;if(n.include_history!==!1)try{i=HE(await e.fileHistory({since:J(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:J(n.since)})}catch(l){s=Ee(Ct(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,...r.headSha?{head_sha:r.headSha}:{},dirty:r.dirty,...r.baseSha?{base_sha:r.baseSha}:{},code_index_version:Df,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.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:is(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. Persisting a replayable record additionally needs commit_sha / diff_stats.head_sha.`}}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:J(n.since),limit:Ft(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}o(gh,"dispatchLocalTool");var ss=class{constructor(t=oh,n=null,r=fe){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Qa}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&hh.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await gh(this.getEngine(),i,s),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=nh(a)?`${rh} (${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=ph(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};bn();var GE="/mcp-client-metrics-ingest",WE=4e3,BE="codebase_search_tokens_saved";async function yh(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${hr()}${GE}`,n=new AbortController,r=setTimeout(()=>n.abort(),WE);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:BE,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)}
|
|
855
|
-
`),!1}finally{clearTimeout(r)}}
|
|
856
|
-
`).filter(
|
|
857
|
-
`),process.exit(1)),
|
|
858
|
-
`),process.exit(1)),
|
|
859
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
860
|
-
`),process.exit(0));let
|
|
861
|
-
`),n=await
|
|
862
|
-
`))}
|
|
886
|
+
`),g}a(Wh,"runInstall");Or();import{readFileSync as M0}from"node:fs";import{join as Gh}from"node:path";function ps(t){return t?Math.ceil(t.length/4):0}a(ps,"estimateTokens");var Bh=1e6,fs=class{static{a(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(e){!Number.isFinite(e)||e<=0||(this.pendingTokens+=Math.floor(e),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let e={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,e}};function Kh(t){try{let e=M0(t,"utf8");return e.length>Bh?e.slice(0,Bh):e}catch{return""}}a(Kh,"readFileCapped");function P0(t){if(!Array.isArray(t))return[];let e=new Set;for(let n of t){let r=n?.filePath;typeof r=="string"&&r.length>0&&e.add(r)}return[...e]}a(P0,"distinctFilePaths");function Vh(t,e,n,r){try{let i=ps(n);if(t==="codebase_search"){let s=P0(e);if(s.length===0)return 0;let o=0;for(let c of s)o+=ps(Kh(Gh(r,c)));return Math.max(0,o-i)}if(t==="codebase_snippet"){let s=e?.filePath;if(typeof s!="string"||s.length===0)return 0;let o=ps(Kh(Gh(r,s)));return Math.max(0,o-i)}return 0}catch{return 0}}a(Vh,"measureLocalToolSaved");En();Or();import{createHash as L0}from"node:crypto";function ms(t){return L0("sha256").update(t,"utf8").digest("hex")}a(ms,"nodeKeyHash");var $0=["module","class","interface","function","method","type_alias","enum","variable"],gc=[{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:$0,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 four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) 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 keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",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:"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."}}}}],Yh=new Set(gc.map(t=>t.name));function J(t){return typeof t=="string"&&t.length>0?t:void 0}a(J,"str");var F0=10;function j0(t,e=Date.now()){if(t.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let o of t.history){let c=o.ownership?.commitsInWindow??o.lastCommits.length;c>=F0&&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:t.ownershipWindowCommits,files_scanned:t.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((e-s)/864e5)):0}}a(j0,"aggregateHistoryContext");function Kt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}a(Kt,"num");function zh(t){if(t===void 0)return{repoRoot:fe(),scanDirs:void 0};let e=us(t);return e===null?null:{repoRoot:e.repoRoot,scanDirs:e.repoRelDir===""?void 0:[e.repoRelDir]}}a(zh,"anchorRepo");function qh(t,e){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. ${e} 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 ${t}.`}}a(qh,"dirNotFound");async function Jh(t,e,n){switch(e){case"codebase_index":return t.indexRepository({full:n.full===!0});case"codebase_status":return t.status();case"check_divergence":{let r=await t.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=J(n.for_path);if(i!==void 0){let u=Fh(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 Ot(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 x of s){let S=us(x);if(S===null){p.push(x);continue}let A=u.get(S.repoRoot)??new Set;A.add(S.repoRelDir),u.set(S.repoRoot,A)}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[x,S]of u){let A=[...S],D=A.includes(""),F=await Ct(x,{dirs:D?void 0:A,minFiles:r});h.push({repo_root:x,dirs:D?null:A}),m.push(...F.findings),g.push(...F.facts.namespaces.map(j=>({repo_root:x,dir:j.dir,prefix:j.prefix,file_count:j.fileCount}))),y.push(...F.facts.skipped)}let _=m.filter(x=>x.status==="open"),w=m.filter(x=>x.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:w.length,findings:_,preexisting:w.map(x=>`${x.namespace.prefix}${x.number}`),namespaces:g,skipped:y,scanned:h,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let o=fe(),c=await t.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 t.checkSpecDrift({manifestPath:J(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=J(n.dir),i,s;if(r!==void 0){let u=us(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=Pt(i,{dirs:s,baseRef:J(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=zh(J(n.dir));if(r===null)return qh("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Mt(r.repoRoot,{dirs:r.scanDirs,baseRef:J(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=zh(J(n.dir));if(r===null)return qh("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Fa(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:J(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=J(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await t.searchGraph(r,{kind:J(n.kind),limit:Kt(n.limit)})).map(s=>({...s,nodeKeyHash:ms(s.nodeKey)}))}case"codebase_trace":{let r=J(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return t.tracePath(r,{direction:i,maxDepth:Kt(n.max_depth),limit:Kt(n.limit)})}case"codebase_snippet":{let r=J(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await t.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:ms(r)}}case"codebase_map":return t.getArchitecture({topN:Kt(n.top_n)});case"codebase_changes":{let r=await t.changedSymbols({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Kt(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:ms(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 t.reviewChanges({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Kt(n.limit)}),i;if(n.include_history!==!1)try{i=j0(await t.fileHistory({since:J(n.since),limit:1}))}catch{i=void 0}let s;try{s=await t.reviewDetectors({baseRef:J(n.since)})}catch(l){s=Ae(Lt(`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,...r.headSha?{head_sha:r.headSha}:{},dirty:r.dirty,...r.baseSha?{base_sha:r.baseSha}:{},code_index_version:im,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:ms(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 []. Persisting a replayable record additionally needs commit_sha / diff_stats.head_sha.`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await t.fileHistory({paths:r,since:J(n.since),limit:Kt(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: ${e}`)}}a(Jh,"dispatchLocalTool");var hs=class{constructor(e=Uh,n=null,r=fe){this.makeEngine=e;this.aggregator=n;this.resolveRoot=r}static{a(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return gc}handlesToolCall(e,n){if(e!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Yh.has(r)}async handleToolCall(e,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let o=await Jh(this.getEngine(),i,s),c=JSON.stringify(o,null,2);return this.recordSavings(i,o,c),JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:c}]}})}catch(o){let c=o instanceof Error?o.message:String(o),l=Lh(o)?`${$h} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(e){try{let n=JSON.parse(e);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 e}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(e,n,r){if(this.aggregator&&!(e!=="codebase_search"&&e!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Vh(e,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};An();var U0="/mcp-client-metrics-ingest",H0=4e3,W0="codebase_search_tokens_saved";async function Xh(t){if(!Number.isFinite(t.tokensSaved)||t.tokensSaved<=0)return!1;let e=`${Sr()}${U0}`,n=new AbortController,r=setTimeout(()=>n.abort(),H0);try{let i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.apiKey}`,"x-maind-device-id":t.deviceId,"user-agent":`@maind-dev/mcp-bridge/${t.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:t.sessionId,metric_key:W0,metric_value:Math.floor(t.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)}
|
|
887
|
+
`),!1}finally{clearTimeout(r)}}a(Xh,"postSavingsMetric");bc();ys();bs();Gn();import{join as SR}from"node:path";var ER="<synthetic>";function Wg(t){return t===null?null:typeof t.transcript_path=="string"&&t.transcript_path.length>0?t.transcript_path:!t.transcript_stem||!t.cwd?null:SR(Wc,Gc(t.cwd),`${t.transcript_stem}.jsonl`)}a(Wg,"transcriptPathFromSideChannel");var Rs=class{constructor(e){this.deps=e}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??Hc)(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!==ER&&(this.model=s.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let e=null;try{e=this.deps.fallbackModel?.()??null}catch{e=null}return{model:this.model??e,title:this.title}}};import{execFile as TR}from"node:child_process";var RR=8,AR=32;function NR(t){return t.split(`
|
|
888
|
+
`).filter(e=>e.trim().length>0).map(e=>(e.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(e=>e.length>0).slice(0,AR)}a(NR,"parsePorcelain");function IR(t,e=RR){let n=[];for(let r of t){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>=e))break}return n}a(IR,"condenseToDirs");async function Gg(t=CR){let e=await t();if(e===null)return null;let n=IR(NR(e));return n.length>0?n:null}a(Gg,"deriveWorkingPaths");async function CR(){return await new Promise(t=>{TR("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(e,n)=>t(e?null:n))})}a(CR,"defaultGitStatus");var $I=1,FI=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function jI(t){return FI.includes(t)}a(jI,"isHookSubcommand");var UI=6e4;async function HI(){let t=(process.env.MAIND_API_KEY??"").trim();if(t.length>0)return t!==K()&&jt(t),t;let e=K();if(e!==null)return e;let n=await Nn(U);return n===null&&(Ut("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:U}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
889
|
+
`),process.exit(1)),Ut("paired",null,{version:U}),n.apiKey}a(HI,"ensureApiKey");async function WI(t){let e=await Nn(U);return e===null&&(Ut("auth_failed",`${t}; re-authorization did not complete`,{version:U}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
890
|
+
`),process.exit(1)),Ut("paired",null,{version:U}),e.apiKey}a(WI,"reauth");async function GI(){let t=process.argv.slice(2).find(_=>!_.startsWith("-"));if(t==="install"){let _=process.argv.indexOf("install"),w=process.argv.slice(_+1),k=await Wh(w);process.exit(k)}if(t==="doctor"){let{runDoctor:_}=await Promise.resolve().then(()=>(Jc(),Jg));process.exit(await _(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(t==="on-session-end"){let{runOnSessionEnd:_}=await Promise.resolve().then(()=>(Gy(),Wy));process.exit(await _())}if(t==="guard"){let _=process.argv.indexOf("guard"),{runGuard:w}=await Promise.resolve().then(()=>(Zy(),Xy));process.exit(await w(process.argv.slice(_+1)))}if(t==="guard-inject"){let{runGuardInject:_}=await Promise.resolve().then(()=>(i_(),r_));process.exit(await _())}if(t==="guard-gate"){let{runGuardGate:_}=await Promise.resolve().then(()=>(l_(),c_));process.exit(await _())}if(t==="guard-stop"){let{runGuardStop:_}=await Promise.resolve().then(()=>(p_(),u_));process.exit(await _())}if(t==="gateway"){let _=process.argv.indexOf("gateway"),{runGateway:w}=await Promise.resolve().then(()=>(J_(),Y_));process.exit(await w(process.argv.slice(_+1)))}if(t==="guard-cross-observe"){let{runGuardCrossObserve:_}=await Promise.resolve().then(()=>(vl(),wl));process.exit(await _())}if(t==="guard-cross-check"){let{runGuardCrossCheck:_}=await Promise.resolve().then(()=>(vl(),wl));process.exit(await _())}if(t==="on-index-refresh"){let{runOnIndexRefresh:_}=await Promise.resolve().then(()=>(Sl(),xl));process.exit(await _())}if(t==="index-refresh-run"){let{runIndexRefreshWorker:_}=await Promise.resolve().then(()=>(Sl(),xl));process.exit(await _())}if(t!==void 0&&jI(t)){let _=await Promise.resolve().then(()=>(sl(),Iy)),w={"on-session-start":_.runOnSessionStart,"on-tool-use":_.runOnToolUse,"on-file-write":_.runOnFileWrite,"on-file-edit":_.runOnFileEdit,"on-repo-health":_.runOnRepoHealth,"on-write-health":_.runOnWriteHealth,"sync-config":_.runSyncConfig,flush:_.runFlush,status:_.runHookStatus}[t];process.exit(await w())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(U+`
|
|
891
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(BI(),process.exit(0)),process.argv.includes("--reauth")&&(xr(),await Nn(U,process.stdout)===null&&process.exit(1),Ut("paired",null,{version:U}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
892
|
+
`),process.exit(0));let e=ne(),n=await HI(),r=z(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new fs:null,o=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new hs(void 0,s),c=`bridge-${LI()}`,l=a(async()=>{if(!s)return;let _=s.takePending();_.tokens<=0||await Xh({apiKey:n,deviceId:e,sessionId:c,tokensSaved:_.tokens,bridgeVersion:U})},"flushSavings"),d=s?setInterval(()=>{l()},UI):null;d?.unref();let u=null,p=new _s({projectKey:r}),h=new Rs({resolvePath:a(()=>Wg(p.sideChannel()),"resolvePath"),fallbackModel:a(()=>p.sideChannel()?.model??null,"fallbackModel")}),m=new gs({projectKey:r,identity:p,sessionMeta:a(()=>h.read(),"sessionMeta"),postToolCall:a((_,w)=>u===null?Promise.reject(new Error("presence: no active forwarder")):u.postPresenceToolCall(_,w),"postToolCall"),deriveWorkingPaths:a(()=>Gg(),"deriveWorkingPaths"),snapshot:r!==null?cg({projectKey:r}):void 0}),g=m.isEnabled?setInterval(()=>{m.pollActivity()},eg):null;if(g?.unref(),m.isEnabled){let _=a(w=>{m.end().finally(()=>process.exit(w))},"endAndExit");process.on("SIGTERM",()=>_(143)),process.on("SIGINT",()=>_(130))}let y=0;try{for(;;){let _=new Gi({apiKey:n,deviceId:e,bridgeVersion:U,projectKey:r,localRouter:o,presence:m,onConnectionOutcome:a((w,k)=>Ut(w,k,{version:U}),"onConnectionOutcome")});u=_;try{await _.run();return}catch(w){if(w instanceof kr&&y<$I){y+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${w.message}; re-authorizing\u2026
|
|
893
|
+
`),n=await WI(w.reason);continue}throw w}}}finally{d&&clearInterval(d),g&&clearInterval(g),await m.end(),await l()}}a(GI,"main");function BI(){let t=["","@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 skip --session <id> --reason "\u2026" logged override (block-gate exit)'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop)","","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_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(t.join(`
|
|
894
|
+
`))}a(BI,"printHelp");GI().catch(t=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${t instanceof Error?t.message:String(t)}
|
|
863
895
|
`),process.exit(1)});
|