@maind-dev/mcp-bridge 0.80.1 → 0.82.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 +261 -248
- package/build/meta.json +1 -1
- package/package.json +2 -1
package/build/index.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var rd=Object.defineProperty;var a=(t,e)=>rd(t,"name",{value:e,configurable:!0});var _=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>{for(var n in e)rd(t,n,{get:e[n],enumerable:!0})};function sd(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 dn(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 so(t,e,n,r){return{at:r,event:t,server:e,tool:n}}function oo(t,e,n,r,i,s){return{at:r,event:t,server:e,tool:n,convention_id:i,convention_version:s}}function ao(t,e,n,r){return{at:r,event:t,server:e,tool:n}}var co=_(()=>{"use strict";a(sd,"parseFrame");a(dn,"denyResult");a(so,"toolEvent");a(oo,"policyEvent");a(ao,"shaEvent")});import{execFileSync as cd}from"node:child_process";function ld(t){return t.verdict==="fabricated"&&(t.matchedPrefixLen??0)>=yw}function _w(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 mw){let o=r[s];typeof o=="string"&&od.test(o)&&i.push({field:s,sha:o})}for(let[s,o]of hw){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[o];typeof l=="string"&&od.test(l)&&i.push({field:`${s}.${o}`,sha:l})}return i}function bw(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,ad);for(let i=ad;i>=gw;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 un(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 dd(){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 ii(t=process.cwd()){try{let n=cd("git",["rev-parse","--show-toplevel"],{cwd:t,env:dd(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function ww(t){return e=>{try{let r=cd("git",["rev-parse","--verify","--quiet",`${e}^{commit}`],{cwd:t,env:dd(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function si(t,e){if(e===null)return[];let n=_w(t);if(n.length===0)return[];let r=ww(e),i=[];for(let{field:s,sha:o}of n){let c=bw(o,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var mw,hw,od,gw,ad,yw,lo=_(()=>{"use strict";mw=["commit_sha","base_sha","head_sha"],hw=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],od=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,gw=7,ad=12,yw=10;a(ld,"isDenyGrade");a(_w,"extractShaArgs");a(bw,"classifySha");a(un,"shaFindingText");a(dd,"cleanGitEnv");a(ii,"resolveRepoRootForSha");a(ww,"gitShaResolver");a(si,"inspectLineForShas")});var pd=_(()=>{"use strict"});var L,po,T,Te,ar=_(()=>{(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})(L||(L={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(po||(po={}));T=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Te=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 x,vw,ce,oi=_(()=>{ar();x=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),vw=a(t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),ce=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,L.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()}};ce.create=t=>new ce(t)});var kw,je,fo=_(()=>{oi();ar();kw=a((t,e)=>{let n;switch(t.code){case x.invalid_type:t.received===T.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,L.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(t.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(t.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(t.options)}, received '${t.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:typeof 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}"`:L.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case x.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 x.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 x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=e.defaultError,L.assertNever(t)}return{message:n}},"errorMap"),je=kw});function xw(t){fd=t}function pn(){return fd}var fd,ai=_(()=>{fo();fd=je;a(xw,"setErrorMap");a(pn,"getErrorMap")});function E(t,e){let n=pn(),r=cr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===je?void 0:je].filter(i=>!!i)});t.common.issues.push(r)}var cr,Sw,q,C,bt,Q,ci,li,et,fn,mo=_(()=>{ai();fo();cr=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"),Sw=[];a(E,"addIssueToContext");q=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 C;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 C;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}}},C=Object.freeze({status:"aborted"}),bt=a(t=>({status:"dirty",value:t}),"DIRTY"),Q=a(t=>({status:"valid",value:t}),"OK"),ci=a(t=>t.status==="aborted","isAborted"),li=a(t=>t.status==="dirty","isDirty"),et=a(t=>t.status==="valid","isValid"),fn=a(t=>typeof Promise<"u"&&t instanceof Promise,"isAsync")});var md=_(()=>{});var I,hd=_(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}))});function M(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 bd(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 Hw(t){return new RegExp(`^${bd(t)}$`)}function wd(t){let e=`${_d}T${bd(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 Bw(t,e){return!!((e==="v4"||!e)&&Mw.test(t)||(e==="v6"||!e)&&Lw.test(t))}function Ww(t,e){if(!Nw.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 Gw(t,e){return!!((e==="v4"||!e)&&Pw.test(t)||(e==="v6"||!e)&&$w.test(t))}function Kw(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 mn(t){if(t instanceof le){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=fe.create(mn(r))}return new le({...t._def,shape:a(()=>e,"shape")})}else return t instanceof Be?new Be({...t._def,type:mn(t.element)}):t instanceof fe?fe.create(mn(t.unwrap())):t instanceof Re?Re.create(mn(t.unwrap())):t instanceof Ae?Ae.create(t.items.map(e=>mn(e))):t}function go(t,e){let n=Te(t),r=Te(e);if(t===e)return{valid:!0,data:t};if(n===T.object&&r===T.object){let i=L.objectKeys(e),s=L.objectKeys(t).filter(c=>i.indexOf(c)!==-1),o={...t,...e};for(let c of s){let l=go(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=go(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 vd(t,e){return new Nt({values:t,typeName:O.ZodEnum,...M(e)})}function yd(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function kd(t,e={},n){return t?nt.create().superRefine((r,i)=>{let s=t(r);if(s instanceof Promise)return s.then(o=>{if(!o){let c=yd(e,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let o=yd(e,r),c=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:c})}}):nt.create()}var me,gd,P,Ew,Tw,Aw,Rw,Iw,Nw,Cw,Ow,Dw,ho,Mw,Pw,Lw,$w,Fw,jw,_d,Uw,tt,wt,vt,kt,xt,hn,St,Et,nt,He,_e,gn,Be,le,Tt,Ue,di,At,Ae,ui,yn,_n,pi,Rt,It,Nt,Ct,rt,he,fe,Re,Ot,Dt,bn,Vw,lr,dr,Mt,qw,O,zw,xd,Sd,Yw,Jw,Ed,Xw,Zw,Qw,ev,tv,nv,rv,iv,sv,ov,av,cv,lv,dv,uv,pv,fv,mv,hv,gv,yv,_v,bv,wv,vv,kv,xv,Sv,Ev,Tv,Av,Rv,Iv,Nv,Td=_(()=>{oi();ai();hd();mo();ar();me=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}},gd=a((t,e)=>{if(et(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 ce(t.common.issues);return this._error=n,this._error}}},"handleResult");a(M,"processCreateParams");P=class{static{a(this,"ZodType")}get description(){return this._def.description}_getType(e){return Te(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Te(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:Te(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(fn(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:Te(e)},i=this._parseSync({data:e,path:r.path,parent:r});return gd(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Te(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return et(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=>et(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:Te(e)},i=this._parse({data:e,path:r.path,parent:r}),s=await(fn(i)?i:Promise.resolve(i));return gd(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:x.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 he({schema:this,typeName:O.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 fe.create(this,this._def)}nullable(){return Re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Be.create(this)}promise(){return rt.create(this,this._def)}or(e){return Tt.create([this,e],this._def)}and(e){return At.create(this,e,this._def)}transform(e){return new he({...M(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ot({...M(this._def),innerType:this,defaultValue:n,typeName:O.ZodDefault})}brand(){return new lr({typeName:O.ZodBranded,type:this,...M(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Dt({...M(this._def),innerType:this,catchValue:n,typeName:O.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return dr.create(this,e)}readonly(){return Mt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ew=/^c[^\s-]{8,}$/i,Tw=/^[0-9a-z]+$/,Aw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rw=/^[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,Iw=/^[a-z0-9_-]{21}$/i,Nw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cw=/^[-+]?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)?)??$/,Ow=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Dw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Mw=/^(?:(?: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])$/,Pw=/^(?:(?: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])$/,Lw=/^(([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]))$/,$w=/^(([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])$/,Fw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_d="((\\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])))",Uw=new RegExp(`^${_d}$`);a(bd,"timeRegexSource");a(Hw,"timeRegex");a(wd,"datetimeRegex");a(Bw,"isValidIP");a(Ww,"isValidJWT");a(Gw,"isValidCidr");tt=class t extends P{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:x.invalid_type,expected:T.string,received:s.parsedType}),C}let r=new q,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:x.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:x.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:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&E(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ow.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"email",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")ho||(ho=new RegExp(Dw,"u")),ho.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"emoji",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Rw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"uuid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Iw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"nanoid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Ew.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"cuid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Tw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"cuid2",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Aw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"ulid",code:x.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:x.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:x.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:x.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:x.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:x.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?wd(s).test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:x.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Uw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:x.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Hw(s).test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:x.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Cw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"duration",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Bw(e.data,s.version)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"ip",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Ww(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"jwt",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Gw(e.data,s.version)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"cidr",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Fw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"base64",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?jw.test(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{validation:"base64url",code:x.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:x.invalid_string,...I.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.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,...I.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,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...I.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...I.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...I.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...I.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...I.errToObj(n)})}nonempty(e){return this.min(1,I.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}};tt.create=t=>new tt({checks:[],typeName:O.ZodString,coerce:t?.coerce??!1,...M(t)});a(Kw,"floatSafeRemainder");wt=class t extends P{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:x.invalid_type,expected:T.number,received:s.parsedType}),C}let r,i=new q;for(let s of this._def.checks)s.kind==="int"?L.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),E(r,{code:x.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:x.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:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?Kw(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),E(r,{code:x.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:x.not_finite,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.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"&&L.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)}};wt.create=t=>new wt({checks:[],typeName:O.ZodNumber,coerce:t?.coerce||!1,...M(t)});vt=class t extends P{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 q;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:x.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:x.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:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.bigint,received:n.parsedType}),C}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.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:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.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}};vt.create=t=>new vt({checks:[],typeName:O.ZodBigInt,coerce:t?.coerce??!1,...M(t)});kt=class extends P{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:x.invalid_type,expected:T.boolean,received:r.parsedType}),C}return Q(e.data)}};kt.create=t=>new kt({typeName:O.ZodBoolean,coerce:t?.coerce||!1,...M(t)});xt=class t extends P{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:x.invalid_type,expected:T.date,received:s.parsedType}),C}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:x.invalid_date}),C}let r=new q,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),E(i,{code:x.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:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(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:I.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:I.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}};xt.create=t=>new xt({checks:[],coerce:t?.coerce||!1,typeName:O.ZodDate,...M(t)});hn=class extends P{static{a(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==T.symbol){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.symbol,received:r.parsedType}),C}return Q(e.data)}};hn.create=t=>new hn({typeName:O.ZodSymbol,...M(t)});St=class extends P{static{a(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==T.undefined){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.undefined,received:r.parsedType}),C}return Q(e.data)}};St.create=t=>new St({typeName:O.ZodUndefined,...M(t)});Et=class extends P{static{a(this,"ZodNull")}_parse(e){if(this._getType(e)!==T.null){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.null,received:r.parsedType}),C}return Q(e.data)}};Et.create=t=>new Et({typeName:O.ZodNull,...M(t)});nt=class extends P{static{a(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}};nt.create=t=>new nt({typeName:O.ZodAny,...M(t)});He=class extends P{static{a(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}};He.create=t=>new He({typeName:O.ZodUnknown,...M(t)});_e=class extends P{static{a(this,"ZodNever")}_parse(e){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.never,received:n.parsedType}),C}};_e.create=t=>new _e({typeName:O.ZodNever,...M(t)});gn=class extends P{static{a(this,"ZodVoid")}_parse(e){if(this._getType(e)!==T.undefined){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.void,received:r.parsedType}),C}return Q(e.data)}};gn.create=t=>new gn({typeName:O.ZodVoid,...M(t)});Be=class t extends P{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:x.invalid_type,expected:T.array,received:n.parsedType}),C;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(o||c)&&(E(n,{code:o?x.too_big:x.too_small,minimum:c?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(E(n,{code:x.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(E(n,{code:x.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,c)=>i.type._parseAsync(new me(n,o,n.path,c)))).then(o=>q.mergeArray(r,o));let s=[...n.data].map((o,c)=>i.type._parseSync(new me(n,o,n.path,c)));return q.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:I.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};Be.create=(t,e)=>new Be({type:t,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...M(e)});a(mn,"deepPartialify");le=class t extends P{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=L.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:x.invalid_type,expected:T.object,received:d.parsedType}),C}let{status:r,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof _e&&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 me(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof _e){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(E(i,{code:x.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new me(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=>q.mergeObjectSync(r,d)):q.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return I.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:I.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:O.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 L.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 L.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:a(()=>n,"shape")})}deepPartial(){return mn(this)}partial(e){let n={};for(let r of L.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 L.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof fe;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:a(()=>n,"shape")})}keyof(){return vd(L.objectKeys(this.shape))}};le.create=(t,e)=>new le({shape:a(()=>t,"shape"),unknownKeys:"strip",catchall:_e.create(),typeName:O.ZodObject,...M(e)});le.strictCreate=(t,e)=>new le({shape:a(()=>t,"shape"),unknownKeys:"strict",catchall:_e.create(),typeName:O.ZodObject,...M(e)});le.lazycreate=(t,e)=>new le({shape:t,unknownKeys:"strip",catchall:_e.create(),typeName:O.ZodObject,...M(e)});Tt=class extends P{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 ce(c.ctx.common.issues));return E(n,{code:x.invalid_union,unionErrors:o}),C}if(a(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=o.map(l=>new ce(l));return E(n,{code:x.invalid_union,unionErrors:c}),C}}get options(){return this._def.options}};Tt.create=(t,e)=>new Tt({options:t,typeName:O.ZodUnion,...M(e)});Ue=a(t=>t instanceof Rt?Ue(t.schema):t instanceof he?Ue(t.innerType()):t instanceof It?[t.value]:t instanceof Nt?t.options:t instanceof Ct?L.objectValues(t.enum):t instanceof Ot?Ue(t._def.innerType):t instanceof St?[void 0]:t instanceof Et?[null]:t instanceof fe?[void 0,...Ue(t.unwrap())]:t instanceof Re?[null,...Ue(t.unwrap())]:t instanceof lr||t instanceof Mt?Ue(t.unwrap()):t instanceof Dt?Ue(t._def.innerType):[],"getDiscriminator"),di=class t extends P{static{a(this,"ZodDiscriminatedUnion")}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==T.object)return E(n,{code:x.invalid_type,expected:T.object,received:n.parsedType}),C;let r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(E(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let s of n){let o=Ue(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:O.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...M(r)})}};a(go,"mergeValues");At=class extends P{static{a(this,"ZodIntersection")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=a((s,o)=>{if(ci(s)||ci(o))return C;let c=go(s.value,o.value);return c.valid?((li(s)||li(o))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:x.invalid_intersection_types}),C)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};At.create=(t,e,n)=>new At({left:t,right:e,typeName:O.ZodIntersection,...M(n)});Ae=class t extends P{static{a(this,"ZodTuple")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==T.array)return E(r,{code:x.invalid_type,expected:T.array,received:r.parsedType}),C;if(r.data.length<this._def.items.length)return E(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((o,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new me(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>q.mergeArray(n,o)):q.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ae.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ae({items:t,typeName:O.ZodTuple,rest:null,...M(e)})};ui=class t extends P{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:x.invalid_type,expected:T.object,received:r.parsedType}),C;let i=[],s=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new me(r,c,r.path,c)),value:o._parse(new me(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?q.mergeObjectAsync(n,i):q.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof P?new t({keyType:e,valueType:n,typeName:O.ZodRecord,...M(r)}):new t({keyType:tt.create(),valueType:e,typeName:O.ZodRecord,...M(n)})}},yn=class extends P{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:x.invalid_type,expected:T.map,received:r.parsedType}),C;let i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new me(r,c,r.path,[d,"key"])),value:s._parse(new me(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of o){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};yn.create=(t,e,n)=>new yn({valueType:e,keyType:t,typeName:O.ZodMap,...M(n)});_n=class t extends P{static{a(this,"ZodSet")}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==T.set)return E(r,{code:x.invalid_type,expected:T.set,received:r.parsedType}),C;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(E(r,{code:x.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(E(r,{code:x.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function o(l){let d=new Set;for(let u of l){if(u.status==="aborted")return C;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}a(o,"finalizeSet");let c=[...r.data.values()].map((l,d)=>s._parse(new me(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:I.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:I.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};_n.create=(t,e)=>new _n({valueType:t,minSize:null,maxSize:null,typeName:O.ZodSet,...M(e)});pi=class t extends P{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:x.invalid_type,expected:T.function,received:n.parsedType}),C;function r(c,l){return cr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),je].filter(d=>!!d),issueData:{code:x.invalid_arguments,argumentsError:l}})}a(r,"makeArgsIssue");function i(c,l){return cr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),je].filter(d=>!!d),issueData:{code:x.invalid_return_type,returnTypeError:l}})}a(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof rt){let c=this;return Q(async function(...l){let d=new ce([]),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 Q(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new ce([r(l,d.error)]);let u=Reflect.apply(o,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new ce([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:Ae.create(e).rest(He.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||Ae.create([]).rest(He.create()),returns:n||He.create(),typeName:O.ZodFunction,...M(r)})}},Rt=class extends P{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})}};Rt.create=(t,e)=>new Rt({getter:t,typeName:O.ZodLazy,...M(e)});It=class extends P{static{a(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return E(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:e.data}}get value(){return this._def.value}};It.create=(t,e)=>new It({value:t,typeName:O.ZodLiteral,...M(e)});a(vd,"createZodEnum");Nt=class t extends P{static{a(this,"ZodEnum")}_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return E(n,{expected:L.joinValues(r),received:n.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return E(n,{received:n.data,code:x.invalid_enum_value,options:r}),C}return Q(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})}};Nt.create=vd;Ct=class extends P{static{a(this,"ZodNativeEnum")}_parse(e){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==T.string&&r.parsedType!==T.number){let i=L.objectValues(n);return E(r,{expected:L.joinValues(i),received:r.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=L.objectValues(n);return E(r,{received:r.data,code:x.invalid_enum_value,options:i}),C}return Q(e.data)}get enum(){return this._def.values}};Ct.create=(t,e)=>new Ct({values:t,typeName:O.ZodNativeEnum,...M(e)});rt=class extends P{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:x.invalid_type,expected:T.promise,received:n.parsedType}),C;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return Q(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};rt.create=(t,e)=>new rt({type:t,typeName:O.ZodPromise,...M(e)});he=class extends P{static{a(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(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 C;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?C:l.status==="dirty"?bt(l.value):n.value==="dirty"?bt(l.value):l});{if(n.value==="aborted")return C;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?C:c.status==="dirty"?bt(c.value):n.value==="dirty"?bt(c.value):c}}if(i.type==="refinement"){let o=a(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),o(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!et(o))return C;let c=i.transform(o.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>et(o)?Promise.resolve(i.transform(o.value,s)).then(c=>({status:n.value,value:c})):C);L.assertNever(i)}};he.create=(t,e,n)=>new he({schema:t,typeName:O.ZodEffects,effect:e,...M(n)});he.createWithPreprocess=(t,e,n)=>new he({schema:e,effect:{type:"preprocess",transform:t},typeName:O.ZodEffects,...M(n)});fe=class extends P{static{a(this,"ZodOptional")}_parse(e){return this._getType(e)===T.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};fe.create=(t,e)=>new fe({innerType:t,typeName:O.ZodOptional,...M(e)});Re=class extends P{static{a(this,"ZodNullable")}_parse(e){return this._getType(e)===T.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Re.create=(t,e)=>new Re({innerType:t,typeName:O.ZodNullable,...M(e)});Ot=class extends P{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}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:O.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...M(e)});Dt=class extends P{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 fn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ce(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ce(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Dt.create=(t,e)=>new Dt({innerType:t,typeName:O.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...M(e)});bn=class extends P{static{a(this,"ZodNaN")}_parse(e){if(this._getType(e)!==T.nan){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.nan,received:r.parsedType}),C}return{status:"valid",value:e.data}}};bn.create=t=>new bn({typeName:O.ZodNaN,...M(t)});Vw=Symbol("zod_brand"),lr=class extends P{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}},dr=class t extends P{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"?C:s.status==="dirty"?(n.dirty(),bt(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(e,n){return new t({in:e,out:n,typeName:O.ZodPipeline})}},Mt=class extends P{static{a(this,"ZodReadonly")}_parse(e){let n=this._def.innerType._parse(e),r=a(i=>(et(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return fn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Mt.create=(t,e)=>new Mt({innerType:t,typeName:O.ZodReadonly,...M(e)});a(yd,"cleanParams");a(kd,"custom");qw={object:le.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"})(O||(O={}));zw=a((t,e={message:`Input not instance of ${t.name}`})=>kd(n=>n instanceof t,e),"instanceOfType"),xd=tt.create,Sd=wt.create,Yw=bn.create,Jw=vt.create,Ed=kt.create,Xw=xt.create,Zw=hn.create,Qw=St.create,ev=Et.create,tv=nt.create,nv=He.create,rv=_e.create,iv=gn.create,sv=Be.create,ov=le.create,av=le.strictCreate,cv=Tt.create,lv=di.create,dv=At.create,uv=Ae.create,pv=ui.create,fv=yn.create,mv=_n.create,hv=pi.create,gv=Rt.create,yv=It.create,_v=Nt.create,bv=Ct.create,wv=rt.create,vv=he.create,kv=fe.create,xv=Re.create,Sv=he.createWithPreprocess,Ev=dr.create,Tv=a(()=>xd().optional(),"ostring"),Av=a(()=>Sd().optional(),"onumber"),Rv=a(()=>Ed().optional(),"oboolean"),Iv={string:a(t=>tt.create({...t,coerce:!0}),"string"),number:a(t=>wt.create({...t,coerce:!0}),"number"),boolean:a(t=>kt.create({...t,coerce:!0}),"boolean"),bigint:a(t=>vt.create({...t,coerce:!0}),"bigint"),date:a(t=>xt.create({...t,coerce:!0}),"date")},Nv=C});var f={};ae(f,{BRAND:()=>Vw,DIRTY:()=>bt,EMPTY_PATH:()=>Sw,INVALID:()=>C,NEVER:()=>Nv,OK:()=>Q,ParseStatus:()=>q,Schema:()=>P,ZodAny:()=>nt,ZodArray:()=>Be,ZodBigInt:()=>vt,ZodBoolean:()=>kt,ZodBranded:()=>lr,ZodCatch:()=>Dt,ZodDate:()=>xt,ZodDefault:()=>Ot,ZodDiscriminatedUnion:()=>di,ZodEffects:()=>he,ZodEnum:()=>Nt,ZodError:()=>ce,ZodFirstPartyTypeKind:()=>O,ZodFunction:()=>pi,ZodIntersection:()=>At,ZodIssueCode:()=>x,ZodLazy:()=>Rt,ZodLiteral:()=>It,ZodMap:()=>yn,ZodNaN:()=>bn,ZodNativeEnum:()=>Ct,ZodNever:()=>_e,ZodNull:()=>Et,ZodNullable:()=>Re,ZodNumber:()=>wt,ZodObject:()=>le,ZodOptional:()=>fe,ZodParsedType:()=>T,ZodPipeline:()=>dr,ZodPromise:()=>rt,ZodReadonly:()=>Mt,ZodRecord:()=>ui,ZodSchema:()=>P,ZodSet:()=>_n,ZodString:()=>tt,ZodSymbol:()=>hn,ZodTransformer:()=>he,ZodTuple:()=>Ae,ZodType:()=>P,ZodUndefined:()=>St,ZodUnion:()=>Tt,ZodUnknown:()=>He,ZodVoid:()=>gn,addIssueToContext:()=>E,any:()=>tv,array:()=>sv,bigint:()=>Jw,boolean:()=>Ed,coerce:()=>Iv,custom:()=>kd,date:()=>Xw,datetimeRegex:()=>wd,defaultErrorMap:()=>je,discriminatedUnion:()=>lv,effect:()=>vv,enum:()=>_v,function:()=>hv,getErrorMap:()=>pn,getParsedType:()=>Te,instanceof:()=>zw,intersection:()=>dv,isAborted:()=>ci,isAsync:()=>fn,isDirty:()=>li,isValid:()=>et,late:()=>qw,lazy:()=>gv,literal:()=>yv,makeIssue:()=>cr,map:()=>fv,nan:()=>Yw,nativeEnum:()=>bv,never:()=>rv,null:()=>ev,nullable:()=>xv,number:()=>Sd,object:()=>ov,objectUtil:()=>po,oboolean:()=>Rv,onumber:()=>Av,optional:()=>kv,ostring:()=>Tv,pipeline:()=>Ev,preprocess:()=>Sv,promise:()=>wv,quotelessJson:()=>vw,record:()=>pv,set:()=>mv,setErrorMap:()=>xw,strictObject:()=>av,string:()=>xd,symbol:()=>Zw,transformer:()=>vv,tuple:()=>uv,undefined:()=>Qw,union:()=>cv,unknown:()=>nv,util:()=>L,void:()=>iv});var yo=_(()=>{ai();mo();md();ar();Td();oi()});var ee=_(()=>{yo();yo()});var _o,bo=_(()=>{"use strict";ee();_o=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 Cv,Ad=_(()=>{"use strict";ee();bo();Cv=_o.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 Rd,Id,Nd,Cd,wo,Od,Dd,Md,Ov,Pd=_(()=>{"use strict";ee();Rd=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Id=f.enum(Rd),Nd=["new_to_ai_agents","new_to_this_client","experienced"],Cd=f.enum(Nd),wo=[{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"}],Od=wo.map(t=>t.header),Dd=f.object({experience_level:f.array(Cd).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),Md=f.object({id:f.string().min(1),client:Id,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:Dd,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Ov=Md.extend({body:f.string().min(1)})});var $d,fi,Fd,mi,Dv,Mv,jd,Ud,Hd,Bd,hi,Pv,Lv,Ld,$v,Wd,Fv,Gd=_(()=>{"use strict";ee();$d=["operating_procedure","code_review","communication_style"],fi=f.enum($d),Fd=["info","recommended","required"],mi=f.enum(Fd),Dv=["optional","default_on","mandatory"],Mv=f.enum(Dv),jd=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Ud=f.enum(jd),Hd=["verify","contribute","mixed"],Bd=f.enum(Hd),hi=f.object({clients:f.array(Ud).default([]),stacks:f.array(f.string()).default([]),intents:f.array(Bd).default([])}).default({clients:[],stacks:[],intents:[]}),Pv=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Lv=64,Ld=200,$v=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")),Wd=f.object({id:f.string().min(5).max(Lv).regex(Pv,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:fi,version:f.number().int().min(1),changed_at:$v,changelog:f.string().max(500).optional(),applies_to:hi,severity:mi.default("recommended"),disableability:Mv.default("default_on"),summary:f.string().min(1).max(Ld,`summary must be \u2264 ${Ld} 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()}),Fv=Wd.extend({body:f.string().min(1)})});var it=_(()=>{"use strict";bo();Ad();Pd();Gd()});var vo,gi,ko,Kd,Vd,qd,jv,zd=_(()=>{"use strict";ee();vo=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),gi=f.number().min(0).max(1).optional(),ko=f.object({type:f.literal("media"),kind:f.enum(["image","video"]),url:f.string().url().max(2048),alt:f.string().max(500).optional(),caption:f.string().max(500).optional(),fog:f.object({top:gi,right:gi,bottom:gi,left:gi}).optional()}),Kd=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")}),Vd=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Kd.optional(),blocks:f.array(f.discriminatedUnion("type",[vo,ko])).max(50)}),qd=f.discriminatedUnion("type",[vo,ko,Vd]),jv=f.array(qd).max(100)});var Yd,Uv,Jd,Xd,Hv,Bv,Wv,Zd=_(()=>{"use strict";ee();Yd=["free","solo_pro","team","enterprise"],Uv=f.enum(Yd),Jd=["solo_pro","team","enterprise"],Xd=f.enum(Jd),Hv=f.string().refine(t=>!Number.isNaN(Date.parse(t)),"must be ISO datetime"),Bv=f.object({user_id:f.string().uuid(),tier:Xd,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:Hv.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"}),Wv=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Qd=_(()=>{"use strict"});var Gv,Kv,Vv,eu=_(()=>{"use strict";ee();Gv=f.string().refine(t=>!Number.isNaN(Date.parse(t)),"must be ISO datetime"),Kv=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:Gv.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"}),Vv=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var tu,qv,nu,ru,iu,su,zv,ou=_(()=>{"use strict";ee();tu=f.enum(["info","important","critical"]),qv=f.enum(["pass","warn","fail"]),nu=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),ru=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),iu=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")})]),su=f.object({id:f.string().min(1),title:f.string().min(1),severity:tu,weight:f.number().int().positive().max(100),applies_when:ru,check:iu,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:nu.optional()}),zv=f.object({version:f.literal(1),checks:f.array(su).min(1)})});function Jv(t){if(!Yv.test(t))return!1;let e=new Date(`${t}T00:00:00Z`);return!Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}function yi(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 Xv(t){return`${t.model_pattern}|${t.match_kind}|${t.valid_from}`}var Yv,_i,au,cu,Ie,lu,Zv,du=_(()=>{"use strict";ee();Yv=/^\d{4}-\d{2}-\d{2}$/;a(Jv,"isRealDate");_i=f.string().refine(Jv,{message:"expected a real calendar date as YYYY-MM-DD"}),au=["exact","prefix"],cu=f.enum(au),Ie=f.number().finite().min(0).refine(t=>Number.isInteger(t*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),lu=f.object({model_pattern:f.string().min(1).max(100),match_kind:cu,valid_from:_i,valid_to:_i.nullable().optional(),input:Ie,output:Ie,cache_read:Ie,cache_write_5m:Ie,cache_write_1h:Ie,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Ie.optional(),output_above_200k:Ie.optional(),cache_read_above_200k:Ie.optional(),cache_write_5m_above_200k:Ie.optional(),cache_write_1h_above_200k:Ie.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=>yi(t)===0||yi(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"||yi(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=>yi(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(yi,"aboveRateCount");a(Xv,"rowKey");Zv=f.object({changelog:f.string().min(1).max(500),as_of:_i,source_url:f.string().url().max(500),rows:f.array(lu).min(1)}).strict().superRefine((t,e)=>{let n=new Map;t.rows.forEach((i,s)=>{let o=Xv(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 wn=_(()=>{"use strict"});var ur=_(()=>{"use strict"});var mu=_(()=>{"use strict";ur();wn()});var hu=_(()=>{"use strict";wn()});var gu=_(()=>{"use strict";it();ur();wn()});var yu=_(()=>{"use strict";ur();wn()});var _u=_(()=>{"use strict";wn();mu();hu();gu();yu();ur()});var yk,_k,bu,bk,wu,xo,vu,ku,xu,Su,wk,So=_(()=>{"use strict";ee();it();yk=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,_k=64,bu=200,bk=1e3,wu=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")),xo=f.enum(["low","medium","high"]),vu=f.object({owner:f.string().min(1).max(160).optional(),risk_level:xo.optional(),reviewed_at:wu.optional()}).default({}),ku=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}),xu=f.object({lesson_query:ku,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:[]}),Su=f.object({id:f.string().min(6).max(_k).regex(yk,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:wu,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(bu,`summary must be \u2264 ${bu} chars (rendered as one line in skill_index)`),description:f.string().max(bk).optional(),applies_to:hi,membership:xu,governance:vu}),wk=Su.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var Eu,Tu,Au,Ru,Iu,Nu,vk,Cu,kk,xk,Ou=_(()=>{"use strict";ee();So();Eu=f.enum(["maind","agent-skill"]),Tu=f.enum(["ready","needs_attention","blocked"]),Au=f.enum(["info","important","critical"]),Ru=f.enum(["pass","warn","fail"]),Iu=f.enum(["structure","governance","scope","membership","package","references"]),Nu=f.object({id:f.string().min(1),title:f.string().min(1),status:Ru,severity:Au,category:Iu,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),vk=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({}),Cu=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(),kk=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:Cu,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),xk=f.object({format:Eu,subject:f.string().min(1),status:Tu,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(Nu),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var Eo=_(()=>{"use strict"});var Du,Ek,Mu,Pu,Lu,vn,Tk,$u,Fu,ju,Uu,Hu,Bu,Wu,Gu,Ak,Ku,Vu,qu,st,To,zu,Yu,Rk,Ju=_(()=>{"use strict";ee();it();Eo();Du=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Ek=f.enum(Du),Mu=["verdict","advisory"],Pu=f.enum(Mu),Lu=["block","warn","note"],vn=f.enum(Lu),Tk=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:mi,scope:fi,grade:Pu,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()}),$u=["open","warn","info"],Fu=f.enum($u),ju=["introduced","pre_existing"],Uu=f.enum(ju),Hu=["full","partial","none"],Bu=f.enum(Hu),Wu=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:Fu,baseline:Uu,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Gu=f.object({version:f.literal(1).default(1),actions:f.object({required:vn.default("block"),recommended:vn.default("warn"),info:vn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:vn})).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:vn,reason:f.string().min(1).max(200)})).max(32).optional()}),Ak=Gu.parse({}),Ku=["ran","not_applicable","unavailable","ungraded"],Vu=f.enum(Ku),qu=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),state:Vu}),st=1e3,To=f.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),zu=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:Bu}),Rk=f.object({changed_symbols:f.array(zu).max(st),risk_flags:f.array(f.string().max(64)).max(16),detector_findings:f.array(Wu).max(64),detector_runs:f.array(qu).min(1).max(32),diff_stats:Yu,commit_sha:To.optional(),base_sha:To.optional(),merge_base_sha:To.optional(),dirty:f.boolean().optional(),code_index_version:f.string().min(1).max(32).optional()})});var Xu,Zu,Qu,ep,tp,Ao,Ik,Nk,np,rp,ip,sp,op,Ck,Ok,ap,cp,lp,Dk,dp=_(()=>{"use strict";ee();Xu=14,Zu=14,Qu=14,ep=1,tp=365,Ao=f.number().int().min(ep).max(tp),Ik=["propose","direct"],Nk="propose",np=["propose","direct"],rp="propose",ip=["propose","direct"],sp="propose",op=["off","propose","direct"],Ck=["member","admin","owner"],Ok="member",ap="off",cp="en",lp=f.object({version:f.literal(1).default(1),at_risk_days:Ao.default(Xu),stagnation_days:Ao.default(Zu),agent_date_mode:f.enum(Ik).default(Nk),health_manual_ttl_days:Ao.default(Qu),agent_event_mode:f.enum(np).default(rp),agent_update_mode:f.enum(ip).default(sp),agent_pull_mode:f.enum(op).default(ap),org_wide_authoring_min_role:f.enum(Ck).default(Ok),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(cp)}),Dk=lp.parse({})});var up,Mk,pp=_(()=>{"use strict";ee();up=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Mk=up.parse({})});var fp,mp,Pk,Lk,hp=_(()=>{"use strict";ee();fp=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([])}),mp=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:fp.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()}),Pk=mp.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()}),Lk=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var gp=_(()=>{"use strict"});function bi(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=
|
|
4
|
-
`).slice(0,1e3)}var
|
|
5
|
-
`).filter(l=>
|
|
6
|
-
`;)r++;
|
|
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(Wk(e));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function Wk(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 Bk,Tp=_(()=>{"use strict";Bk=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;a(xp,"loadModuleConfig");a(Sp,"compilerFacts");a(Ep,"parseJsonc");a(Wk,"dropTrailingCommas")});import{posix as we}from"node:path";function hr(t,e){let n=we.normalize(t).replace(/^\.\//,""),r=[],i=wi.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 wi)r.push(c+l)}if(!i&&!s){for(let c of wi)r.push(n+c);for(let c of wi)r.push(`${n}/index${c}`)}for(let c of r)if(e.has(c))return c;return null}function Rp(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=Rp(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 gr(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=gr(n[i]);if(l)return l.replace("*",e.slice(o.length,e.length-c.length))}}return null}return e==="."?gr(t):null}function gr(t){if(typeof t=="string")return t;if(Array.isArray(t)){for(let e of t){let n=gr(e);if(n)return n}return null}if(t&&typeof t=="object"){let e=t;for(let n of Gk)if(n in e){let r=gr(e[n]);if(r)return r}}return null}function Kk(t,e){let n=we.normalize(e).replace(/^\.\//,""),r=[n];if(t.outDir){let i=we.normalize(t.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=we.normalize(t.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(we.join(s,n.slice(i.length+1)))}return r}var wi,Gk,No,Ap,kn,Co=_(()=>{"use strict";wi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],Gk=["import","default","node","require","types"],No={kind:"unresolved"},Ap={kind:"external"};a(hr,"resolvePathCandidates");kn=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=`${we.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=hr(we.join(we.dirname(e),n),this.files);return s?{kind:"file",path:s}:No}if(n.startsWith("node:"))return Ap;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}:No}return Ap}viaTsconfigPaths(e,n){let r=this.tsconfigs.find(s=>s.dir===""||e.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=we.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=hr(we.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return No}}return null}viaPackage(e,n){let r=[],i=Rp(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 Kk(e,s)){let c=hr(we.join(e.dir,o),this.files);if(c)return c}return null}};a(Rp,"exportTarget");a(gr,"conditionTarget");a(Kk,"toSource")});function ot(t){return`${t}#<module>`}function Ne(t,e,n){return`${t}#${e}:${n}`}var xn=_(()=>{"use strict";a(ot,"moduleKey");a(Ne,"symbolKey")});import{posix as Ip}from"node:path";function Cp(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),Vk.has(c.kind)&&o(e,c.name,c.nodeKey),c.kind==="method"&&o(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Ne(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 Op(t,e,n=new kn({packages:[],tsconfigs:[]},e.files)){let r=Jk(),i=new Oo(t,e,n);for(let s of t)s.language==="python"?Xk(s.filePath,s.refs,s.imports,e,r.push):i.resolveFile(s,r.push);return r.edges}function Yk(t,e,n){return e.startsWith(".")?hr(Ip.join(Ip.dirname(t),e),n):null}function Jk(){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 Xk(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=Yk(t,s.specifier,r.files);o&&i(s.fromModuleKey,ot(o),"imports")}}function Zk(t){let e=t.indexOf("#"),n=t.slice(e+1,t.lastIndexOf(":"));return Ne(t.slice(0,e),n.slice(0,n.lastIndexOf(".")),"class")}var Vk,Np,qk,zk,Oo,Dp=_(()=>{"use strict";xn();Co();Vk=new Set(["function","method","class","interface","enum","type_alias"]),Np=["function","class","variable","enum","interface","type_alias"],qk=8,zk=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(Cp,"buildResolutionIndex");a(Op,"resolveCrossFileEdges");a(Yk,"resolveImportTarget");a(Jk,"edgeCollector");a(Xk,"legacyFacts");a(Zk,"classKeyOfMethod");Oo=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(ot(e.filePath),ot(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(zk.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=Zk(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=Ne(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=Ne(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=Ne(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>qk)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=Np.indexOf(s.slice(s.lastIndexOf(":")+1));return o<0?Np.length:o},"rank");return{kind:"symbol",key:[...r].sort((s,o)=>i(s)-i(o))[0]}}}});function vi(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 Do(t){return t.toLowerCase().endsWith(".d.ts")}var ki=_(()=>{"use strict";a(vi,"languageForPath");a(Do,"isSkippablePath")});import{appendFileSync as Qk,existsSync as Mp,mkdirSync as ex,readFileSync as tx}from"node:fs";import{join as nx}from"node:path";function yr(t,e={}){try{if(!Mp(t)){if(!e.create)return"skipped";ex(t,{recursive:!0})}let n=nx(t,".gitignore"),r=Mp(n)?tx(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=xi.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let o=r===null?[...rx,...s]:s,c=r&&!r.endsWith(`
|
|
2
|
+
var Vd=Object.defineProperty;var a=(e,t)=>Vd(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var n in t)Vd(e,n,{get:t[n],enumerable:!0})};function zd(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let o=n.params;if(typeof o=="object"&&o!==null){let c=o.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function wn(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 Ao(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ro(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Io(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var No=_(()=>{"use strict";a(zd,"parseFrame");a(wn,"denyResult");a(Ao,"toolEvent");a(Ro,"policyEvent");a(Io,"shaEvent")});import{execFileSync as Xd}from"node:child_process";function Zd(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=Rv}function Iv(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 Ev){let o=r[s];typeof o=="string"&&Yd.test(o)&&i.push({field:s,sha:o})}for(let[s,o]of Tv){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[o];typeof l=="string"&&Yd.test(l)&&i.push({field:`${s}.${o}`,sha:l})}return i}function Nv(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,Jd);for(let i=Jd;i>=Av;i--){let s=r.slice(0,i),o=t(s);if(o!==null&&o.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:o,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function vn(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 Qd(){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 bi(e=process.cwd()){try{let n=Xd("git",["rev-parse","--show-toplevel"],{cwd:e,env:Qd(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function Cv(e){return t=>{try{let r=Xd("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Qd(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function wi(e,t){if(t===null)return[];let n=Iv(e);if(n.length===0)return[];let r=Cv(t),i=[];for(let{field:s,sha:o}of n){let c=Nv(o,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var Ev,Tv,Yd,Av,Jd,Rv,Co=_(()=>{"use strict";Ev=["commit_sha","base_sha","head_sha"],Tv=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Yd=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,Av=7,Jd=12,Rv=10;a(Zd,"isDenyGrade");a(Iv,"extractShaArgs");a(Nv,"classifySha");a(vn,"shaFindingText");a(Qd,"cleanGitEnv");a(bi,"resolveRepoRootForSha");a(Cv,"gitShaResolver");a(wi,"inspectLineForShas")});var tu=_(()=>{"use strict"});var L,Do,T,Ae,gr=_(()=>{(function(e){e.assertEqual=i=>{};function t(i){}a(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}a(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),o={};for(let c of s)o[c]=i[c];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}a(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Do||(Do={}));T=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ae=a(e=>{switch(typeof e){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(e)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(e)?T.array:e===null?T.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?T.promise:typeof Map<"u"&&e instanceof Map?T.map:typeof Set<"u"&&e instanceof Set?T.set:typeof Date<"u"&&e instanceof Date?T.date:T.object;default:return T.unknown}},"getParsedType")});var x,Ov,de,vi=_(()=>{gr();x=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ov=a(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),de=class e extends Error{static{a(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},i=a(s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let c=r,l=0;for(;l<o.path.length;){let d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};de.create=e=>new de(e)});var Dv,Ue,Po=_(()=>{vi();gr();Dv=a((e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===T.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,L.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case x.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},"errorMap"),Ue=Dv});function Pv(e){nu=e}function kn(){return nu}var nu,ki=_(()=>{Po();nu=Ue;a(Pv,"setErrorMap");a(kn,"getErrorMap")});function E(e,t){let n=kn(),r=yr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ue?void 0:Ue].filter(i=>!!i)});e.common.issues.push(r)}var yr,Mv,J,C,Tt,ne,xi,Si,ct,xn,Mo=_(()=>{ki();Po();yr=a(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(o,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),Mv=[];a(E,"addIssueToContext");J=class e{static{a(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return C;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let s=await i.key,o=await i.value;r.push({key:s,value:o})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return C;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:t.value,value:r}}},C=Object.freeze({status:"aborted"}),Tt=a(e=>({status:"dirty",value:e}),"DIRTY"),ne=a(e=>({status:"valid",value:e}),"OK"),xi=a(e=>e.status==="aborted","isAborted"),Si=a(e=>e.status==="dirty","isDirty"),ct=a(e=>e.status==="valid","isValid"),xn=a(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var ru=_(()=>{});var I,iu=_(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}))});function P(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:a((o,c)=>{let{message:l}=e;return o.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function cu(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 Zv(e){return new RegExp(`^${cu(e)}$`)}function lu(e){let t=`${au}T${cu(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 Qv(e,t){return!!((t==="v4"||!t)&&Kv.test(e)||(t==="v6"||!t)&&qv.test(e))}function ek(e,t){if(!Hv.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 tk(e,t){return!!((t==="v4"||!t)&&Vv.test(e)||(t==="v6"||!t)&&zv.test(e))}function nk(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function Sn(e){if(e instanceof ue){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=he.create(Sn(r))}return new ue({...e._def,shape:a(()=>t,"shape")})}else return e instanceof Be?new Be({...e._def,type:Sn(e.element)}):e instanceof he?he.create(Sn(e.unwrap())):e instanceof Ie?Ie.create(Sn(e.unwrap())):e instanceof Re?Re.create(e.items.map(t=>Sn(t))):e}function $o(e,t){let n=Ae(e),r=Ae(t);if(e===t)return{valid:!0,data:e};if(n===T.object&&r===T.object){let i=L.objectKeys(t),s=L.objectKeys(e).filter(c=>i.indexOf(c)!==-1),o={...e,...t};for(let c of s){let l=$o(e[c],t[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(n===T.array&&r===T.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],c=t[s],l=$o(o,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===T.date&&r===T.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function du(e,t){return new $t({values:e,typeName:O.ZodEnum,...P(t)})}function ou(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function uu(e,t={},n){return e?dt.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(o=>{if(!o){let c=ou(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let o=ou(t,r),c=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:c})}}):dt.create()}var ge,su,M,Lv,$v,Fv,jv,Uv,Hv,Gv,Bv,Wv,Lo,Kv,Vv,qv,zv,Yv,Jv,au,Xv,lt,At,Rt,It,Nt,En,Ct,Ot,dt,Ge,we,Tn,Be,ue,Dt,He,Ei,Pt,Re,Ti,An,Rn,Ai,Mt,Lt,$t,Ft,ut,ye,he,Ie,jt,Ut,In,rk,_r,br,Ht,ik,O,sk,pu,fu,ok,ak,mu,ck,lk,dk,uk,pk,fk,mk,hk,gk,yk,_k,bk,wk,vk,kk,xk,Sk,Ek,Tk,Ak,Rk,Ik,Nk,Ck,Ok,Dk,Pk,Mk,Lk,$k,Fk,jk,Uk,Hk,hu=_(()=>{vi();ki();iu();Mo();gr();ge=class{static{a(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},su=a((e,t)=>{if(ct(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new de(e.common.issues);return this._error=n,this._error}}},"handleResult");a(P,"processCreateParams");M=class{static{a(this,"ZodType")}get description(){return this._def.description}_getType(t){return Ae(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ae(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new J,ctx:{common:t.parent.common,data:t.data,parsedType:Ae(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(xn(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:Ae(t)},i=this._parseSync({data:t,path:r.path,parent:r});return su(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ae(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ct(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>ct(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ae(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(xn(i)?i:Promise.resolve(i));return su(r,s)}refine(t,n){let r=a(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let o=t(i),c=a(()=>s.addIssue({code:x.custom,...r(i)}),"setError");return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new ye({schema:this,typeName:O.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a(n=>this["~validate"](n),"validate")}}optional(){return he.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Be.create(this)}promise(){return ut.create(this,this._def)}or(t){return Dt.create([this,t],this._def)}and(t){return Pt.create(this,t,this._def)}transform(t){return new ye({...P(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new jt({...P(this._def),innerType:this,defaultValue:n,typeName:O.ZodDefault})}brand(){return new _r({typeName:O.ZodBranded,type:this,...P(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ut({...P(this._def),innerType:this,catchValue:n,typeName:O.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return br.create(this,t)}readonly(){return Ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Lv=/^c[^\s-]{8,}$/i,$v=/^[0-9a-z]+$/,Fv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jv=/^[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,Uv=/^[a-z0-9_-]{21}$/i,Hv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Gv=/^[-+]?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)?)??$/,Bv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Kv=/^(?:(?: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])$/,Vv=/^(?:(?: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])$/,qv=/^(([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]))$/,zv=/^(([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])$/,Yv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Jv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,au="((\\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])))",Xv=new RegExp(`^${au}$`);a(cu,"timeRegexSource");a(Zv,"timeRegex");a(lu,"datetimeRegex");a(Qv,"isValidIP");a(ek,"isValidJWT");a(tk,"isValidCidr");lt=class e extends M{static{a(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==T.string){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:T.string,received:s.parsedType}),C}let r=new J,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let o=t.data.length>s.value,c=t.data.length<s.value;(o||c)&&(i=this._getOrReturnCtx(t,i),o?E(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&E(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Bv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"email",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Lo||(Lo=new RegExp(Wv,"u")),Lo.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"emoji",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")jv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"uuid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Uv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"nanoid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Lv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")$v.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid2",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Fv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ulid",code:x.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),E(i,{validation:"url",code:x.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"regex",code:x.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?lu(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Xv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Zv(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:x.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Gv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"duration",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Qv(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ip",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?ek(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"jwt",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?tk(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cidr",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Yv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64",code:x.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Jv.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64url",code:x.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:x.invalid_string,...I.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...I.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...I.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...I.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...I.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...I.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...I.errToObj(n)})}nonempty(t){return this.min(1,I.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};lt.create=e=>new lt({checks:[],typeName:O.ZodString,coerce:e?.coerce??!1,...P(e)});a(nk,"floatSafeRemainder");At=class e extends M{static{a(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==T.number){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:T.number,received:s.parsedType}),C}let r,i=new J;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:x.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?nk(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:x.not_finite,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};At.create=e=>new At({checks:[],typeName:O.ZodNumber,coerce:e?.coerce||!1,...P(e)});Rt=class e extends M{static{a(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==T.bigint)return this._getInvalidInput(t);let r,i=new J;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),E(r,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:T.bigint,received:n.parsedType}),C}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Rt.create=e=>new Rt({checks:[],typeName:O.ZodBigInt,coerce:e?.coerce??!1,...P(e)});It=class extends M{static{a(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==T.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.boolean,received:r.parsedType}),C}return ne(t.data)}};It.create=e=>new It({typeName:O.ZodBoolean,coerce:e?.coerce||!1,...P(e)});Nt=class e extends M{static{a(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==T.date){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:T.date,received:s.parsedType}),C}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_date}),C}let r=new J,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:I.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:I.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Nt.create=e=>new Nt({checks:[],coerce:e?.coerce||!1,typeName:O.ZodDate,...P(e)});En=class extends M{static{a(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==T.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.symbol,received:r.parsedType}),C}return ne(t.data)}};En.create=e=>new En({typeName:O.ZodSymbol,...P(e)});Ct=class extends M{static{a(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.undefined,received:r.parsedType}),C}return ne(t.data)}};Ct.create=e=>new Ct({typeName:O.ZodUndefined,...P(e)});Ot=class extends M{static{a(this,"ZodNull")}_parse(t){if(this._getType(t)!==T.null){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.null,received:r.parsedType}),C}return ne(t.data)}};Ot.create=e=>new Ot({typeName:O.ZodNull,...P(e)});dt=class extends M{static{a(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ne(t.data)}};dt.create=e=>new dt({typeName:O.ZodAny,...P(e)});Ge=class extends M{static{a(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ne(t.data)}};Ge.create=e=>new Ge({typeName:O.ZodUnknown,...P(e)});we=class extends M{static{a(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:T.never,received:n.parsedType}),C}};we.create=e=>new we({typeName:O.ZodNever,...P(e)});Tn=class extends M{static{a(this,"ZodVoid")}_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.void,received:r.parsedType}),C}return ne(t.data)}};Tn.create=e=>new Tn({typeName:O.ZodVoid,...P(e)});Be=class e extends M{static{a(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==T.array)return E(n,{code:x.invalid_type,expected:T.array,received:n.parsedType}),C;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(o||c)&&(E(n,{code:o?x.too_big:x.too_small,minimum:c?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(E(n,{code:x.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(E(n,{code:x.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,c)=>i.type._parseAsync(new ge(n,o,n.path,c)))).then(o=>J.mergeArray(r,o));let s=[...n.data].map((o,c)=>i.type._parseSync(new ge(n,o,n.path,c)));return J.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(t){return this.min(1,t)}};Be.create=(e,t)=>new Be({type:e,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...P(t)});a(Sn,"deepPartialify");ue=class e extends M{static{a(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==T.object){let d=this._getOrReturnCtx(t);return E(d,{code:x.invalid_type,expected:T.object,received:d.parsedType}),C}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof we&&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 ge(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof we){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(E(i,{code:x.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ge(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=>J.mergeObjectSync(r,d)):J.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:a((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:a(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:a(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:O.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:a(()=>n,"shape")})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:a(()=>n,"shape")})}deepPartial(){return Sn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:a(()=>n,"shape")})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof he;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:a(()=>n,"shape")})}keyof(){return du(L.objectKeys(this.shape))}};ue.create=(e,t)=>new ue({shape:a(()=>e,"shape"),unknownKeys:"strip",catchall:we.create(),typeName:O.ZodObject,...P(t)});ue.strictCreate=(e,t)=>new ue({shape:a(()=>e,"shape"),unknownKeys:"strict",catchall:we.create(),typeName:O.ZodObject,...P(t)});ue.lazycreate=(e,t)=>new ue({shape:e,unknownKeys:"strip",catchall:we.create(),typeName:O.ZodObject,...P(t)});Dt=class extends M{static{a(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let o=s.map(c=>new de(c.ctx.common.issues));return E(n,{code:x.invalid_union,unionErrors:o}),C}if(a(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=o.map(l=>new de(l));return E(n,{code:x.invalid_union,unionErrors:c}),C}}get options(){return this._def.options}};Dt.create=(e,t)=>new Dt({options:e,typeName:O.ZodUnion,...P(t)});He=a(e=>e instanceof Mt?He(e.schema):e instanceof ye?He(e.innerType()):e instanceof Lt?[e.value]:e instanceof $t?e.options:e instanceof Ft?L.objectValues(e.enum):e instanceof jt?He(e._def.innerType):e instanceof Ct?[void 0]:e instanceof Ot?[null]:e instanceof he?[void 0,...He(e.unwrap())]:e instanceof Ie?[null,...He(e.unwrap())]:e instanceof _r||e instanceof Ht?He(e.unwrap()):e instanceof Ut?He(e._def.innerType):[],"getDiscriminator"),Ei=class e extends M{static{a(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return E(n,{code:x.invalid_type,expected:T.object,received:n.parsedType}),C;let r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(E(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let s of n){let o=He(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of o){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:O.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...P(r)})}};a($o,"mergeValues");Pt=class extends M{static{a(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=a((s,o)=>{if(xi(s)||xi(o))return C;let c=$o(s.value,o.value);return c.valid?((Si(s)||Si(o))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:x.invalid_intersection_types}),C)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Pt.create=(e,t,n)=>new Pt({left:e,right:t,typeName:O.ZodIntersection,...P(n)});Re=class e extends M{static{a(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.array)return E(r,{code:x.invalid_type,expected:T.array,received:r.parsedType}),C;if(r.data.length<this._def.items.length)return E(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((o,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ge(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>J.mergeArray(n,o)):J.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Re.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Re({items:e,typeName:O.ZodTuple,rest:null,...P(t)})};Ti=class e extends M{static{a(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.object)return E(r,{code:x.invalid_type,expected:T.object,received:r.parsedType}),C;let i=[],s=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ge(r,c,r.path,c)),value:o._parse(new ge(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?J.mergeObjectAsync(n,i):J.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:O.ZodRecord,...P(r)}):new e({keyType:lt.create(),valueType:t,typeName:O.ZodRecord,...P(n)})}},An=class extends M{static{a(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.map)return E(r,{code:x.invalid_type,expected:T.map,received:r.parsedType}),C;let i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ge(r,c,r.path,[d,"key"])),value:s._parse(new ge(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of o){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};An.create=(e,t,n)=>new An({valueType:t,keyType:e,typeName:O.ZodMap,...P(n)});Rn=class e extends M{static{a(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.set)return E(r,{code:x.invalid_type,expected:T.set,received:r.parsedType}),C;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(E(r,{code:x.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(E(r,{code:x.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function o(l){let d=new Set;for(let u of l){if(u.status==="aborted")return C;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}a(o,"finalizeSet");let c=[...r.data.values()].map((l,d)=>s._parse(new ge(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Rn.create=(e,t)=>new Rn({valueType:e,minSize:null,maxSize:null,typeName:O.ZodSet,...P(t)});Ai=class e extends M{static{a(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return E(n,{code:x.invalid_type,expected:T.function,received:n.parsedType}),C;function r(c,l){return yr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,kn(),Ue].filter(d=>!!d),issueData:{code:x.invalid_arguments,argumentsError:l}})}a(r,"makeArgsIssue");function i(c,l){return yr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,kn(),Ue].filter(d=>!!d),issueData:{code:x.invalid_return_type,returnTypeError:l}})}a(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof ut){let c=this;return ne(async function(...l){let d=new de([]),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 ne(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new de([r(l,d.error)]);let u=Reflect.apply(o,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new de([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Re.create(t).rest(Ge.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||Re.create([]).rest(Ge.create()),returns:n||Ge.create(),typeName:O.ZodFunction,...P(r)})}},Mt=class extends M{static{a(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Mt.create=(e,t)=>new Mt({getter:e,typeName:O.ZodLazy,...P(t)});Lt=class extends M{static{a(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}};Lt.create=(e,t)=>new Lt({value:e,typeName:O.ZodLiteral,...P(t)});a(du,"createZodEnum");$t=class e extends M{static{a(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:L.joinValues(r),received:n.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{received:n.data,code:x.invalid_enum_value,options:r}),C}return ne(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})}};$t.create=du;Ft=class extends M{static{a(this,"ZodNativeEnum")}_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==T.string&&r.parsedType!==T.number){let i=L.objectValues(n);return E(r,{expected:L.joinValues(i),received:r.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=L.objectValues(n);return E(r,{received:r.data,code:x.invalid_enum_value,options:i}),C}return ne(t.data)}get enum(){return this._def.values}};Ft.create=(e,t)=>new Ft({values:e,typeName:O.ZodNativeEnum,...P(t)});ut=class extends M{static{a(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return E(n,{code:x.invalid_type,expected:T.promise,received:n.parsedType}),C;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return ne(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ut.create=(e,t)=>new ut({type:e,typeName:O.ZodPromise,...P(t)});ye=class extends M{static{a(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:a(o=>{E(r,o),o.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async c=>{if(n.value==="aborted")return C;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?C:l.status==="dirty"?Tt(l.value):n.value==="dirty"?Tt(l.value):l});{if(n.value==="aborted")return C;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?C:c.status==="dirty"?Tt(c.value):n.value==="dirty"?Tt(c.value):c}}if(i.type==="refinement"){let o=a(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),o(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ct(o))return C;let c=i.transform(o.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ct(o)?Promise.resolve(i.transform(o.value,s)).then(c=>({status:n.value,value:c})):C);L.assertNever(i)}};ye.create=(e,t,n)=>new ye({schema:e,typeName:O.ZodEffects,effect:t,...P(n)});ye.createWithPreprocess=(e,t,n)=>new ye({schema:t,effect:{type:"preprocess",transform:e},typeName:O.ZodEffects,...P(n)});he=class extends M{static{a(this,"ZodOptional")}_parse(t){return this._getType(t)===T.undefined?ne(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};he.create=(e,t)=>new he({innerType:e,typeName:O.ZodOptional,...P(t)});Ie=class extends M{static{a(this,"ZodNullable")}_parse(t){return this._getType(t)===T.null?ne(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ie.create=(e,t)=>new Ie({innerType:e,typeName:O.ZodNullable,...P(t)});jt=class extends M{static{a(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===T.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};jt.create=(e,t)=>new jt({innerType:e,typeName:O.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...P(t)});Ut=class extends M{static{a(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return xn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ut.create=(e,t)=>new Ut({innerType:e,typeName:O.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...P(t)});In=class extends M{static{a(this,"ZodNaN")}_parse(t){if(this._getType(t)!==T.nan){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:T.nan,received:r.parsedType}),C}return{status:"valid",value:t.data}}};In.create=e=>new In({typeName:O.ZodNaN,...P(e)});rk=Symbol("zod_brand"),_r=class extends M{static{a(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},br=class e extends M{static{a(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return a(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?C:s.status==="dirty"?(n.dirty(),Tt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?C:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:O.ZodPipeline})}},Ht=class extends M{static{a(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=a(i=>(ct(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return xn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Ht.create=(e,t)=>new Ht({innerType:e,typeName:O.ZodReadonly,...P(t)});a(ou,"cleanParams");a(uu,"custom");ik={object:ue.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(O||(O={}));sk=a((e,t={message:`Input not instance of ${e.name}`})=>uu(n=>n instanceof e,t),"instanceOfType"),pu=lt.create,fu=At.create,ok=In.create,ak=Rt.create,mu=It.create,ck=Nt.create,lk=En.create,dk=Ct.create,uk=Ot.create,pk=dt.create,fk=Ge.create,mk=we.create,hk=Tn.create,gk=Be.create,yk=ue.create,_k=ue.strictCreate,bk=Dt.create,wk=Ei.create,vk=Pt.create,kk=Re.create,xk=Ti.create,Sk=An.create,Ek=Rn.create,Tk=Ai.create,Ak=Mt.create,Rk=Lt.create,Ik=$t.create,Nk=Ft.create,Ck=ut.create,Ok=ye.create,Dk=he.create,Pk=Ie.create,Mk=ye.createWithPreprocess,Lk=br.create,$k=a(()=>pu().optional(),"ostring"),Fk=a(()=>fu().optional(),"onumber"),jk=a(()=>mu().optional(),"oboolean"),Uk={string:a(e=>lt.create({...e,coerce:!0}),"string"),number:a(e=>At.create({...e,coerce:!0}),"number"),boolean:a(e=>It.create({...e,coerce:!0}),"boolean"),bigint:a(e=>Rt.create({...e,coerce:!0}),"bigint"),date:a(e=>Nt.create({...e,coerce:!0}),"date")},Hk=C});var f={};te(f,{BRAND:()=>rk,DIRTY:()=>Tt,EMPTY_PATH:()=>Mv,INVALID:()=>C,NEVER:()=>Hk,OK:()=>ne,ParseStatus:()=>J,Schema:()=>M,ZodAny:()=>dt,ZodArray:()=>Be,ZodBigInt:()=>Rt,ZodBoolean:()=>It,ZodBranded:()=>_r,ZodCatch:()=>Ut,ZodDate:()=>Nt,ZodDefault:()=>jt,ZodDiscriminatedUnion:()=>Ei,ZodEffects:()=>ye,ZodEnum:()=>$t,ZodError:()=>de,ZodFirstPartyTypeKind:()=>O,ZodFunction:()=>Ai,ZodIntersection:()=>Pt,ZodIssueCode:()=>x,ZodLazy:()=>Mt,ZodLiteral:()=>Lt,ZodMap:()=>An,ZodNaN:()=>In,ZodNativeEnum:()=>Ft,ZodNever:()=>we,ZodNull:()=>Ot,ZodNullable:()=>Ie,ZodNumber:()=>At,ZodObject:()=>ue,ZodOptional:()=>he,ZodParsedType:()=>T,ZodPipeline:()=>br,ZodPromise:()=>ut,ZodReadonly:()=>Ht,ZodRecord:()=>Ti,ZodSchema:()=>M,ZodSet:()=>Rn,ZodString:()=>lt,ZodSymbol:()=>En,ZodTransformer:()=>ye,ZodTuple:()=>Re,ZodType:()=>M,ZodUndefined:()=>Ct,ZodUnion:()=>Dt,ZodUnknown:()=>Ge,ZodVoid:()=>Tn,addIssueToContext:()=>E,any:()=>pk,array:()=>gk,bigint:()=>ak,boolean:()=>mu,coerce:()=>Uk,custom:()=>uu,date:()=>ck,datetimeRegex:()=>lu,defaultErrorMap:()=>Ue,discriminatedUnion:()=>wk,effect:()=>Ok,enum:()=>Ik,function:()=>Tk,getErrorMap:()=>kn,getParsedType:()=>Ae,instanceof:()=>sk,intersection:()=>vk,isAborted:()=>xi,isAsync:()=>xn,isDirty:()=>Si,isValid:()=>ct,late:()=>ik,lazy:()=>Ak,literal:()=>Rk,makeIssue:()=>yr,map:()=>Sk,nan:()=>ok,nativeEnum:()=>Nk,never:()=>mk,null:()=>uk,nullable:()=>Pk,number:()=>fu,object:()=>yk,objectUtil:()=>Do,oboolean:()=>jk,onumber:()=>Fk,optional:()=>Dk,ostring:()=>$k,pipeline:()=>Lk,preprocess:()=>Mk,promise:()=>Ck,quotelessJson:()=>Ov,record:()=>xk,set:()=>Ek,setErrorMap:()=>Pv,strictObject:()=>_k,string:()=>pu,symbol:()=>lk,transformer:()=>Ok,tuple:()=>kk,undefined:()=>dk,union:()=>bk,unknown:()=>fk,util:()=>L,void:()=>hk});var Fo=_(()=>{ki();Mo();ru();gr();hu();vi()});var re=_(()=>{Fo();Fo()});var jo,Uo=_(()=>{"use strict";re();jo=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 Gk,gu=_(()=>{"use strict";re();Uo();Gk=jo.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 yu,_u,bu,wu,Ho,vu,ku,xu,Bk,Su=_(()=>{"use strict";re();yu=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],_u=f.enum(yu),bu=["new_to_ai_agents","new_to_this_client","experienced"],wu=f.enum(bu),Ho=[{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"}],vu=Ho.map(e=>e.header),ku=f.object({experience_level:f.array(wu).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),xu=f.object({id:f.string().min(1),client:_u,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:ku,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Bk=xu.extend({body:f.string().min(1)})});var Tu,Ri,Au,Ii,Wk,Kk,Ru,Iu,Nu,Cu,Ni,Vk,qk,Eu,zk,Ou,Yk,Du=_(()=>{"use strict";re();Tu=["operating_procedure","code_review","communication_style"],Ri=f.enum(Tu),Au=["info","recommended","required"],Ii=f.enum(Au),Wk=["optional","default_on","mandatory"],Kk=f.enum(Wk),Ru=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Iu=f.enum(Ru),Nu=["verify","contribute","mixed"],Cu=f.enum(Nu),Ni=f.object({clients:f.array(Iu).default([]),stacks:f.array(f.string()).default([]),intents:f.array(Cu).default([])}).default({clients:[],stacks:[],intents:[]}),Vk=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,qk=64,Eu=200,zk=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")),Ou=f.object({id:f.string().min(5).max(qk).regex(Vk,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:Ri,version:f.number().int().min(1),changed_at:zk,changelog:f.string().max(500).optional(),applies_to:Ni,severity:Ii.default("recommended"),disableability:Kk.default("default_on"),summary:f.string().min(1).max(Eu,`summary must be \u2264 ${Eu} 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()}),Yk=Ou.extend({body:f.string().min(1)})});var pt=_(()=>{"use strict";Uo();gu();Su();Du()});var Go,Ci,Bo,Pu,Mu,Lu,Jk,$u=_(()=>{"use strict";re();Go=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),Ci=f.number().min(0).max(1).optional(),Bo=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:Ci,right:Ci,bottom:Ci,left:Ci}).optional()}),Pu=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")}),Mu=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Pu.optional(),blocks:f.array(f.discriminatedUnion("type",[Go,Bo])).max(50)}),Lu=f.discriminatedUnion("type",[Go,Bo,Mu]),Jk=f.array(Lu).max(100)});var Fu,Xk,ju,Uu,Zk,Qk,ex,Hu=_(()=>{"use strict";re();Fu=["free","solo_pro","team","enterprise"],Xk=f.enum(Fu),ju=["solo_pro","team","enterprise"],Uu=f.enum(ju),Zk=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Qk=f.object({user_id:f.string().uuid(),tier:Uu,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:Zk.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"}),ex=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Gu=_(()=>{"use strict"});var tx,nx,rx,Bu=_(()=>{"use strict";re();tx=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),nx=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:tx.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"}),rx=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Wu,ix,Ku,Vu,qu,zu,sx,Yu=_(()=>{"use strict";re();Wu=f.enum(["info","important","critical"]),ix=f.enum(["pass","warn","fail"]),Ku=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),Vu=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),qu=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")})]),zu=f.object({id:f.string().min(1),title:f.string().min(1),severity:Wu,weight:f.number().int().positive().max(100),applies_when:Vu,check:qu,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:Ku.optional()}),sx=f.object({version:f.literal(1),checks:f.array(zu).min(1)})});function ax(e){if(!ox.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Oi(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 cx(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var ox,Di,Ju,Xu,Ne,Wo,Zu,lx,Qu=_(()=>{"use strict";re();ox=/^\d{4}-\d{2}-\d{2}$/;a(ax,"isRealDate");Di=f.string().refine(ax,{message:"expected a real calendar date as YYYY-MM-DD"}),Ju=["exact","prefix"],Xu=f.enum(Ju),Ne=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Wo=[2e5,272e3],Zu=f.object({model_pattern:f.string().min(1).max(100),match_kind:Xu,valid_from:Di,valid_to:Di.nullable().optional(),input:Ne,output:Ne,cache_read:Ne,cache_write_5m:Ne,cache_write_1h:Ne,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Ne.optional(),output_above_200k:Ne.optional(),cache_read_above_200k:Ne.optional(),cache_write_5m_above_200k:Ne.optional(),cache_write_1h_above_200k:Ne.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=>Oi(e)===0||Oi(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"||Oi(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=>Oi(e)===0||e.context_threshold_tokens==null||Wo.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Wo.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});a(Oi,"aboveRateCount");a(cx,"rowKey");lx=f.object({changelog:f.string().min(1).max(500),as_of:Di,source_url:f.string().url().max(500),rows:f.array(Zu).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let o=cx(i),c=n.get(o);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${o} (first at rows[${c}])`}):n.set(o,s)});let r=new Map;e.rows.forEach((i,s)=>{let o=`${i.model_pattern}|${i.match_kind}`,c=r.get(o)??[];c.push({i:s,r:i}),r.set(o,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,o)=>s.r.valid_from.localeCompare(o.r.valid_from));for(let s=0;s<i.length-1;s++){let o=i[s],c=i[s+1];(!o.r.valid_to||o.r.valid_to>c.r.valid_from)&&t.addIssue({code:f.ZodIssueCode.custom,path:["rows",o.i,"valid_to"],message:`window overlaps the next one for ${o.r.model_pattern} (${o.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var Nn=_(()=>{"use strict"});var wr=_(()=>{"use strict"});var rp=_(()=>{"use strict";wr();Nn()});var ip=_(()=>{"use strict";Nn()});var sp=_(()=>{"use strict";pt();wr();Nn()});var op=_(()=>{"use strict";wr();Nn()});var ap=_(()=>{"use strict";Nn();rp();ip();sp();op();wr()});var Rx,Ix,cp,Nx,lp,Ko,dp,up,pp,fp,Cx,Vo=_(()=>{"use strict";re();pt();Rx=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Ix=64,cp=200,Nx=1e3,lp=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")),Ko=f.enum(["low","medium","high"]),dp=f.object({owner:f.string().min(1).max(160).optional(),risk_level:Ko.optional(),reviewed_at:lp.optional()}).default({}),up=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}),pp=f.object({lesson_query:up,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:[]}),fp=f.object({id:f.string().min(6).max(Ix).regex(Rx,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:lp,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(cp,`summary must be \u2264 ${cp} chars (rendered as one line in skill_index)`),description:f.string().max(Nx).optional(),applies_to:Ni,membership:pp,governance:dp}),Cx=fp.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var mp,hp,gp,yp,_p,bp,Ox,wp,Dx,Px,vp=_(()=>{"use strict";re();Vo();mp=f.enum(["maind","agent-skill"]),hp=f.enum(["ready","needs_attention","blocked"]),gp=f.enum(["info","important","critical"]),yp=f.enum(["pass","warn","fail"]),_p=f.enum(["structure","governance","scope","membership","package","references"]),bp=f.object({id:f.string().min(1),title:f.string().min(1),status:yp,severity:gp,category:_p,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),Ox=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({}),wp=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(),Dx=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:wp,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),Px=f.object({format:mp,subject:f.string().min(1),status:hp,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(bp),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var qo=_(()=>{"use strict"});var kp,Lx,xp,Sp,Ep,Cn,$x,Tp,Ap,Rp,Ip,Np,Cp,Op,Dp,Fx,Pp,Mp,Lp,ft,zo,$p,Fp,jx,jp=_(()=>{"use strict";re();pt();qo();kp=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Lx=f.enum(kp),xp=["verdict","advisory"],Sp=f.enum(xp),Ep=["block","warn","note"],Cn=f.enum(Ep),$x=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:Ii,scope:Ri,grade:Sp,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()}),Tp=["open","warn","info"],Ap=f.enum(Tp),Rp=["introduced","pre_existing"],Ip=f.enum(Rp),Np=["full","partial","none"],Cp=f.enum(Np),Op=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:Ap,baseline:Ip,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Dp=f.object({version:f.literal(1).default(1),actions:f.object({required:Cn.default("block"),recommended:Cn.default("warn"),info:Cn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:Cn})).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:Cn,reason:f.string().min(1).max(200)})).max(32).optional()}),Fx=Dp.parse({}),Pp=["ran","not_applicable","unavailable","ungraded"],Mp=f.enum(Pp),Lp=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),state:Mp}),ft=1e3,zo=f.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),$p=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()}),Fp=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:Cp}),jx=f.object({changed_symbols:f.array($p).max(ft),risk_flags:f.array(f.string().max(64)).max(16),detector_findings:f.array(Op).max(64),detector_runs:f.array(Lp).min(1).max(32),diff_stats:Fp,commit_sha:zo.optional(),base_sha:zo.optional(),merge_base_sha:zo.optional(),dirty:f.boolean().optional(),code_index_version:f.string().min(1).max(32).optional()})});var Up,Hp,Gp,Bp,Wp,Yo,Ux,Hx,Kp,Vp,qp,zp,Yp,Gx,Bx,Jp,Xp,Zp,Wx,Qp=_(()=>{"use strict";re();Up=14,Hp=14,Gp=14,Bp=1,Wp=365,Yo=f.number().int().min(Bp).max(Wp),Ux=["propose","direct"],Hx="propose",Kp=["propose","direct"],Vp="propose",qp=["propose","direct"],zp="propose",Yp=["off","propose","direct"],Gx=["member","admin","owner"],Bx="member",Jp="off",Xp="en",Zp=f.object({version:f.literal(1).default(1),at_risk_days:Yo.default(Up),stagnation_days:Yo.default(Hp),agent_date_mode:f.enum(Ux).default(Hx),health_manual_ttl_days:Yo.default(Gp),agent_event_mode:f.enum(Kp).default(Vp),agent_update_mode:f.enum(qp).default(zp),agent_pull_mode:f.enum(Yp).default(Jp),org_wide_authoring_min_role:f.enum(Gx).default(Bx),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Xp)}),Wx=Zp.parse({})});var ef,Kx,tf=_(()=>{"use strict";re();ef=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Kx=ef.parse({})});var nf,rf,Vx,qx,sf=_(()=>{"use strict";re();nf=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([])}),rf=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:nf.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()}),Vx=rf.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()}),qx=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var of=_(()=>{"use strict"});function Pi(e){let t=[],n=null;return e.split(`
|
|
3
|
+
`).forEach((r,i)=>{let s=r.trim(),o=r.length-r.trimStart().length;if(n!==null){if(s===""||o>n)return;n=null}if(s===""||s.startsWith("#"))return;let c=Yx.exec(r);if(!c)return;let l=c[3]??"";if(zx.has(l.trim())){n=o;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:i+1,value:d})}),t}var zx,Yx,af=_(()=>{"use strict";zx=new Set(["|",">","|-",">-","|+",">+"]),Yx=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;a(Pi,"plainScalarViolations")});function kr(e,t){let n=a(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(p=>{let h=Number(p);return Number.isFinite(h)?h:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,i]=n(e),[s,o]=n(t);for(let c=0;c<Math.max(r.length,s.length);c+=1){let l=(r[c]??0)-(s[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&o.length===0)return 0;if(i.length===0)return 1;if(o.length===0)return-1;for(let c=0;c<Math.max(i.length,o.length);c+=1){let l=i[c],d=o[c];if(l===void 0)return-1;if(d===void 0)return 1;let u=/^\d+$/.test(l),p=/^\d+$/.test(d);if(u&&p){let h=Number(l)-Number(d);if(h!==0)return h<0?-1:1}else{if(u!==p)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var cf=_(()=>{"use strict";a(kr,"compareSemver")});var xr=_(()=>{"use strict";pt();$u();pt();pt();Hu();Gu();Bu();Yu();Qu();ap();pt();Vo();vp();jp();Qp();tf();sf();of();qo();af();cf()});function lf(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
4
|
+
`).slice(0,1e3)}var df=_(()=>{"use strict";a(lf,"nodeEmbedText")});var Jo,Xo=_(()=>{"use strict";Jo=["function","method","class","interface","enum","type_alias"]});function uf(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let o=0;o<n;o++){let c=e[o],l=t[o];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}var pf=_(()=>{"use strict";a(uf,"cosineSimilarity")});import{execFileSync as Jx}from"node:child_process";import{createHash as Xx}from"node:crypto";import{readFileSync as Zx}from"node:fs";import{posix as ve}from"node:path";function ff(e){let t=Xx("sha256"),n=[];try{n=Jx("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
5
|
+
`).filter(l=>Qx.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,i=a(l=>{if(r.has(l))return r.get(l);try{let d=Zx(ve.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),s=[],o=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=mf(l,i,0),u=ve.dirname(l)==="."?"":ve.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=hf(i(l));if(!d||typeof d.name!="string")continue;let u=ve.dirname(l)==="."?"":ve.dirname(l),p=o.get(u);c.push({name:d.name,dir:u,exports:d.exports,main:typeof d.main=="string"?d.main:void 0,module:typeof d.module=="string"?d.module:void 0,types:typeof d.types=="string"?d.types:void 0,outDir:p?.outDir,rootDir:p?.rootDir})}for(let l of[...r.keys()].sort())t.update(l).update("\0").update(r.get(l)).update("\0");return{config:{packages:c,tsconfigs:s},fingerprint:t.digest("hex")}}function mf(e,t,n){let r=hf(t(e));if(!r)return{};let i=ve.dirname(e)==="."?"":ve.dirname(e),s={},o=r.extends;if(typeof o=="string"&&o.startsWith(".")&&n<4){let d=ve.normalize(ve.join(i,o.endsWith(".json")?o:o+".json"));s=mf(d,t,n+1)}let c=r.compilerOptions??{},l={...s};return typeof c.outDir=="string"&&(l.outDir=ve.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=ve.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 hf(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"')n=!0,t+=i;else if(i==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
6
|
+
`;)r++;t+=`
|
|
7
|
+
`}else if(i==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=i}try{let r=JSON.parse(eS(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function eS(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let s=r+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e[s]==="}"||e[s]==="]")continue}t+=i}return t}var Qx,gf=_(()=>{"use strict";Qx=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;a(ff,"loadModuleConfig");a(mf,"compilerFacts");a(hf,"parseJsonc");a(eS,"dropTrailingCommas")});import{posix as ke}from"node:path";function Sr(e,t){let n=ke.normalize(e).replace(/^\.\//,""),r=[],i=Mi.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 Mi)r.push(c+l)}if(!i&&!s){for(let c of Mi)r.push(n+c);for(let c of Mi)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function _f(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let s=_f(i,t);if(s)return s}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return Er(n[t]);for(let i of r){let s=i.indexOf("*");if(s<0)continue;let o=i.slice(0,s),c=i.slice(s+1);if(t.startsWith(o)&&t.endsWith(c)){let l=Er(n[i]);if(l)return l.replace("*",t.slice(o.length,t.length-c.length))}}return null}return t==="."?Er(e):null}function Er(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Er(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of tS)if(n in t){let r=Er(t[n]);if(r)return r}}return null}function nS(e,t){let n=ke.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=ke.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=ke.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(ke.join(s,n.slice(i.length+1)))}return r}var Mi,tS,Zo,yf,On,Qo=_(()=>{"use strict";Mi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],tS=["import","default","node","require","types"],Zo={kind:"unresolved"},yf={kind:"external"};a(Sr,"resolvePathCandidates");On=class{static{a(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,i)=>i.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,i)=>i.dir.length-r.dir.length)}resolve(t,n){let r=`${ke.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let s=Sr(ke.join(ke.dirname(t),n),this.files);return s?{kind:"file",path:s}:Zo}if(n.startsWith("node:"))return yf;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(s=>n===s.name||n.startsWith(s.name+"/"));if(i){let s=n===i.name?".":"./"+n.slice(i.name.length+1),o=this.viaPackage(i,s);return o?{kind:"file",path:o}:Zo}return yf}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(s=>s.dir===""||t.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=ke.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=Sr(ke.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return Zo}}return null}viaPackage(t,n){let r=[],i=_f(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let s of[t.module,t.main,t.types])s&&r.push(s);r.push("index")}else r.push(n);for(let s of r)for(let o of nS(t,s)){let c=Sr(ke.join(t.dir,o),this.files);if(c)return c}return null}};a(_f,"exportTarget");a(Er,"conditionTarget");a(nS,"toSource")});function mt(e){return`${e}#<module>`}function Ce(e,t,n){return`${e}#${t}:${n}`}var Dn=_(()=>{"use strict";a(mt,"moduleKey");a(Ce,"symbolKey")});import{posix as bf}from"node:path";function vf(e){let t=new Map,n=new Set,r=new Map,i=new Map,s=new Set,o=a((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),s.add(c.nodeKey),rS.has(c.kind)&&o(t,c.name,c.nodeKey),c.kind==="method"&&o(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Ce(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),o(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:s}}function kf(e,t,n=new On({packages:[],tsconfigs:[]},t.files)){let r=aS(),i=new ea(e,t,n);for(let s of e)s.language==="python"?cS(s.filePath,s.refs,s.imports,t,r.push):i.resolveFile(s,r.push);return r.edges}function oS(e,t,n){return t.startsWith(".")?Sr(bf.join(bf.dirname(e),t),n):null}function aS(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let s=`${n} ${r} ${i}`;e.has(s)||(e.add(s),t.push({srcKey:n,dstKey:r,kind:i}))}}}function cS(e,t,n,r,i){for(let s of t){let o=r.nameToKeys.get(s.targetName);!o||o.length!==1||i(s.fromKey,o[0],s.kind)}for(let s of n){let o=oS(e,s.specifier,r.files);o&&i(s.fromModuleKey,mt(o),"imports")}}function lS(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return Ce(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var rS,wf,iS,sS,ea,xf=_(()=>{"use strict";Dn();Qo();rS=new Set(["function","method","class","interface","enum","type_alias"]),wf=["function","class","variable","enum","interface","type_alias"],iS=8,sS=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(vf,"buildResolutionIndex");a(kf,"resolveCrossFileEdges");a(oS,"resolveImportTarget");a(aS,"edgeCollector");a(cS,"legacyFacts");a(lS,"classKeyOfMethod");ea=class{static{a(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let s=new Map;for(let o of i.imports)o.localName&&o.importedName&&s.set(o.localName,{specifier:o.specifier,importedName:o.importedName});this.bindings.set(i.filePath,s);for(let o of i.refs){if(o.kind==="calls")continue;let c=this.heritage.get(o.fromKey);c?c.push({file:i.filePath,ref:o}):this.heritage.set(o.fromKey,[{file:i.filePath,ref:o}])}}}resolveFile(t,n){for(let r of t.refs){let i=this.resolveRef(t.filePath,r);i&&n(r.fromKey,i,r.kind)}for(let r of t.imports){let i=this.modules.resolve(t.filePath,r.specifier);i.kind==="file"&&n(mt(t.filePath),mt(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let o=this.resolveLocal(t,n.targetName,0);return o?.kind==="symbol"?o.key:null}if(r==="this")return n.kind==="calls"?this.ownMethod(n.fromKey,n.targetName):null;if(n.receiverType&&n.kind==="calls")return this.typedMethod(t,n.receiverType,n.targetName);if(r!=="?"&&r!=="this.*"&&!r.startsWith("this.")){let o=r.endsWith(".*"),c=o?r.slice(0,-2):r;if(sS.has(c)&&!this.bindings.get(t)?.has(c))return null;let l=this.bindings.get(t)?.get(c);if(l&&this.modules.resolve(t,l.specifier).kind!=="file")return null;if(!o){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),s=(this.index.methodsByName.get(n.targetName)??[]).filter(o=>{let c=lS(o);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return s.length===1?s[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),s;if(i<0)s=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);s=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(s?.kind!=="symbol")return null;let o=s.key.endsWith(":class")?[s.key]:[...this.implementers(s.key)];return o.length!==1?null:this.methodOf(o[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=Ce(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let s of this.supertypes(t)){if(!s.endsWith(":class"))continue;let o=s.indexOf("#"),c=Ce(s.slice(0,o),`${s.slice(o+1,s.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let s=this.resolveRef(r,i);if(s){n.add(s);for(let o of this.supertypes(s))n.add(o)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let s=t.slice(0,r),o=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?o.slice(0,o.lastIndexOf(".")):c==="class"?o:null;if(!l)return null;let d=Ce(s,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>iS)return null;this.memo.set(i,null);let s=this.computeExport(t,n,r);return this.memo.set(i,s),s}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let s=this.topLevel(t,n);if(s)return s;let o=this.bindings.get(t)?.get(n);if(o)return this.resolveBinding(t,o,r);let c=new Map;for(let l of i){if(l.exportedName!=="*"||!l.specifier)continue;let d=this.modules.resolve(t,l.specifier);if(d.kind!=="file")continue;let u=this.resolveExport(d.path,n,r+1);u&&c.set(u.kind==="symbol"?u.key:`ns:${u.file}`,u)}return c.size===1?[...c.values()][0]:null}topLevel(t,n){let r=this.index.topLevel.get(t)?.get(n);if(!r||r.length===0)return null;if(r.length===1)return{kind:"symbol",key:r[0]};let i=a(s=>{let o=wf.indexOf(s.slice(s.lastIndexOf(":")+1));return o<0?wf.length:o},"rank");return{kind:"symbol",key:[...r].sort((s,o)=>i(s)-i(o))[0]}}}});function Li(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function ta(e){return e.toLowerCase().endsWith(".d.ts")}var $i=_(()=>{"use strict";a(Li,"languageForPath");a(ta,"isSkippablePath")});import{appendFileSync as dS,existsSync as Sf,mkdirSync as uS,readFileSync as pS}from"node:fs";import{join as fS}from"node:path";function Tr(e,t={}){try{if(!Sf(e)){if(!t.create)return"skipped";uS(e,{recursive:!0})}let n=fS(e,".gitignore"),r=Sf(n)?pS(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?[...mS,...s]:s,c=r&&!r.endsWith(`
|
|
8
8
|
`)?`
|
|
9
|
-
`:"";return
|
|
9
|
+
`:"";return dS(n,c+o.join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`),r===null?"created":"appended"}catch{return"skipped"}}var
|
|
12
|
-
`));let n=[];return
|
|
13
|
-
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=
|
|
14
|
-
`)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let p=l.slice(3),h=p.indexOf(" -> ");h>=0&&(p=p.slice(h+4)),p=
|
|
15
|
-
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=
|
|
16
|
-
`),"norm"),l=c(s),d=c(o);if(!d.startsWith(l))return!1;let u=new Set([...
|
|
17
|
-
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var
|
|
18
|
-
`)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||o.has(u))&&o.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:o,coverage:c}}function
|
|
19
|
-
`)){if(l.startsWith("diff --git ")){c(),s=!1,o=!1;continue}if(l.startsWith("new file mode")){o=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:o?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=
|
|
20
|
-
`),v=Vp(y[0]??"");if(!v)continue;let b=y.slice(1).filter(w=>w.trim().length>0).length;m.push({sha:v.sha,dateIso:v.dateIso,authorName:v.authorName,subject:v.subject,filesTouched:b})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,Ii),truncated:m.length>Ii}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:o.length>Ho}}var _x,bx,qp,Ho,Ii,Gp,zp,Wo=_(()=>{"use strict";ne();_x="",bx="\0",qp=200,Ho=50,Ii=100,Gp="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",zp=10;a(Bo,"aggregateHistoryContext");a(wx,"clamp");a(Kp,"splitRecords");a(Vp,"parseHistoryRecord");a(vx,"aggregateOwnership");a(Yp,"readFileHistory")});import{execFileSync as kx}from"node:child_process";import{readdirSync as xx,statSync as Jp}from"node:fs";import{isAbsolute as Sx,join as Go,relative as Ex,resolve as Tx}from"node:path";function Rx(t){return!t.endsWith(".sample")&&!t.startsWith(".")}function Ix(t,e){try{let n=kx("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 Nx(t){let e;try{e=xx(t)}catch{return null}for(let n of e.filter(Rx))try{let r=Jp(Go(t,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Cx(t){try{return Jp(t).isDirectory()}catch{return!1}}function Ox(t,e){let n=Ex(t,e);return!n||n.startsWith("..")?e:n}function Ko(t){let e=Ax.filter(c=>Cx(Go(t,c))),n=Ix(t,"core.hooksPath"),r=n?Sx(n)?n:Tx(t,n):Go(t,".git","hooks"),i=Ox(t,r),s=Nx(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 Vo(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 Ax,qo=_(()=>{"use strict";Ax=[".githooks",".husky"];a(Rx,"isRealHook");a(Ix,"gitConfig");a(Nx,"hasExecutableHook");a(Cx,"isDir");a(Ox,"displayPath");a(Ko,"resolveHookState");a(Vo,"describeHookState")});import{posix as Xp}from"node:path";function Sn(t){let e=Dx.exec(t);return e?e[1]:null}function We(t,e){return t.length!==e.length?t.length-e.length:t<e?-1:t>e?1:0}function Pt(t,e){let n=A(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=Xp.basename(s),c=Sn(o);if(c===null)continue;let l=Xp.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)=>We(c.version,l.version))})).sort((s,o)=>s.dir.localeCompare(o.dir))}function br(t){let e=A(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(A(t,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var Dx,wr=_(()=>{"use strict";ne();Dx=/^(\d+)_.+\.sql$/;a(Sn,"parseMigrationVersion");a(We,"compareVersions");a(Pt,"discoverSupabaseProjects");a(br,"resolveDefaultBranch")});import{execFileSync as Mx}from"node:child_process";import{existsSync as te,readFileSync as ct,readdirSync as Ni,statSync as Yo}from"node:fs";import{posix as $}from"node:path";function Fx(t,e){let n=(()=>{let i=A(e,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=$.dirname(t);for(let i=0;i<8&&r&&r!==$.dirname(r);i++){if(te($.join(r,".git"))){let s=(()=>{let c=A(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&Xo(n,s))){let c=jx(t,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=$.dirname(r)}return null}function jx(t,e){let n=[];for(let r of Lx){let i;try{i=Ni($.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=$.join(t,o),l=$.join(e,o);try{let d=Yo(c),u=Yo(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(o);continue}if(d.size>$x)continue;ct(c).equals(ct(l))||n.push(o)}catch{continue}}}return n.sort()}function sf(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 ${Zo}.`})}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 ${$.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=Ux(t.hooks);return o&&e.push(o),Hx(e)}function Ux(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:Vo(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 Hx(t){return[...t].sort((e,n)=>Zp[e.status]-Zp[n.status]||e.id.localeCompare(n.id))}function of(t){return!t.some(e=>e.status==="open"||e.status==="warn")}function Ge(t){let e=t?.trim();return e||null}function Bx(t){let e=Ge(A(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(A(t,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Wx(t){let e=Ge(A(t,["rev-parse","--git-dir"]));if(!e)return null;let n=$.isAbsolute(e)?e:$.join(t,e);return te($.join(n,"rebase-merge"))||te($.join(n,"rebase-apply"))?"rebase":te($.join(n,"MERGE_HEAD"))?"merge":te($.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Gx(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(),
|
|
22
|
-
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function
|
|
23
|
-
`).filter(H=>H.trim().length>0).length,g=
|
|
24
|
-
`).map(U=>U.trim()).filter(U=>U.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:
|
|
25
|
-
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let o=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);o?
|
|
26
|
-
`).filter(Boolean):[]}function
|
|
27
|
-
`,
|
|
28
|
-
`:i==="r"?"\r":i==="t"?" ":i)}function
|
|
29
|
-
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||s("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(
|
|
30
|
-
Pre-existing at ${
|
|
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&&
|
|
32
|
-
`).map(
|
|
33
|
-
`;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)
|
|
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=
|
|
35
|
-
`).map(
|
|
36
|
-
`)}function
|
|
37
|
-
`).filter(Boolean)}function
|
|
38
|
-
`).filter(Boolean)),l=a(p=>c.has(p)?A(
|
|
39
|
-
`).filter(i=>i.length>0&&n.some(s=>ZS(i,s)))}function ZS(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 QS(t){let e=A(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(e?/refs\/remotes\/origin\/(.+)$/.exec(e):null)?.[1]??["main","master"].find(i=>A(t,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Oa(t,e){try{let n=VS(t,"utf8");return n.length>e?null:n}catch{return null}}var sm,qS,zS,nm,JS,Hi=_(()=>{"use strict";ne();a(Da,"isThemeClassDriftGraded");sm=["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"],qS=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,zS=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+sm.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");a(Ma,"extractTokens");a(Pa,"deriveNamespaces");a(om,"stripCommentLines");a(La,"evaluateThemeClasses");a(tm,"findingKey");a(YS,"gradeAgainstBaseline");a(am,"deriveThemeClassVerdict");nm=["*.ts","*.tsx","*.js","*.jsx"],JS=15e5;a($a,"isScannableSource");a(rm,"listTracked");a(Ut,"checkThemeClassDrift");a(XS,"baselineFindings");a(im,"listTrackedAt");a(ZS,"matchesSourcePattern");a(QS,"resolveBaseRef");a(Oa,"safeRead")});function Fa(t){return Sr[t].version}function qe(t,e,n,r){return{detector_id:t,detector_version:Fa(t),state:e,finding_count:n,...r?{reason:r}:{}}}function W(t,e,n){return{summary:qe(t,e,0,n),findings:[]}}function fm(t){return t==="open"||t==="warn"||t==="info"}function eE(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(!na(n))return W(e,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!fm(s.status))continue;let{level:o,baseline:c}=An(s.status);i.push({detector_id:e,rule_id:la,level:o,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:qe(e,"ran",i.length),findings:i}}function tE(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(!ya(n))return W(e,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!fm(i.status))continue;let{level:s,baseline:o}=An(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:e,rule_id:pa(i.dimension),level:s,baseline:o,evidence:[i.id],title:i.title})}return{summary:qe(e,"ran",r.length),findings:r}}function nE(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(!Da(n))return W(e,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=An(i.status);r.push({detector_id:e,rule_id:da,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:qe(e,"ran",r.length),findings:r}}function rE(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(!Na(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}=An(i.status);r.push({detector_id:e,rule_id:ua,level:s,baseline:o,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:qe(e,"ran",r.length),findings:r}}function iE(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:qe(e,"ran",r.length),findings:r}}function sE(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:qe(e,"ran",r.length),findings:r}}function oE(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:qe(e,"ran",r.length),findings:r}}function aE(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:qe(e,"ran",r.length),findings:r}}function ja(t,e){return t.detector_id.localeCompare(e.detector_id)||t.rule_id.localeCompare(e.rule_id)||Bi[t.level]-Bi[e.level]||lm[t.baseline]-lm[e.baseline]||(t.evidence_hash<e.evidence_hash?-1:t.evidence_hash>e.evidence_hash?1:0)}function dm(t){return t.baseline==="pre_existing"?3:t.level==="open"?0:t.level==="warn"?1:2}function cE(t){let e=new Map,n=new Map;for(let i of t)if(i.baseline==="introduced"){let s=Er(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:Fa(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,Bi[i.level]<Bi[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:Fa(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Er(i.evidence),count:i.count});return r.sort(ja)}function lE(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 ge(t){let e={det_number_collisions:eE(t.number),det_spec_drift:tE(t.spec),det_theme_class_drift:nE(t.theme),det_table_acl_lint:rE(t.acl),det_changelog_duplicates:iE(t.changelog),det_workflow_yaml:sE(t.workflow),det_release_claims:oE(t.release),det_agent_doc_prose:aE(t.agentDoc)},n=cm.map(l=>e[l].summary),r=cm.flatMap(l=>e[l].findings),i=cE(r),s=[...i].sort((l,d)=>dm(l)-dm(d)||ja(l,d)).slice(0,um).sort(ja),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:Er(l.evidence),title:l.title}));return{findings:s,coverage:lE(n,o),engines:n,local:c,truncated:o}}function Ve(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 Ha(t){return t instanceof Error?t.message:String(t)}async function lt(t){try{return{ok:!0,report:await t()}}catch(e){return{ok:!1,error:Ha(e)}}}async function Ba(t,e={}){let n={...pm,...e.engines};try{if(!mm(t))return ge(Ve("not a git work tree"));let r=await hm(t,n,e.baseRef),i=await Ua(t,n,e.baseRef,e.scope??"local",e.includeWorktrees);return ge({...r,number:i})}catch(r){return ge(Ve(`detector adapter failed: ${Ha(r)}`))}}async function Wa(t,e={}){let n={...pm,...e.engines};try{if(!mm(t)){let o=ge(Ve("not a git work tree"));return{commit:o,local:o}}let r=await hm(t,n,e.baseRef),i=await Ua(t,n,e.baseRef,"commit"),s=await Ua(t,n,e.baseRef,"local");return{commit:ge({...r,number:i}),local:ge({...r,number:s})}}catch(r){let i=ge(Ve(`detector adapter failed: ${Ha(r)}`));return{commit:i,local:i}}}function mm(t){return A(t,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function hm(t,e,n){let r=n?{baseRef:n}:{};return{spec:await lt(()=>e.spec(t,r)),theme:await lt(()=>e.theme(t,r)),acl:await lt(()=>e.acl(t,r)),changelog:await lt(()=>e.changelog(t,r)),workflow:await lt(()=>e.workflow(t,r)),release:await lt(()=>e.release(t,r)),agentDoc:await lt(()=>e.agentDoc(t,r))}}function Ua(t,e,n,r,i){let s=r==="local";return lt(()=>e.number(t,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var um,pm,cm,Bi,lm,Ga=_(()=>{"use strict";ne();fa();xr();Ar();va();Sa();Ta();Fi();Ui();Hi();um=64,pm={number:a((t,e)=>Lt(t,e),"number"),spec:a((t,e)=>Ft(t,e),"spec"),theme:a((t,e)=>Ut(t,e),"theme"),acl:a((t,e)=>jt(t,e),"acl"),changelog:a((t,e)=>_a(t,e),"changelog"),workflow:a((t,e)=>Ea(t,e),"workflow"),release:a((t,e)=>wa(t,e),"release"),agentDoc:a((t,e)=>xa(t,e),"agentDoc")},cm=["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(Fa,"versionOf");a(qe,"summary");a(W,"noFindings");a(fm,"isFindingStatus");a(eE,"adaptNumber");a(tE,"adaptSpec");a(nE,"adaptTheme");a(rE,"adaptAcl");a(iE,"adaptChangelog");a(sE,"adaptWorkflow");a(oE,"adaptRelease");a(aE,"adaptAgentDoc");Bi={open:0,warn:1,info:2},lm={introduced:0,pre_existing:1};a(ja,"compareWire");a(dm,"capPriority");a(cE,"buildWire");a(lE,"deriveCoverage");a(ge,"adaptDetectorReports");a(Ve,"unavailableDetectorReports");a(Ha,"errorText");a(lt,"attempt");a(Ba,"runRepoHealthDetectors");a(Wa,"runRepoHealthDetectorScopes");a(mm,"insideWorkTree");a(hm,"runSharedEngines");a(Ua,"runNumberEngine")});var gm,Ka=_(()=>{"use strict";gm=[{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 ym(t){let e=new Set;for(let[n,r]of t.paths)for(let i of gm){if(e.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){e.add(i.flag);continue}let s=dE(n,t);s!==null&&i.content.test(s)&&e.add(i.flag)}return[...e].sort()}function dE(t,e){let n=e.hunks.get(t);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
40
|
-
`):
|
|
11
|
+
`),r===null?"created":"appended"}catch{return"skipped"}}var Fi,na,mS,ji=_(()=>{"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"],na=["# 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).'],mS=na;a(Tr,"ensureMaindLocalIgnore")});import{execFileSync as hS}from"node:child_process";import{createHash as gS}from"node:crypto";import{readFileSync as yS,readdirSync as _S,statSync as bS}from"node:fs";import{posix as ia,sep as Ef}from"node:path";function A(e,t){try{return hS("git",[...wS,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function vS(e){return Ef==="/"?e:e.split(Ef).join("/")}function Ui(e){let t=[];for(let n of e){let r=vS(n).trim();if(!r||ta(r))continue;let i=Li(r);i&&t.push({path:r,language:i})}return t}function Af(e){return Ui(e)}function Rf(e){let t=ht(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Ui(t.split(`
|
|
12
|
+
`));let n=[];return If(e,"",n),Ui(n)}function If(e,t,n){let r;try{r=_S(ia.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Tf.has(i.name)||Tf.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?If(e,s,n):i.isFile()&&n.push(s)}}function sa(e,t){return oa(e,t)??t}function oa(e,t){let n=A(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Hi(e,t={}){if(Ar(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?sa(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=ht(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map;for(let c of s.split(`
|
|
13
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=ra((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=ht(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
|
|
14
|
+
`)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let p=l.slice(3),h=p.indexOf(" -> ");h>=0&&(p=p.slice(h+4)),p=ra(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 ra(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function aa(e,t={}){let n=Hi(e,t);return n===null?null:Ui(n.keys())}function Nf(e,t){try{let n=bS(ia.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Gi(e){return gS("sha256").update(e).digest("hex")}function Ar(e){return ht(e,["rev-parse","HEAD"])?.trim()??null}function Bi(e,t){return ht(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function ca(e){let t=ht(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
|
|
15
|
+
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=kS(e);return n.some(i=>r===null||!xS(e,i,r))}function kS(e){let t=ht(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function xS(e,t,n){let r=t[0],i=t[1];if(ra(t.slice(3))!==n)return!1;let s;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))s="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let p=ht(e,["show",`HEAD:${n}`]);if(p===null)return!1;s=p}else return!1;let o;try{o=yS(ia.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=a(p=>p.replace(/\r\n/g,`
|
|
16
|
+
`),"norm"),l=c(s),d=c(o);if(!d.startsWith(l))return!1;let u=new Set([...Fi,...na]);return d.slice(l.length).split(`
|
|
17
|
+
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var Tf,wS,ht,oe=_(()=>{"use strict";$i();ji();Tf=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),wS=["-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(A,"runGit");ht=A;a(vS,"toPosix");a(Ui,"classify");a(Af,"classifyPaths");a(Rf,"discoverSourceFiles");a(If,"walk");a(sa,"resolveDiffBase");a(oa,"resolveMergeBase");a(Hi,"enumerateChangedPaths");a(ra,"unquote");a(aa,"changedSourceFiles");a(Nf,"statFile");a(Gi,"hashContent");a(Ar,"headCommit");a(Bi,"resolveCommitSha");a(ca,"isWorktreeDirty");a(kS,"toolIgnoreRepoPath");a(xS,"isToolOnlyIgnoreChange")});function Of(e,t={}){if(A(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?sa(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=A(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map,c="full";if(Buffer.byteLength(s,"utf8")>SS?c="none":RS(s,o,()=>{c="partial"}),n){let l=A(e,["status","--porcelain","-uall"])??"";for(let d of l.split(`
|
|
18
|
+
`)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||o.has(u))&&o.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:o,coverage:c}}function RS(e,t,n){let r=null,i=0,s=!1,o=!1,c=a(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
19
|
+
`)){if(l.startsWith("diff --git ")){c(),s=!1,o=!1;continue}if(l.startsWith("new file mode")){o=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:o?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=AS.exec(l);if(d){if(i++,i>ES){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<TS&&r.addedLines.push(l.slice(1))}c()}var SS,ES,TS,Cf,AS,Df=_(()=>{"use strict";oe();SS=16*1024*1024,ES=500,TS=4e3,Cf=256*1024,AS=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;a(Of,"changedHunks");a(RS,"parseUnifiedDiff")});function da(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let o of e.history){let c=o.ownership?.commitsInWindow??o.lastCommits.length;c>=Ff&&r++,c>i&&(i=c);for(let d of o.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=o.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>s&&(s=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}function CS(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Mf(e){return e.split(IS).filter(t=>t.trim().length>0)}function Lf(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(NS);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function OS(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function jf(e,t,n={}){let r=CS(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,$f),o=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=o.slice(0,la),l=[];for(let u of c){let p=A(e,["log","-n",String(s),Pf,"--",u]),h=p===null?[]:Mf(p).map(Lf).filter(m=>m!==null);l.push({path:u,lastCommits:h.slice(0,r),ownership:i?{topAuthors:OS(h),commitsInWindow:h.length}:null})}let d=null;if(n.since){let u=Bi(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],h=A(e,["log",...p,"-n",String(Wi+1),Pf,"--name-only","--",...c]),m=[];if(h!==null)for(let g of Mf(h)){let y=g.split(`
|
|
20
|
+
`),v=Lf(y[0]??"");if(!v)continue;let w=y.slice(1).filter(b=>b.trim().length>0).length;m.push({sha:v.sha,dateIso:v.dateIso,authorName:v.authorName,subject:v.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:m.slice(0,Wi),truncated:m.length>Wi}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:o.length>la}}var IS,NS,$f,la,Wi,Pf,Ff,ua=_(()=>{"use strict";oe();IS="",NS="\0",$f=200,la=50,Wi=100,Pf="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",Ff=10;a(da,"aggregateHistoryContext");a(CS,"clamp");a(Mf,"splitRecords");a(Lf,"parseHistoryRecord");a(OS,"aggregateOwnership");a(jf,"readFileHistory")});import{execFileSync as DS}from"node:child_process";import{readdirSync as PS,statSync as Uf}from"node:fs";import{isAbsolute as MS,join as pa,relative as LS,resolve as $S}from"node:path";function jS(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function US(e,t){try{let n=DS("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 HS(e){let t;try{t=PS(e)}catch{return null}for(let n of t.filter(jS))try{let r=Uf(pa(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function GS(e){try{return Uf(e).isDirectory()}catch{return!1}}function BS(e,t){let n=LS(e,t);return!n||n.startsWith("..")?t:n}function fa(e){let t=FS.filter(c=>GS(pa(e,c))),n=US(e,"core.hooksPath"),r=n?MS(n)?n:$S(e,n):pa(e,".git","hooks"),i=BS(e,r),s=HS(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let o=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:o,hookDirs:t,hooksPath:n,effectiveDir:i}}function ma(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 FS,ha=_(()=>{"use strict";FS=[".githooks",".husky"];a(jS,"isRealHook");a(US,"gitConfig");a(HS,"hasExecutableHook");a(GS,"isDir");a(BS,"displayPath");a(fa,"resolveHookState");a(ma,"describeHookState")});import{posix as Hf}from"node:path";function Pn(e){let t=WS.exec(e);return t?t[1]:null}function We(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Gt(e,t){let n=A(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=a(s=>!t||t.length===0?!0:t.some(o=>{let c=o.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let o=Hf.basename(s),c=Pn(o);if(c===null)continue;let l=Hf.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)=>We(c.version,l.version))})).sort((s,o)=>s.dir.localeCompare(o.dir))}function Rr(e){let t=A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var WS,Ir=_(()=>{"use strict";oe();WS=/^(\d+)_.+\.sql$/;a(Pn,"parseMigrationVersion");a(We,"compareVersions");a(Gt,"discoverSupabaseProjects");a(Rr,"resolveDefaultBranch")});import{execFileSync as KS}from"node:child_process";import{existsSync as ie,readFileSync as gt,readdirSync as Ki,statSync as ya}from"node:fs";import{posix as $}from"node:path";function YS(e,t){let n=(()=>{let i=A(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=$.dirname(e);for(let i=0;i<8&&r&&r!==$.dirname(r);i++){if(ie($.join(r,".git"))){let s=(()=>{let c=A(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&ba(n,s))){let c=JS(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=$.dirname(r)}return null}function JS(e,t){let n=[];for(let r of qS){let i;try{i=Ki($.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let o=`${r}/${s}`,c=$.join(e,o),l=$.join(t,o);try{let d=ya(c),u=ya(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(o);continue}if(d.size>zS)continue;gt(c).equals(gt(l))||n.push(o)}catch{continue}}}return n.sort()}function zf(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 ${wa}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let c=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${c.map(l=>l.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:c.map(l=>`${l.install} (in ${$.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,d=l.slice(0,3).join(", "),u=l.length>3?` (+${l.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${c} ships ${d}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=a(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),d=c.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:c.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${c.map(l).join(", ")}: src/ is newer than the built ${[...new Set(c.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${d}`,hint:`Rebuild: pnpm --filter ./${c[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let o=XS(e.hooks);return o&&t.push(o),ZS(t)}function XS(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:ma(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 ZS(e){return[...e].sort((t,n)=>Gf[t.status]-Gf[n.status]||t.id.localeCompare(n.id))}function Yf(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Ke(e){let t=e?.trim();return t||null}function QS(e){let t=Ke(A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function eE(e){let t=Ke(A(e,["rev-parse","--git-dir"]));if(!t)return null;let n=$.isAbsolute(t)?t:$.join(e,t);return ie($.join(n,"rebase-merge"))||ie($.join(n,"rebase-apply"))?"rebase":ie($.join(n,"MERGE_HEAD"))?"merge":ie($.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function tE(e){let t=[],n=null,r=a(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
21
|
+
`))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function nE(e){let t=$.join(e,wa);if(!ie(t))return[];try{return gt(t,"utf8").split(`
|
|
22
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function rE(e){try{return Gt(e).map(t=>$.join($.dirname(t.dir),"config.toml"))}catch{return[]}}function iE(e){let t=A(e,["ls-files","-z","--",...VS]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=qf[$.basename(r)];if(i===void 0)continue;let s=$.dirname(r);if(!sE(e,s))continue;let o=s==="."?"node_modules":$.join(s,"node_modules");n.has(o)||n.set(o,{dir:o,install:i})}return[...n.values()]}function sE(e,t){return t==="."?!0:_a(e,t)}function _a(e,t){if(ie($.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(gt($.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Jf(e,t={}){if(Ke(A(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=Ke(A(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,o=QS(e),c=Ke(A(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let H=Ke(A(e,["rev-parse","HEAD"])),U=Ke(A(e,["rev-parse","@{u}"]));l=H!=null&&U!=null?H===U:null,d=A(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(o){let H=Ke(A(e,["rev-list","--left-right","--count",`origin/${o}...HEAD`]));if(H){let[U,N]=H.split(/\s+/).map(j=>Number.parseInt(j,10));Number.isFinite(U)&&(p=U),Number.isFinite(N)&&(u=N)}}let m=(A(e,["status","--porcelain"])??"").split(`
|
|
23
|
+
`).filter(H=>H.trim().length>0).length,g=eE(e),y=Ke(A(e,["rev-parse","--show-toplevel"]))??e,v=tE(A(e,["worktree","list","--porcelain"])??""),w=v[0]?.path??null,b=w!=null&&ba(w,y),k=Math.max(0,v.length-1),S=null;if(w&&!ba(w,y)){let H=a(N=>ie($.join(w,N))&&!ie($.join(y,N)),"here"),U=[...Vf,...rE(y),...nE(y),...t.probePaths??[]];S={mainWorktreePath:w,currentWorktreePath:y,missing:[...new Set(U.filter(H))],missingDeps:iE(y).filter(N=>H(N.dir))}}let R=YS(y,e),D=t.includeRelease===!1?null:pE(e,s),F=[];return o&&(F=(A(e,["diff","--name-only","--diff-filter=A",`origin/${o}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
24
|
+
`).map(U=>U.trim()).filter(U=>U.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:b,otherWorktrees:k,worktreeParity:S,toolCopyDrift:R,stalePackageBuilds:Xf(y),release:D,unmergedMigrations:F,hooks:fa(e)}}function ba(e,t){let n=a(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function cE(e){let t=new Set;_a(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Wf;){let i=n.pop();if(i===void 0)break;if(i.depth>=aE)continue;let s;try{s=Ki($.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let o of s){if(!o.isDirectory()||o.name.startsWith(".")||o.name==="node_modules")continue;let c=i.rel==="."?o.name:$.join(i.rel,o.name);if(r+=1,r>=Wf)break;_a(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function lE(e){let t=[];try{let n=$.join(e,"pnpm-workspace.yaml");if(ie(n)){let r=!1;for(let i of gt(n,"utf8").split(`
|
|
25
|
+
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let o=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);o?t.push(o[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=$.join(e,"package.json");if(ie(r)){let i=JSON.parse(gt(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(o=>typeof o=="string"))}}}catch{return[]}return t}function dE(e){let t=[];for(let n of cE(e)){let r=n==="."?e:$.join(e,n),i=a(s=>n==="."?s:$.join(n,s),"prefix");for(let s of lE(r)){if(t.length>=ga)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let o=s.slice(0,-2),c=$.join(r,o);if(!ie(c))continue;for(let l of Ki(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i($.join(o,l.name))),t.length>=ga)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,ga)}function Kf(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Bf;){let i=r.pop();if(i===void 0)break;let s;try{s=Ki(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let c=$.join(i,o.name);if(o.isDirectory())r.push(c);else if(o.isFile()){n+=1;try{let l=ya(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Bf)break}}}return t}function uE(e,t){let n=new Set;for(let r of t)try{let i=$.join(e,r,"package.json");if(!ie(i))continue;let s=JSON.parse(gt(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 Xf(e){let t=[],n=dE(e),r=uE(e,n);for(let i of n)try{let s=$.join(e,i,"package.json");if(!ie(s))continue;let o=JSON.parse(gt(s,"utf8"));if(typeof o.name!="string"||!r.has(o.name))continue;let c=a(w=>{if(typeof w!="string")return null;let b=w.replace(/^\.\//,"").split("/")[0];return b==="build"||b==="dist"?b:null},"builtSeg"),l=c(o.types??o.typings),d=c(o.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",h=$.join(e,i,"src"),m=$.join(e,i,u);if(!ie(h)||!ie(m))continue;let g=Kf(h),y=Kf(m);if(g===null||y===null)continue;let v=g-y;v>oE&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(v),impact:p})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function pE(e,t){if(!t)return null;let n=fE(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function fE(e,t){try{return KS("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function Nr(e,t={}){let n=await Jf(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=zf(n),i=Yf(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var Vf,wa,qf,VS,qS,zS,Gf,oE,ga,Bf,aE,Wf,va=_(()=>{"use strict";ha();oe();Ir();Vf=["supabase/config.toml","supabase/.temp",".env"],wa=".maind/worktree-requirements",qf={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},VS=Object.keys(qf).flatMap(e=>[e,"*/"+e]),qS=["scripts"],zS=512*1024;a(YS,"gatherToolCopyDrift");a(JS,"compareToolDirs");a(zf,"computeDivergence");a(XS,"computeHookFinding");Gf={open:0,warn:1,info:2,passed:3};a(ZS,"sortFindings");a(Yf,"isHealthy");a(Ke,"trimOrNull");a(QS,"resolveDefaultBranch");a(eE,"detectInProgressOp");a(tE,"parseWorktrees");a(nE,"readWorktreeRequirements");a(rE,"discoverSupabaseConfigProbes");a(iE,"discoverDependencyDirs");a(sE,"isWorkspaceRoot");a(_a,"hasWorkspaceMarkers");a(Jf,"gatherRepoHealthFacts");a(ba,"samePath");oE=2e3,ga=64,Bf=4e3,aE=3,Wf=400;a(cE,"findWorkspaceRoots");a(lE,"workspacePatternsAt");a(dE,"listWorkspacePackageDirs");a(Kf,"newestMtimeUnder");a(uE,"consumedWorkspaceNames");a(Xf,"gatherStalePackageBuilds");a(pE,"gatherReleaseFact");a(fE,"runGh");a(Nr,"checkDivergence")});import{existsSync as ka,readdirSync as Zf}from"node:fs";import{posix as Oe}from"node:path";function Sa(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(xa)}function em(e,t={}){let n=t.minFiles??Ea;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Qf)}function Ln(e){return`${e.dir}#${e.prefix}`}function Cr(e){let t=mE.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function tm(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=Ln(i),o=e.sightingsByNamespace.get(s);if(!o)continue;let c=new Set(o.keys());for(let[l,d]of o){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),h=u.filter(g=>g!==p),m=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${h.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${i.prefix}${Ta(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${s}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}function nm(e){return!e.some(t=>t.status==="open")}function Ta(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function Aa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function rm(e,t){let n=Aa(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=Cr(Oe.basename(n));if(!i)return r;let s=`${Oe.dirname(n)}#${i.prefix}`,o=e.namespaces.find(u=>Ln(u)===s)??null;if(!o)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:o,number:i.number,taken:d.length>0,sightings:d,suggestion:Ta(c.keys(),i.number)}}function Vi(e){let t=e?.trim();return t||null}function Mn(e){return e?e.split(`
|
|
26
|
+
`).filter(Boolean):[]}function hE(e){let t=Vi(A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function im(e,t={}){let n=t.minFiles??Ea,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=A(e,r);if(i===null)return[];let s=new Map;for(let o of i.split("\0").filter(Boolean)){let c=Oe.dirname(o),l=Cr(Oe.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=>em(o.numbers,{...t,minFiles:n})).map(o=>({dir:o.dir,prefix:o.prefix,fileCount:o.numbers.length,distinctRatio:new Set(o.numbers).size/o.numbers.length})).sort((o,c)=>Ln(o).localeCompare(Ln(c)))}async function Ra(e,t={}){let n=[];if(Vi(A(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=im(e,t),s=new Map(i.map(m=>[Ln(m),m])),o=[...new Set(i.map(m=>m.dir))],c=new Map,l=a((m,g,y)=>{let v=Oe.dirname(m),w=Cr(Oe.basename(m));if(!w)return;let b=`${v}#${w.prefix}`;if(!s.has(b))return;let k=c.get(b)??new Map,S=k.get(w.number)??[];S.push({kind:g,where:y,path:m}),k.set(w.number,S),c.set(b,k)},"record"),d=a((m,g,y)=>{if(o.length===0)return;let v=A(e,["ls-tree","-r","--name-only",m,"--",...o]);if(v===null){n.push(`could not read ${y}`);return}for(let w of Mn(v))l(w,g,y)},"scanTree");for(let m of o){let g=Oe.join(e,m);if(ka(g))try{for(let y of Zf(g))l(`${m}/${y}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let u=hE(e),p=t.baseRef??(u?`origin/${u}`:null);if(p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let m=Vi(A(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of Mn(A(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==m&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let m=Vi(A(e,["rev-parse","--show-toplevel"]));for(let g of Mn(A(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===m||!ka(y)))for(let v of o){let w=Oe.join(y,v);if(ka(w))try{for(let b of Zf(w))l(`${v}/${b}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${v} in ${y}`)}}}}let h=[];if(p&&o.length>0){let m=A(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...o]);m===null?n.push(xa):h=Mn(m);let g=A(e,["ls-files","--others","--exclude-standard","--",...o]);g!==null&&(h=[...h,...Mn(g)]);let y=A(e,["diff","--cached","--name-only","--diff-filter=A","--",...o]);y!==null&&(h=[...h,...Mn(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:h,skipped:n}}async function Bt(e,t={}){let n=await Ra(e,t),r=tm(n);return{ok:nm(r),findings:r,facts:n}}async function Wt(e,t,n={}){let r=Aa(t);if(!Cr(Oe.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Ra(e,{...n,dirs:n.dirs??[Oe.dirname(r)]});return rm(i,r)}var xa,mE,Ea,Qf,Or=_(()=>{"use strict";oe();xa="could not diff against the base ref \u2014 everything reported as info";a(Sa,"isNumberCollisionsGraded");mE=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Ea=3,Qf=.8;a(em,"isCounterNamespace");a(Ln,"namespaceKey");a(Cr,"parseNumbered");a(tm,"computeNumberCollisions");a(nm,"isCollisionFree");a(Ta,"suggestNextNumber");a(Aa,"normaliseRepoPath");a(rm,"checkProposedNumber");a(Vi,"trimOrNull");a(Mn,"lines");a(hE,"resolveDefaultBranch");a(im,"detectNamespaces");a(Ra,"gatherNumberCollisionFacts");a(Bt,"checkNumberCollisions");a(Wt,"checkNumberForPath")});import{execFileSync as gE}from"node:child_process";import{createHash as yE}from"node:crypto";function Ia(e){return yE("sha256").update(e).digest("hex")}function _E(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 bE(e){let t=_E(e);return t?Ia(t):null}function vE(e){return typeof e=="string"&&wE.test(e)}function sm(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(vE(t))return t;let n;try{n=gE("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?bE(n):null}var wE,Na=_(()=>{"use strict";a(Ia,"sha256Hex");a(_E,"normalizeRemoteUrl");a(bE,"projectKeyFromRemote");wE=/^[a-f0-9]{64}$/;a(vE,"isProjectKey");a(sm,"computeProjectKey")});function Pa(e){return`spec.${e}`}function $n(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}function kE(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){let o=(n[s].codePointAt(0)??0)-(r[s].codePointAt(0)??0);if(o!==0)return o}return n.length-r.length}function om(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(kE)}function Pr(e){return Ia(JSON.stringify(om(e)))}var Dr,Ca,Oa,Da,Ma=_(()=>{"use strict";Na();Dr={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"]}},Ca="number.collision",Oa="theme.dead_class",Da="acl.missing_revoke";a(Pa,"specDriftRuleId");a($n,"gradeEngineStatus");a(kE,"codePointCompare");a(om,"normalizeEvidenceForHash");a(Pr,"hashDetectorEvidence")});import{existsSync as xE,readFileSync as am}from"node:fs";import{posix as SE}from"node:path";function Yi(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function Ji(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
|
|
27
|
+
`,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function Mr(e){return e==='"'||e==="'"||e==="`"}function Xi(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function qi(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(Mr(s)){i=Yi(e,i);continue}if(Xi(e,i)){i=Ji(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function EE(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Xi(e,t)){t=Ji(e,t);continue}break}return e.slice(t)}function Fn(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(Mr(s)){i=Yi(e,i);continue}if(Xi(e,i)){i=Ji(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>EE(s).trim()).filter(s=>s.length>0)}function um(e){let t=Yi(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
28
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function TE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $a(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${TE(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let o=e[i];if(Mr(o)){i=Yi(e,i);continue}if(Xi(e,i)){i=Ji(e,i);continue}if(!s){if(o==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(o===";")return null;i++;continue}if(o==="[")return qi(e,i);if(o===";")return null;i++}return null}function Fa(e){let t={};if(!e.startsWith("{"))return t;for(let n of Fn(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();Mr(s[0]??"")&&(t[i]=um(s))}return t}function AE(e,t){if(!e.startsWith("{"))return null;for(let n of Fn(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function pm(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function fm(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function mm(e,t){let n=$a(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=fm(),i=[],s=0;for(let o of Fn(n.slice(1,-1))){if(!o.startsWith("{")){s++;continue}let c=Fa(o),l=c[t.key_field];if(!l){s++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:pm(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function hm(e,t){let n=$a(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=fm(),i=[],s=0,o=a((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let h of Fn(c.slice(1,-1))){let m={...d},g=null;if(u.shape==="object"){if(!h.startsWith("{")){s++;continue}let y=Fa(h);for(let[v,w]of Object.entries(u.fields??{}))m[v]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let v=AE(h,u.children);g=v&&v.startsWith("[")?qi(v,0):null}}else{if(!h.startsWith("[")){s++;continue}let y=Fn(h.slice(1,-1));for(let[v,w]of Object.entries(u.fields??{})){let b=y[Number(w)];m[v]=b!==void 0&&Mr(b[0]??"")?um(b):""}if(!p&&typeof u.children=="number"){let v=y[u.children];g=v!==void 0&&v.startsWith("[")?qi(v,0):null}}if(p){let y=m[t.key_field];if(!y){s++;continue}let v=(t.partition_by??[]).map(w=>m[w]??"");i.push({key:y,fields:pm(m,t.fields),orderPath:v,ordinal:r(v)});continue}g!==null&&o(g,l+1,m)}},"walk");return o(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function cm(e,t){return t.extractor==="object-array"?mm(e,t):hm(e,t)}function gm(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function ym(e,t,n){return`spec.drift:${e}#${t}:${n}`}function RE(e){return e.orderPath.join(" / ")||"(flat)"}function _m(e,t,n,r){let i=[],s=a((d,u,p,h,m,g)=>{i.push({id:ym(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:h,detail:m,hint:g})},"push"),o=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=o.get(d.key);if(!u){s("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${RE(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let h=d.fields[p]??"",m=u.fields[p]??"";h!==m&&s("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${m||"\u2014"}", the specification says "${h||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>o.has(y.key)).map(y=>y.key),h=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),m=new Set(h),g=p.filter(y=>m.has(y));if(h.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";s("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${h.join(" \u2192 ")}
|
|
29
|
+
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||s("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...o.keys(),...c.keys()])){if(gm(d,e.grounding,r))continue;let u=o.has(d);s("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function IE(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let o=s.indexOf(i.prefix);if(o===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(o+i.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[i.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${d}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function lm(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}function bm(e,t={}){let n=a(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=a(u=>{let p=[],h=[];for(let m of r){let g=u.get(m.spec.path),y=u.get(m.impl.path);if(g==null||y==null){let k=g==null?m.spec.path:m.impl.path;p.push(lm(m.id,`Declared file could not be read: ${k}`)),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let v=cm(g,m.spec),w=cm(y,m.impl);if(v.error||w.error){p.push(lm(m.id,v.error??w.error??"unknown")),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=v.dropped>0||w.dropped>0;h.push({id:m.id,measured:!0,specRecords:v.records.length,implRecords:w.records.length,partial:b}),b&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${v.dropped} specification and ${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(..._m(m,v.records,w.records,e.files)),p.push(...IE(m,{spec:v.records.length,impl:w.records.length},u))}return{findings:p,contracts:h}},"runOnce"),s=i(e.sources),o=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of i(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||o.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(ym(u.id,p.dimension,p.key),p);let l=s.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:o.has(u.id)?{...u,status:"info",detail:`${u.detail}
|
|
30
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>dm[u.status]-dm[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 La(e){let t=e?.trim();return t||null}function Zi(e){let t;try{t=JSON.parse(e)}catch(o){return{manifest:null,error:`manifest is not valid JSON: ${o.message}`}}let n=a(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null,"obj"),r=a(o=>typeof o=="string"?o:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=a(o=>({manifest:null,error:o}),"bad");for(let[o,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${o+1}`;if(!l)return s(`${u}: not an object`);if(!d)return s(`${u}: \`id\` is missing`);if(!r(l.reason))return s(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let h=n(l[p]);if(!h)return s(`${u}: \`${p}\` is missing`);let m=r(h.extractor);if(!m)return s(`${u}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return s(`${u}: unknown \`${p}.extractor\` "${m}"`);if(!r(h.path)||!r(h.symbol)||!r(h.key_field))return s(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(h.levels))return s(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let h=n(p);if(!h||!r(h.reason))return s(`${u}: exception for "${r(h?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function NE(e){let t=La(A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(A(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function CE(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}async function wm(e,t={}){let n=a((g,y)=>SE.join(g,y),"join"),r=t.manifestPath??zi,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(La(A(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let o=n(e,r);if(!xE(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}=Zi(am(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 CE(c))try{d.set(g,am(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=A(e,["ls-files","-z"]);if(p===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let h=null,m=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:NE(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(h=La(A(e,["merge-base",y,"HEAD"])),!h)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let v of d.keys())m.set(v,A(e,["show",`${h}:${v}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:m,baseRef:h,files:u,skipped:i}}async function Kt(e,t={}){let n=await wm(e,t);return{...bm(n,t),facts:n}}function ja(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var zi,dm,Lr=_(()=>{"use strict";oe();zi=".maind/spec-contracts.json";a(Yi,"endOfString");a(Ji,"skipComment");a(Mr,"isQuote");a(Xi,"isCommentStart");a(qi,"sliceBalanced");a(EE,"stripLeadingTrivia");a(Fn,"splitTopLevel");a(um,"readStringLiteral");a(TE,"escapeRe");a($a,"findSymbolArray");a(Fa,"parseObjectFields");a(AE,"objectFieldRaw");a(pm,"pickFields");a(fm,"makeOrdinals");a(mm,"extractObjectArray");a(hm,"extractNestedList");a(cm,"extractRecords");a(gm,"isGrounded");a(ym,"findingId");a(RE,"partitionOf");a(_m,"compareContract");a(IE,"checkAssertions");a(lm,"unreadable");dm={open:0,warn:1,info:2,passed:3};a(bm,"computeSpecDrift");a(La,"trimOrNull");a(Zi,"parseManifest");a(NE,"resolveDefaultBranch");a(CE,"declaredPaths");a(wm,"gatherSpecDriftFacts");a(Kt,"checkSpecDrift");a(ja,"isSpecDriftGraded")});import{execFileSync as OE}from"node:child_process";import{existsSync as DE,readFileSync as PE}from"node:fs";import{join as ME}from"node:path";function $r(e){let t=[],n=e.split(`
|
|
31
|
+
`);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let s=/(\d+\.\d+\.\d+)/.exec(i);s&&t.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":LE.test(i)?"never-published":"released"})}return t}function km(e){let t=new Map;for(let n of $r(e)){let r=t.get(n.version);r?r.push(n):t.set(n.version,[n])}return[...t.entries()].filter(([,n])=>n.length>1).map(([n,r])=>({version:n,count:r.length,lines:r.map(i=>i.line),shapes:r.map(i=>i.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function xm(e,t){let n=km(e);if(t===null)return{introduced:[],preExisting:n.map(o=>({...o,countBefore:o.count})),baseResolved:!1};let r=new Map;for(let o of $r(t))r.set(o.version,(r.get(o.version)??0)+1);let i=[],s=[];for(let o of n){let c=r.get(o.version)??0;(o.count>c?i:s).push({...o,countBefore:c})}return{introduced:i,preExisting:s,baseResolved:!0}}function Sm(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let i=xm(r.head,e.baseRef===null?null:r.base);for(let s of i.introduced)t.push({path:r.path,version:s.version,level:"open",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} has ${s.count} headings (was ${s.countBefore})`});for(let s of i.preExisting)t.push({path:r.path,version:s.version,level:"info",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} already had ${s.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function vm(e,t){try{return OE("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function $E(e,t={}){let n=vm(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null,s=r.map(o=>{let c=ME(e,o);return{path:o,head:DE(c)?PE(c,"utf8"):null,base:i===null?null:vm(["show",`${i}:${o}`],e)}});return{isRepo:!0,baseRef:i,files:s}}function Ua(e,t={}){return Sm($E(e,t))}var LE,Qi=_(()=>{"use strict";LE=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;a($r,"parseVersionHeadings");a(km,"findDuplicateHeadings");a(xm,"classifyIntroduced");a(Sm,"computeChangelogDuplicates");a(vm,"git");a($E,"gatherChangelogFacts");a(Ua,"checkChangelogDuplicates")});import{execFileSync as FE}from"node:child_process";import{existsSync as jE,readFileSync as Em}from"node:fs";import{dirname as Tm,join as Am}from"node:path";function Im(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),i=new Set(n.documentedBase??n.documented),s=[...n.documented].sort(kr);for(let o of s){if(r.has(o)||kr(o,n.version)>=0)continue;let c=!i.has(o);t.push({package:n.name,version:o,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${o} is newly documented as released but the registry never served it`:`${n.name}@${o} is documented as released but the registry never served it`})}for(let o of[...n.neverPublished??[]].sort(kr))r.has(o)&&t.push({package:n.name,version:o,level:"info",rule:"release.mislabelled",title:`${n.name}@${o} is marked never published but the registry serves it`});r.has(n.version)||t.push({package:n.name,version:n.version,level:"info",rule:"release.unpublished",title:`${n.name}@${n.version} is not published yet`})}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"mismatch",reason:null,findings:t,facts:e}}function Rm(e){let t=$r(e),n=[...new Set(t.filter(s=>s.shape!=="never-published").map(s=>s.version))],r=new Set(n),i=[...new Set(t.filter(s=>s.shape==="never-published"&&!r.has(s.version)).map(s=>s.version))];return{documented:n,neverPublished:i}}function Ha(e,t){try{return FE("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function Nm(e,t=null){let n=Ha(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let s;try{s=JSON.parse(Em(Am(e,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let o=Tm(i)==="."?"":Tm(i),c=Am(e,o,"CHANGELOG.md"),{documented:l,neverPublished:d}=jE(c)?Rm(Em(c,"utf8")):{documented:[],neverPublished:[]},u=o===""?"CHANGELOG.md":`${o}/CHANGELOG.md`,p=t===null?null:Ha(["show",`${t}:${u}`],e),h=t===null?null:p===null?[]:Rm(p).documented;r.push({dir:o,name:s.name,version:s.version,documented:l,documentedBase:h,neverPublished:d})}return r}async function UE(e){let t=`https://registry.npmjs.org/${e.replace("/","%2F")}`,n=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(n.status===404)return[];if(!n.ok)throw new Error(`HTTP ${n.status}`);let r=await n.json();return Object.keys(r.versions??{})}async function Cm(e,t={}){if(Ha(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=Nm(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??UE,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 Ga(e,t={}){return Im(await Cm(e,t))}var Ba=_(()=>{"use strict";xr();Qi();a(Im,"computeReleaseClaims");a(Rm,"claimsOf");a(Ha,"git");a(Nm,"discoverPackages");a(UE,"packument");a(Cm,"gatherReleaseClaimsFacts");a(Ga,"checkReleaseClaims")});import{execFileSync as HE}from"node:child_process";import{existsSync as GE,readFileSync as BE}from"node:fs";import{join as WE}from"node:path";function Om(e){return e.split(`
|
|
32
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function Pm(e,t){let n=new Map;for(let s of Om(t??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of Om(e)){let o=n.get(s)??0;o>0?n.set(s,o-1):r.push(s)}let i=0;for(let s of n.values())i+=s;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function Mm(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.baseRef===null)return{ok:!1,verdict:"no_opinion",reason:"no base to measure growth against",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no agent instruction file tracked",findings:[],facts:e};let t=[];for(let n of e.files){if(n.head===null)continue;let r=Pm(n.head,n.base);r.net!==0&&t.push({path:n.path,level:"open",netLines:r.net,addedLines:r.added.length,removedLines:r.removed,sample:r.added.slice(0,5),newFile:n.base===null,title:n.base===null?`${n.path}: new agent instruction file with ${r.net} line(s) \u2014 every line loads into every session`:`${n.path}: +${r.net} line(s) of agent instructions \u2014 every line loads into every session; durable knowledge belongs in docs, a convention or a code comment`})}return{ok:t.length===0,verdict:t.length===0?"clean":"grown",reason:null,findings:t,facts:e}}function Wa(e,t){try{return HE("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function Lm(e,t={}){let n=Wa(["ls-files","-z","--",...Dm],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Wa(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(o=>{let c=WE(e,o);return{path:o,head:GE(c)?BE(c,"utf8"):null,base:r===null?null:Wa(["show",`${r}:${o}`],e)}});return{isRepo:!0,baseRef:r,files:s}}function Ka(e,t={}){return Mm(Lm(e,t))}var Dm,Va=_(()=>{"use strict";Dm=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"];a(Om,"contentLines");a(Pm,"proseDelta");a(Mm,"computeAgentDocProse");a(Wa,"git");a(Lm,"gatherAgentDocProseFacts");a(Ka,"checkAgentDocProse")});import{execFileSync as KE}from"node:child_process";import{existsSync as VE,readFileSync as qE}from"node:fs";import{join as zE}from"node:path";function Fm(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no workflow files under .github/workflows",findings:[],facts:e};let t=[];for(let n of e.files){if(n.content===null)continue;let r=new Set(n.base===null?[]:Pi(n.base).map(i=>i.value));for(let i of Pi(n.content)){let s=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,o=e.baseRef!==null&&!r.has(i.value);t.push({path:n.path,level:o?"open":"info",line:i.line,value:i.value,title:`${n.path}:${i.line}: unquoted plain scalar containing ": " \u2014 ${s}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function $m(e,t){try{return KE("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function jm(e,t={}){let n=$m(["ls-files","-z","--",".github/workflows/*.yml",".github/workflows/*.yaml"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(s=>{let o=zE(e,s);return{path:s,content:VE(o)?qE(o,"utf8"):null,base:i===null?null:$m(["show",`${i}:${s}`],e)}})}}function qa(e,t={}){return Fm(jm(e,t))}var za=_(()=>{"use strict";xr();a(Fm,"computeWorkflowYaml");a($m,"git");a(jm,"gatherWorkflowYamlFacts");a(qa,"checkWorkflowYaml")});import{readFileSync as YE}from"node:fs";import{join as JE,posix as XE}from"node:path";function Um(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
|
|
33
|
+
`;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let o=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||o){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function xe(e){let t=[],n="",r=!1,i=!1,s=a(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let o=t.filter(c=>c.length>0);return o.length===0||o.length>2?null:o.length===2?{schema:o[0],name:o[1]}:{schema:"public",name:o[0]}}function Ve(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function ZE(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let o=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(o&&!Ve(o[1]).map(h=>xe(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||!Ve(c[1]).map(p=>xe(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Ve(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>xe(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Ve(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:[...Fr]};h[2]!=="("&&Fr.includes(m)&&u.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Hm(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(n)return null;let o=i.trim();if(QE.test(o))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(o);if(l){if(!Ve(l[1]).map(h=>xe(h)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=o.replace(/^TABLE\s+/i,""),h=Ve(p).map(m=>xe(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(h.length===0)return null;c=h}let d=Ve(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>xe(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Ve(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:[...Fr]};!g&&Fr.includes(m)&&u.push(m)}return{tables:c,roles:d,writePrivs:u}}function Ja(e){let t=new Map,n=[...e].sort((i,s)=>We(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=Um(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=ZE(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=xe(l[2]);if(!p||p.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(p.name))continue;t.set(p.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(d){let p=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let h of Ve(p)){let m=xe(h);m&&m.schema==="public"&&t.delete(m.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=xe(u[1]),h=xe(u[2]);if(p&&h&&p.schema==="public"){let m=t.get(p.name);m&&(t.delete(p.name),t.set(h.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=Hm(c);if(!p)continue;let h=p.tables==="all_in_public"?[...t.keys()]:p.tables,m=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!m&&!g)continue;for(let y of h){let v=t.get(y);if(v&&(m&&(v.anonAddressed=!0),g))for(let w of p.writePrivs)v.authWritesRevoked.add(w)}continue}}}return t}function Ya(e){let t=[];for(let[n,r]of Ja(e)){let i=[];r.anonAddressed||i.push("anon"),Fr.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Gm(e){let t=Ya(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Ya(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),o=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:o,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function Bm(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Za(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(es)||t.endsWith(Xa))}function t0(e,t){try{let n=YE(e,"utf8");return n.length>t?null:n}catch{return null}}function n0(e,t,n,r,i){let s=A(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(s===null)return i.push(`could not diff ${t} against ${r} ${es}`),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=XE.basename(u),h=Pn(p);if(h===null)continue;let m=A(e,["show",`${r}:${u}`]);if(m===null)return i.push(`could not read ${u} at ${r} ${Xa}`),null;l.push({name:p,version:h,content:m})}return l}function Vt(e,t={}){let n=t.maxFileBytes??e0,r=[],i=Gt(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=t.includeBaseline!==!1,o=null;if(s)if(t.baseRef)o=t.baseRef;else{let h=Rr(e);o=h?`origin/${h}`:null,o===null&&r.push(`no default branch resolvable ${es}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let h of i){let m=[];for(let v of h.files){let w=t0(JE(e,v.path),n);if(w===null){r.push(`could not read ${v.path} \u2014 excluded from the fold`);continue}m.push({ref:v,content:w})}let g=m.map(({ref:v,content:w})=>({name:v.name,version:v.version,content:w})),y=o===null?null:n0(e,h.dir,m,o,r);c.push(...Gm({dir:h.dir,files:g,baseFiles:y})),l.push({dir:h.dir,migrationCount:g.length,tableCount:Ja(g).size})}let d=l.reduce((h,m)=>h+m.migrationCount,0),u=Bm(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 Fr,QE,e0,es,Xa,ts=_(()=>{"use strict";oe();Ir();a(Um,"stripSql");a(xe,"normalizeQualifiedIdent");a(Ve,"splitTopLevel");Fr=["INSERT","UPDATE","DELETE"];a(ZE,"parseDefaultAclTables");QE=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;a(Hm,"parseTableRevoke");a(Ja,"foldTableAcl");a(Ya,"evaluateTableAcl");a(Gm,"computeTableAclFindings");a(Bm,"deriveTableAclVerdict");e0=5e6,es="\u2014 findings reported ungraded (open)",Xa="\u2014 baseline degraded";a(Za,"isTableAclGraded");a(t0,"safeRead");a(n0,"baseFilesFor");a(Vt,"checkTableAclLint")});import{readFileSync as r0}from"node:fs";import{join as Qa}from"node:path";function tc(e){return e.verdict!=="no_opinion"&&e.graded}function nc(e){let t=new Set;for(let n of e.matchAll(i0))t.add(n[1]);return t}function rc(e){return new Set([...e].map(t=>t.split("-")[0]))}function Ym(e){return e.split(`
|
|
35
|
+
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
36
|
+
`)}function ic(e){let t=rc(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=Ym(i),o=new Set;for(let c of s.matchAll(s0)){let l=c[2],d=l.split("-")[0];if(!t.has(d)||e.tokens.has(l))continue;let u=`${c[1]}-${l}`;o.has(u)||(o.add(u),n.push({file:r,klass:u,token:l,namespace:d}))}}return n}function Wm(e){return`${e.file} ${e.klass}`}function o0(e,t){let n=t===null?null:new Set(t.map(Wm));return e.map(r=>({...r,status:n!==null&&n.has(Wm(r))?"info":"open"}))}function Jm(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function sc(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Vm(e,t){let n=A(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
37
|
+
`).filter(Boolean)}function qt(e,t={}){let n=t.maxFileBytes??a0,r=new Set;for(let u of Vm(e,["*.css"])){let p=ec(Qa(e,u),n);if(p!==null)for(let h of nc(p))r.add(h)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>Km.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):Km,s=[];for(let u of Vm(e,i)){if(!sc(u))continue;let p=ec(Qa(e,u),n);p!==null&&s.push({path:u,content:p})}let o=ic({tokens:r,sources:s}),c=t.includeBaseline===!1?null:c0(e,i,n,t.baseRef),l=o0(o,c?.findings??null),d=Jm(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:rc(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function c0(e,t,n,r){let i=r??d0(e);if(i===null)return null;let s=A(e,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let o=A(e,["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)?A(e,["show",`${s}:${p}`]):ec(Qa(e,p),n),"atBase"),d=new Set;for(let p of qm(e,s,["*.css"])){let h=l(p);if(h!==null)for(let m of nc(h))d.add(m)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let p of qm(e,s,t)){if(!sc(p))continue;let h=l(p);h===null||h.length>n||u.push({path:p,content:h})}return{findings:ic({tokens:d,sources:u}),mergeBase:s}}function qm(e,t,n){let r=A(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
39
|
+
`).filter(i=>i.length>0&&n.some(s=>l0(i,s)))}function l0(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 d0(e){let t=A(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>A(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function ec(e,t){try{let n=r0(e,"utf8");return n.length>t?null:n}catch{return null}}var zm,i0,s0,Km,a0,ns=_(()=>{"use strict";oe();a(tc,"isThemeClassDriftGraded");zm=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],i0=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,s0=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+zm.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");a(nc,"extractTokens");a(rc,"deriveNamespaces");a(Ym,"stripCommentLines");a(ic,"evaluateThemeClasses");a(Wm,"findingKey");a(o0,"gradeAgainstBaseline");a(Jm,"deriveThemeClassVerdict");Km=["*.ts","*.tsx","*.js","*.jsx"],a0=15e5;a(sc,"isScannableSource");a(Vm,"listTracked");a(qt,"checkThemeClassDrift");a(c0,"baselineFindings");a(qm,"listTrackedAt");a(l0,"matchesSourcePattern");a(d0,"resolveBaseRef");a(ec,"safeRead")});function oc(e){return Dr[e].version}function ze(e,t,n,r){return{detector_id:e,detector_version:oc(e),state:t,finding_count:n,...r?{reason:r}:{}}}function B(e,t,n){return{summary:ze(e,t,0,n),findings:[]}}function nh(e){return e==="open"||e==="warn"||e==="info"}function u0(e){let t="det_number_collisions";if(!e.ok)return B(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return B(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return B(t,"not_applicable","no numbered namespaces");if(!Sa(n))return B(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!nh(s.status))continue;let{level:o,baseline:c}=$n(s.status);i.push({detector_id:t,rule_id:Ca,level:o,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:ze(t,"ran",i.length),findings:i}}function p0(e){let t="det_spec_drift";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return B(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return B(t,"not_applicable",n.reason??"no opinion");if(!ja(n))return B(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!nh(i.status))continue;let{level:s,baseline:o}=$n(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Pa(i.dimension),level:s,baseline:o,evidence:[i.id],title:i.title})}return{summary:ze(t,"ran",r.length),findings:r}}function f0(e){let t="det_theme_class_drift";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable","no theme tokens");if(!tc(n))return B(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=$n(i.status);r.push({detector_id:t,rule_id:Oa,level:s,baseline:o,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:ze(t,"ran",r.length),findings:r}}function m0(e){let t="det_table_acl_lint";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable","no supabase migrations");if(!Za(n))return B(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=$n(i.status);r.push({detector_id:t,rule_id:Da,level:s,baseline:o,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:ze(t,"ran",r.length),findings:r}}function h0(e){let t="det_changelog_duplicates";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return B(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,i.version],title:i.title}));return{summary:ze(t,"ran",r.length),findings:r}}function g0(e){let t="det_workflow_yaml";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return B(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return B(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,String(i.line)],title:i.title}));return{summary:ze(t,"ran",r.length),findings:r}}function y0(e){let t="det_release_claims";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?B(t,"ungraded",n.reason??"registry unreachable"):B(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:ze(t,"ran",r.length),findings:r}}function _0(e){let t="det_agent_doc_prose";if(!e.ok)return B(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.files.length>0&&n.facts.baseRef===null?B(t,"ungraded",n.reason??"no base ref to grade against"):B(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:ze(t,"ran",r.length),findings:r}}function ac(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||rs[e.level]-rs[t.level]||Zm[e.baseline]-Zm[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Qm(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function b0(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=Pr(i.evidence),o=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(o);c?c.count+=1:t.set(o,{detector_id:i.detector_id,detector_version:oc(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,rs[i.level]<rs[o.level]&&(o.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:oc(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Pr(i.evidence),count:i.count});return r.sort(ac)}function w0(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 _e(e){let t={det_number_collisions:u0(e.number),det_spec_drift:p0(e.spec),det_theme_class_drift:f0(e.theme),det_table_acl_lint:m0(e.acl),det_changelog_duplicates:h0(e.changelog),det_workflow_yaml:g0(e.workflow),det_release_claims:y0(e.release),det_agent_doc_prose:_0(e.agentDoc)},n=Xm.map(l=>t[l].summary),r=Xm.flatMap(l=>t[l].findings),i=b0(r),s=[...i].sort((l,d)=>Qm(l)-Qm(d)||ac(l,d)).slice(0,eh).sort(ac),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:Pr(l.evidence),title:l.title}));return{findings:s,coverage:w0(n,o),engines:n,local:c,truncated:o}}function qe(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e},changelog:{ok:!1,error:e},workflow:{ok:!1,error:e},release:{ok:!1,error:e},agentDoc:{ok:!1,error:e}}}function lc(e){return e instanceof Error?e.message:String(e)}async function yt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:lc(t)}}}async function dc(e,t={}){let n={...th,...t.engines};try{if(!rh(e))return _e(qe("not a git work tree"));let r=await ih(e,n,t.baseRef),i=await cc(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return _e({...r,number:i})}catch(r){return _e(qe(`detector adapter failed: ${lc(r)}`))}}async function uc(e,t={}){let n={...th,...t.engines};try{if(!rh(e)){let o=_e(qe("not a git work tree"));return{commit:o,local:o}}let r=await ih(e,n,t.baseRef),i=await cc(e,n,t.baseRef,"commit"),s=await cc(e,n,t.baseRef,"local");return{commit:_e({...r,number:i}),local:_e({...r,number:s})}}catch(r){let i=_e(qe(`detector adapter failed: ${lc(r)}`));return{commit:i,local:i}}}function rh(e){return A(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function ih(e,t,n){let r=n?{baseRef:n}:{};return{spec:await yt(()=>t.spec(e,r)),theme:await yt(()=>t.theme(e,r)),acl:await yt(()=>t.acl(e,r)),changelog:await yt(()=>t.changelog(e,r)),workflow:await yt(()=>t.workflow(e,r)),release:await yt(()=>t.release(e,r)),agentDoc:await yt(()=>t.agentDoc(e,r))}}function cc(e,t,n,r,i){let s=r==="local";return yt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var eh,th,Xm,rs,Zm,pc=_(()=>{"use strict";oe();Ma();Or();Lr();Ba();Va();za();Qi();ts();ns();eh=64,th={number:a((e,t)=>Bt(e,t),"number"),spec:a((e,t)=>Kt(e,t),"spec"),theme:a((e,t)=>qt(e,t),"theme"),acl:a((e,t)=>Vt(e,t),"acl"),changelog:a((e,t)=>Ua(e,t),"changelog"),workflow:a((e,t)=>qa(e,t),"workflow"),release:a((e,t)=>Ga(e,t),"release"),agentDoc:a((e,t)=>Ka(e,t),"agentDoc")},Xm=["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(oc,"versionOf");a(ze,"summary");a(B,"noFindings");a(nh,"isFindingStatus");a(u0,"adaptNumber");a(p0,"adaptSpec");a(f0,"adaptTheme");a(m0,"adaptAcl");a(h0,"adaptChangelog");a(g0,"adaptWorkflow");a(y0,"adaptRelease");a(_0,"adaptAgentDoc");rs={open:0,warn:1,info:2},Zm={introduced:0,pre_existing:1};a(ac,"compareWire");a(Qm,"capPriority");a(b0,"buildWire");a(w0,"deriveCoverage");a(_e,"adaptDetectorReports");a(qe,"unavailableDetectorReports");a(lc,"errorText");a(yt,"attempt");a(dc,"runRepoHealthDetectors");a(uc,"runRepoHealthDetectorScopes");a(rh,"insideWorkTree");a(ih,"runSharedEngines");a(cc,"runNumberEngine")});var sh,fc=_(()=>{"use strict";sh=[{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 oh(e){let t=new Set;for(let[n,r]of e.paths)for(let i of sh){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=v0(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function v0(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
40
|
+
`):t.readUntracked(e)}var ah=_(()=>{"use strict";fc();a(oh,"scanRiskFlags");a(v0,"contentForPath")});var jn,ch,Un,Hn,mc,is,hc,ss,os,as,gc,lh,jr=_(()=>{"use strict";jn="3",ch=`
|
|
41
41
|
CREATE TABLE IF NOT EXISTS meta (
|
|
42
42
|
key TEXT PRIMARY KEY,
|
|
43
43
|
value TEXT NOT NULL
|
|
@@ -125,33 +125,33 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
125
125
|
vec BLOB NOT NULL,
|
|
126
126
|
content_hash TEXT NOT NULL
|
|
127
127
|
);
|
|
128
|
-
`,Nn="schema_version",Cn="last_index_commit",Va="last_indexed_at",Wi="edges_dirty",qa="resolve_config_fp",Gi="embed_recipe_version",Ki="embed_model",Vi="embed_dim",za="last_synced_at",wm="last_synced_commit"});function Ya(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 vm(t){let e=new Set;e.add(t.name.toLowerCase()),e.add(t.qualifiedName.toLowerCase());for(let i of Ya(t.name))e.add(i);for(let i of Ya(t.qualifiedName))e.add(i);let n=[t.doc??"",t.signature??""].join(" ").trim(),r=[...e].join(" ");return n?`${r} ${n}`:r}function km(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 Ya(r))e.add(i)}}return e.size===0?null:[...e].map(n=>`${n}*`).join(" OR ")}var Ja=_(()=>{"use strict";a(Ya,"splitIdentifier");a(vm,"buildSearchText");a(km,"toFtsMatchQuery")});import{readFileSync as xm}from"node:fs";import{posix as Sm}from"node:path";function Em(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 Ht(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(1,Math.min(n,Math.floor(t)))}function Tm(t){return t==="added"?0:t==="modified"?1:2}function uE(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 Cr,Xa=_(()=>{"use strict";mr();wp();Io();kp();Tp();Co();Dp();ne();Wp();Wo();Qo();xr();Ga();Ar();_m();Nr();Ja();Cr=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(Nn),i=await this.store.countFiles()>0;(e.full||i&&r!==In)&&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 b=jo(this.repoRoot,{since:e.onlyChangedSince,includeUncommitted:!1});if(b===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");o=b}else o=Fp(this.repoRoot);let c=new Set(o.map(b=>b.path)),l=new Map(s.map(b=>[b.path,b])),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(Wi,"1"))},"markEdgesDirty");for(let b of s)c.has(b.path)||(await h(),await this.store.deleteFile(b.path),u.filesDeleted++);let m=0;for(let b of o){m++;let w=Up(this.repoRoot,b.path);if(!w){u.filesSkipped++;continue}let k=l.get(b.path);if(k&&k.mtimeMs===w.mtimeMs&&k.size===w.size){u.filesSkipped++;continue}let S=this.readRepoFile(b.path);if(S===null){u.filesSkipped++;continue}let R=Ai(S);if(k&&k.contentHash===R){await this.store.upsertFile({...k,mtimeMs:w.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let D=await this.parser.parse(b.path,S,b.language),F=new Map;for(let U of D.nodes)F.set(U.nodeKey,vm(U));let H={path:b.path,language:b.language,contentHash:R,mtimeMs:w.mtimeMs,size:w.size,indexedAt:n};await h(),await this.store.replaceFileNodes(H,D.nodes,F,{contains:D.edges,refs:D.refs,imports:D.imports,exports:D.exports}),u.filesParsed++,e.onProgress?.({path:b.path,done:m,total:o.length})}let g=xp(this.repoRoot),y=await this.store.getMeta(qa)!==g.fingerprint;if(p||y||await this.store.getMeta(Wi)==="1"){let b=Cp(await this.store.getNameIndex()),w=new kn(g.config,b.files),k=Op(await this.store.getAllFacts(),b,w);await this.store.replaceCrossFileEdges(k),await this.store.setMeta(qa,g.fingerprint),await this.store.setMeta(Wi,"0")}if(this.embedder&&e.embed){let b=await this.store.getNodesByKinds([...Ro]),w=await this.store.getEmbeddingContentHashes(),k=[];for(let R of b){let D=bp(R),F=Ai(`${this.embedder.recipeVersion}\0${D}`);w.get(R.nodeKey)!==F&&k.push({nodeKey:R.nodeKey,text:D,hash:F})}let S=64;for(let R=0;R<k.length;R+=S){let D=k.slice(R,R+S),F=await this.embedder.embedDocuments(D.map(U=>U.text));await this.store.upsertEmbeddings(D.map((U,N)=>({nodeKey:U.nodeKey,dim:this.embedder.dim,vec:F[N],contentHash:U.hash})));let H=Math.min(R+S,k.length);e.onProgress?.({path:"embedding symbols",done:H,total:k.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Gi,this.embedder.recipeVersion),await this.store.setMeta(Ki,this.embedder.model),await this.store.setMeta(Vi,String(this.embedder.dim))}await this.store.setMeta(Nn,In),await this.store.setMeta(Va,String(n));let v=_r(this.repoRoot);return v&&await this.store.setMeta(Cn,v),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(Va);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(Cn),schemaVersion:await this.store.getMeta(Nn),languages:r}}async searchGraph(e,n={}){await this.store.init();let r=Ht(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({...Em(c),score:o.score})}return s}async semanticQuery(e,n={}){if(await this.store.init(),!this.embedder)return[];let r=Ht(n.limit,20,100),i=await this.embedder.embedQuery(e),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:vp(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({...Em(d),score:l.score})}return c}async tracePath(e,n={}){await this.store.init();let r=n.direction??"out",i=Ht(n.maxDepth,3,5),s=Ht(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 v=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(v))continue;if(l.add(v),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let b=r==="out"?y.dstKey:y.srcKey;d.has(b)||(d.add(b),h.push(b))}}u=h}return c}async getCodeSnippet(e){await this.store.init();let n=await this.store.getNode(e);if(!n)return null;let r="";try{r=xm(Sm.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(Ht(e.topN,10,50))}}async changedSymbols(e={}){await this.store.init();let n=jo(this.repoRoot,e);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Ht(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=Ti(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(_r(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Yp(this.repoRoot,n,e)}async checkDivergence(e={}){return vr(this.repoRoot,e)}async checkNumberCollisions(e={}){return Lt(this.repoRoot,e)}async checkNumberForPath(e,n={}){return $t(this.repoRoot,e,n)}async checkSpecDrift(e={}){return Ft(this.repoRoot,e)}async reviewDetectors(e={}){return Ba(this.repoRoot,e)}async reviewDetectorScopes(e={}){return Wa(this.repoRoot,e)}async reviewChanges(e={}){await this.store.init();let n=Ti(this.repoRoot,e);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Bp(this.repoRoot,e),i=r?.files??new Map,s=r?.coverage??"none",o=ym({paths:n,hunks:i,readUntracked:a(h=>this.readRepoFileHead(h,Hp),"readUntracked")}),c=$p(n.keys()),l=Ht(e.limit,64,e.attest?st:200),d=[],u=0,p=0;for(let h of c){let m=await this.store.getNodesByFile(h.path);if(m.length===0)continue;u++;let g=await this.store.getFile(h.path),y=this.readRepoFile(h.path),v=g!==null&&y!==null&&Ai(y)!==g.contentHash;v&&(p++,s==="full"&&(s="partial"));let b=n.get(h.path)??"modified",w=i.get(h.path);for(let k of m)d.push(uE(k,b,w,v))}return d.sort((h,m)=>Tm(h.change)-Tm(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:_r(this.repoRoot),dirty:Uo(this.repoRoot),baseSha:e.since?Ri(this.repoRoot,e.since):null,mergeBaseSha:e.since?Fo(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 xm(Sm.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(Em,"toHit");a(Ht,"clampLimit");a(Tm,"changeRank");a(uE,"classifyReviewSymbol")});var Am=_(()=>{"use strict";ne()});var pE,_F,Rm=_(()=>{"use strict";ne();pE=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],_F=new RegExp(pE.join("|"),"g")});import{existsSync as Za,readdirSync as fE,readFileSync as mE}from"node:fs";import{spawnSync as hE}from"node:child_process";import{dirname as gE,join as qi,posix as Qa}from"node:path";function Nm(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 ${ec} ausweichen \u2014 dorthin schreibt ein Werkzeug ohne Fehlermeldung, ggf. in die Datenbank eines FREMDEN Projekts (real passiert 2026-08-26: 'INSERT 0 1' in den falschen Ledger). Dieses Tool r\xE4t deshalb NIE einen Port und hat keine Verbindung versucht.`,hint:"config.toml aus dem Haupt-Checkout kopieren (sie ist bewusst gitignored \u2014 Ports/Keys sind lokal), dann erneut pr\xFCfen. `.maind/worktree-requirements` deklariert die Datei bereits f\xFCr check_divergence."}),{dir: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 ${ec} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=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(We);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(We),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(We),m=t.remote.versions.filter(g=>!s.has(g)).sort(We);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 Cm(t){return t.length===0?"no_opinion":t.includes("blind")?"blind":t.includes("drift")?"drift":"in_sync"}function Dm(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
|
|
130
|
-
`).map(i=>i.trim()).filter(Boolean)}}function
|
|
131
|
-
`)){if(!s.startsWith("worktree "))continue;let o=s.slice(9).trim();if(!o||o===i||!
|
|
132
|
-
|
|
133
|
-
${i}`};return JSON.stringify({jsonrpc:"2.0",id:
|
|
134
|
-
`,{encoding:"utf8",mode:384});try{
|
|
135
|
-
`,{encoding:"utf8",mode:384});try{
|
|
136
|
-
`,{encoding:"utf8",mode:384}),o0(o,s)}catch{}}function th(t=ke()){try{let e=JSON.parse(s0(eh(t),"utf8"));return e.v!==1||typeof e.at!="string"||!l0.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 l0,d0,u0,yc=_(()=>{"use strict";ie();l0=["ok","paired","auth_failed","not_paired"],d0="connection-state.json",u0=200;a(eh,"connectionStatePath");a(p0,"redactDetail");a(Kt,"writeConnectionState");a(th,"readConnectionState")});var B,dt=_(()=>{"use strict";B="0.80.1"});import{execFileSync as nh}from"node:child_process";import{createHash as f0}from"node:crypto";function m0(t){return f0("sha256").update(t).digest("hex")}function h0(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 rs(t){let e=h0(t);return e?m0(e):null}function z(){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(t&&g0.test(t))return t;let e;try{e=nh("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return e?rs(e):null}function rh(t){let e;try{e=nh("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return e?rs(e):null}var g0,ut=_(()=>{"use strict";a(m0,"sha256Hex");a(h0,"normalizeRemoteUrl");a(rs,"projectKeyFromRemote");g0=/^[a-f0-9]{64}$/;a(z,"computeProjectKey");a(rh,"projectKeyForRepo")});import _0 from"node:path";import{fileURLToPath as b0}from"node:url";function w0(t,e=_0.sep){return t.split(e).includes("_npx")}function De(t){let e=t.extraArgs??[],n=a(r=>({command:"npx",args:["-y",fh,...e],env:{},fallbackReason:r}),"npx");return t.entryPath===null?n("bridge entry path could not be resolved"):w0(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 Me(){try{let t=b0(import.meta.url);return t.endsWith(".js")?t:null}catch{return null}}function Ln(t){let e=Object.entries(t.env).map(([n,r])=>`${n}=${ph(r)}`);return[...e,t.command,...t.args].map((n,r)=>r<e.length?n:ph(n)).join(" ")}function ss(t){return/(^|\s)npx(\s|$)/.test(t)&&t.includes(fh)}function os(t){return/(^|[\s/])maind-hook(\s|$)/.test(t)?!0:/claude-code-hook[/\\]build[/\\]/.test(t)}function ph(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var fh,$n=_(()=>{"use strict";fh="@maind-dev/mcp-bridge";a(w0,"isEphemeralEntry");a(De,"resolveBridgeLaunch");a(Me,"currentBridgeEntry");a(Ln,"launchToShellCommand");a(ss,"isNpxForm");a(os,"isLegacyHookForm");a(ph,"shellQuote")});import*as xe from"node:path";function hh(t){let e=t.launch??De({entryPath:Me(),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 v0(t){switch(t.platform){case"darwin":return xe.join(t.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let e=t.appData??xe.join(t.homeDir,"AppData","Roaming");return xe.join(e,"Claude","claude_desktop_config.json")}default:{let e=t.xdgConfigHome??xe.join(t.homeDir,".config");return xe.join(e,"Claude","claude_desktop_config.json")}}}function as(t){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:xe.join(t.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:xe.join(t.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:v0(t),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:xe.join(t.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:xe.join(t.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:xe.join(t.homeDir,".codex","config.toml"),kind:"toml"}]}function gh(t,e){return e===null?t:t.filter(n=>n.clientFamilyEnv===e)}function cs(t){return{projectRoot:t.projectRoot,homeDir:t.homeDir,platform:t.platform,xdgConfigHome:mh(t.env.XDG_CONFIG_HOME),appData:mh(t.env.APPDATA)}}function mh(t){if(t===void 0)return null;let e=t.trim();return e.length>0?e:null}var _c=_(()=>{"use strict";$n();a(hh,"buildMaindServerEntry");a(v0,"claudeDesktopConfigPath");a(as,"getClientTargets");a(gh,"filterTargetsByFamily");a(cs,"makeDefaultContext");a(mh,"nonEmpty")});import*as Y from"node:fs/promises";import*as ls from"node:path";async function se(t){try{return await Y.readFile(t,"utf8")}catch(e){if(k0(e))return null;throw e}}async function bc(t){await Y.mkdir(t,{recursive:!0})}async function J(t,e,n){let r=ls.dirname(t);await bc(r);let i=ls.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await Y.writeFile(i,e,{encoding:"utf8",mode:n});try{await Y.rename(i,t)}catch(s){if(x0(s))try{await Y.copyFile(i,t),await Y.unlink(i).catch(()=>{}),n!==void 0&&await Y.chmod(t,n).catch(()=>{});return}catch(o){throw await Y.unlink(i).catch(()=>{}),o}throw await Y.unlink(i).catch(()=>{}),s}}async function yh(t,e){let n=await se(t);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(e))}function k0(t){return _h(t)&&t.code==="ENOENT"}function x0(t){return!_h(t)||process.platform!=="win32"?!1:t.code==="EEXIST"||t.code==="EPERM"||t.code==="EACCES"}function _h(t){return typeof t=="object"&&t!==null&&"code"in t}var Ye=_(()=>{"use strict";a(se,"readFileSafe");a(bc,"ensureDir");a(J,"atomicWriteFile");a(yh,"hasLinePrefix");a(k0,"isNoEnt");a(x0,"isWindowsRenameFailure");a(_h,"isNodeError")});import{existsSync as U0}from"node:fs";import*as Sh from"node:path";function qt(t,e={},n=xc){let r=e.fileExists??U0,i=e.expectedCommand??H0,s={};if(t!==null&&t.trim().length>0)try{let o=JSON.parse(t);kc(o)&&(s=o)}catch{}return n.map(o=>{let c={event:o.event,subcommand:o.subcommand},l=B0(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(os(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(ss(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=W0(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 Sc(t){return t.some(e=>e.status!=="ok")}function ps(t){return t.some(e=>e.remedy==="run-install")}function H0(t){return Ln(De({entryPath:Me(),nodePath:process.execPath,extraArgs:[t],isElectron:process.versions.electron!==void 0}))}function B0(t,e,n){let r=t.hooks?.[e];if(!Array.isArray(r))return null;for(let i of r){if(!kc(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!kc(o))continue;let c=o.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function W0(t){for(let e of G0(t))if(e.endsWith(".js")||e.endsWith(".mjs")||e.endsWith(".cjs"))return Sh.isAbsolute(e)?e:null;return null}function G0(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 kc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var xc,us,Fn=_(()=>{"use strict";$n();xc=[{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."}],us=[{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(qt,"inspectHookWiring");a(Sc,"hasWiringDrift");a(ps,"needsInstallRun");a(H0,"defaultExpectedCommand");a(B0,"findCommand");a(W0,"extractScriptPath");a(G0,"tokenize");a(kc,"isObject")});import*as Ac from"node:path";import*as Th from"node:readline";async function Ah(t,e){let n=Ac.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 se(n)}catch(h){return{target:r,action:"merge",status:"failed",detail:`read: ${Ec(h)}`}}let s,o="create";if(i===null||i.trim().length===0)s={};else{o="merge";try{let h=JSON.parse(i);if(!Tc(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: ${Ec(h)}`}}}let c=V0(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 q0(t.out,`
|
|
137
|
-
Merge a ${
|
|
138
|
-
${
|
|
139
|
-
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...
|
|
140
|
-
`;if(
|
|
141
|
-
`,1)[0]??"").trim().slice(0,200)}function iT(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 sT(t,e){let n=new Set;for(let r of t.descendantsOfType(e)){let i=iT(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Nc(t,e,n,r){for(let i of sT(n,r))t.refs.push({fromKey:e,kind:"calls",targetName:i})}function jr(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 mt(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 mt(e.childForFieldName("name"));case"parenthesized_type":return mt(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?mt(n[0]):"#"}default:return"#"}}function aT(t){let e=t?.type==="await_expression"?t.namedChildren[0]??null:t;return e?.type==="call_expression"&&e.childForFieldName("function")?.type==="member_expression"}function Cc(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 Ur(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=mt(n.childForFieldName("type"))??Cc(i)??(aT(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=mt(n.childForFieldName("type"));i&&e.set(r.text,i)}return e}function gt(t,e,n,r,i={locals:Ur(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",...oT]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")o(jr(l.childForFieldName("function")));else if(l.type==="new_expression")o(jr(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;o(jr(d))}}var oT,hs=_(()=>{"use strict";a(fs,"newResult");a(ht,"line1");a(ms,"signatureOf");a(iT,"calleeName");a(sT,"collectCallTargets");a(Nc,"addCallRefs");a(jr,"calleeRef");oT=["jsx_opening_element","jsx_self_closing_element"];a(mt,"typeNameOf");a(aT,"isMethodCallResult");a(Cc,"newTypeOf");a(Ur,"collectTypeHints");a(gt,"addTsRefs")});function Fh(t,e){let n=fs();for(let r of t.namedChildren)cT(r,e,n);return n}function jh(t){return t.type==="decorated_definition"?t.childForFieldName("definition")??t:t}function cT(t,e,n){let r=jh(t);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??dT(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=gs(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&&Nc(n,s.nodeKey,o,$h);return}case"class_definition":lT(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=gs(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 lT(t,e,n){let r=t.childForFieldName("name")?.text;if(!r)return;let i=gs(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=jh(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=gs(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&&Nc(n,p.nodeKey,h,$h)}}function gs(t,e,n,r,i){return{nodeKey:Ne(e.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:e.filePath,language:e.language,startLine:ht(t.startPosition.row),endLine:ht(t.endPosition.row),startByte:t.startIndex,endByte:t.endIndex,signature:ms(t),doc:null}}function dT(t){return t.descendantsOfType("dotted_name")[0]?.text??null}var $h,Uh=_(()=>{"use strict";xn();hs();$h="call";a(Fh,"extractPython");a(jh,"unwrapDecorated");a(cT,"handleTopLevel");a(lT,"addClass");a(gs,"makeNode");a(dT,"firstDottedName")});function Bh(t,e){let n=fs(),r=e.language!=="typescript";for(let i of t.namedChildren)pT(i,e,n,r);return hT(t,e,n),n}function uT(t){return t.type==="export_statement"?t.childForFieldName("declaration")??t:t}function pT(t,e,n,r){if(t.type==="export_statement"&&fT(t,e,n,r))return;let i=uT(t),s=t.type==="export_statement"&&/^export\s+default\b/.test(t.text);switch(i.type){case"import_statement":mT(i,e,n);return;case"function_declaration":case"generator_function_declaration":{let o=Hh(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=yT(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&>(n,e.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";Hh(o,e,n,d?"function":"variable",r,c,l)}return}default:gt(n,e.moduleKey,i,r);return}}function fT(t,e,n,r){if(t.childForFieldName("declaration"))return!1;let i=Mc(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}):gt(n,e.moduleKey,c,r),!0):!1}function mT(t,e,n){let r=Mc(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 hT(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"?Mc(i):null;if(s===null)continue;let c=gT(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 gT(t){let e=t.parent??null,n=e?.type==="await_expression"?e.parent??null:e;return n?.type==="variable_declarator"?n:null}function Hh(t,e,n,r,i,s,o){let l=(s??t.childForFieldName("name"))?.text;if(!l)return null;let d=ys(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;gt(n,d.nodeKey,u,i,{locals:Ur(t)})}else o&>(n,d.nodeKey,o,i);return d}function Oc(t,e,n,r){let i=t.childForFieldName("name")?.text;if(!i)return;let s=ys(t,e,i,i,r);n.nodes.push(s),n.edges.push({srcKey:e.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function yT(t,e,n,r){let i=t.childForFieldName("name")?.text;if(!i)return null;let s=ys(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:Dc(p)})):[{kind:"extends",ref:Dc(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=_T(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&>(n,s.nodeKey,g,r,{locals:Ur(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,h=ys(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&>(n,h.nodeKey,m,r,{locals:Ur(d),thisFields:l})}return s}function _T(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=mt(n.childForFieldName("type"))??Cc(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=mt(r.childForFieldName("type"));i?.type==="identifier"&&s&&e.set(i.text,s)}return e}function ys(t,e,n,r,i){return{nodeKey:Ne(e.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:e.filePath,language:e.language,startLine:ht(t.startPosition.row),endLine:ht(t.endPosition.row),startByte:t.startIndex,endByte:t.endIndex,signature:ms(t),doc:null}}function Dc(t){if(!t)return null;switch(t.type){case"generic_type":return Dc(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 jr(t);default:return null}}function Mc(t){return!t||t.type!=="string"?null:t.text.replace(/^["'`]|["'`]$/g,"")}var Wh=_(()=>{"use strict";xn();hs();a(Bh,"extractTypescript");a(uT,"unwrapExport");a(pT,"handleTopLevel");a(fT,"handleExportForm");a(mT,"addImport");a(hT,"collectDynamicImports");a(gT,"enclosingDeclarator");a(Hh,"addFunctionLike");a(Oc,"addSimpleNamed");a(yT,"addClass");a(_T,"classFieldTypes");a(ys,"makeNode");a(Dc,"heritageRef");a(Mc,"stringValue")});import{createRequire as bT}from"node:module";import{join as wT}from"node:path";function Vh(t,e){return e?wT(e,Gh[t]):bT(import.meta.url).resolve(`tree-sitter-wasms/out/${Gh[t]}`)}var Gh,Kh,qh=_(()=>{"use strict";Gh={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Kh="tree-sitter.wasm";a(Vh,"grammarPath")});import{join as vT}from"node:path";import Pc from"web-tree-sitter";var kT,_s,zh=_(()=>{"use strict";xn();ki();Uh();Wh();hs();qh();kT=["typescript","tsx","javascript","python"],_s=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(e={}){this.assetDir=e.assetDir}async init(){this.initialized||(await Pc.init(this.assetDir?{locateFile:a(e=>vT(this.assetDir,e||Kh),"locateFile")}:void 0),this.parser=new Pc,this.initialized=!0)}supports(e){return kT.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=ot(e),l={nodeKey:c,kind:"module",name:e.split("/").pop()??e,qualifiedName:"<module>",filePath:e,language:r,startLine:1,endLine:ht(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:e,language:r,source:n,moduleKey:c},u=r==="python"?Fh(o,d):Bh(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 Pc.Language.load(Vh(e,this.assetDir)),this.grammars.set(e,n)),n}}});import{createRequire as xT}from"node:module";function Jh(){return Yh("node:sqlite")}function Un(){if(Hr)return Hr;try{let{DatabaseSync:t}=Jh(),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(),Hr={ok:!0}}finally{e.close()}}catch(t){Hr={ok:!1,reason:t instanceof Error?t.message:String(t)}}return Hr}function ST(t){let{DatabaseSync:e}=Jh(),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 ET(t){let e=Yh("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 TT(){let t=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return t==="builtin"||t==="better"?t:null}function bs(t){let e=TT(),n=a(i=>{let s=i==="node:sqlite"?ST(t):ET(t);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(e==="builtin"){let i=Un();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=Un();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 Yh,Hr,Lc=_(()=>{"use strict";Yh=xT(import.meta.url);a(Jh,"loadBuiltin");Hr=null;a(Un,"probeBuiltinSqlite");a(ST,"openBuiltin");a(ET,"openBetter");a(TT,"backendOverride");a(bs,"openSqliteDatabase")});function ig(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 sg(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:Yt(o.receiver),receiverType:Yt(o.receiver_type)});for(let o of n){let c=s(o);if(!c)continue;let l={fromModuleKey:ot(c.filePath),specifier:String(o.specifier),importedName:Yt(o.imported_name),localName:Yt(o.local_name)};c.imports.push(l)}for(let o of r){let c={exportedName:String(o.exported_name),localName:Yt(o.local_name),specifier:Yt(o.specifier),importedName:Yt(o.imported_name)};s(o)?.exports.push(c)}return[...i.values()]}var Xh,Zh,Qh,eg,tg,ng,rg,Yt,og=_(()=>{"use strict";xn();Xh=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Zh="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Qh="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",eg="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",tg="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",ng="SELECT file_path, specifier, imported_name, local_name FROM file_imports",rg="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";a(ig,"factRows");Yt=a(t=>t==null?null:String(t),"str");a(sg,"assembleFacts")});function ws(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 ag,Br,cg=_(()=>{"use strict";Lc();Nr();og();Ja();a(ws,"toNodeRow");ag=400,Br=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(e){let n=bs(e);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(bm)}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=ig(e.path,i),u=this.db.prepare(Zh);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Qh);for(let m of d.imports)p.run(...m);let h=this.db.prepare(eg);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 sg(e,this.db.prepare(tg).all(),this.db.prepare(ng).all(),this.db.prepare(rg).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?ws(n):null}async getNodesByFile(e){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(e).map(ws)}async getNodesByKinds(e){return e.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${e.map(()=>"?").join(",")})`).all(...e).map(ws)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ws)}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=km(e);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
128
|
+
`,Un="schema_version",Hn="last_index_commit",mc="last_indexed_at",is="edges_dirty",hc="resolve_config_fp",ss="embed_recipe_version",os="embed_model",as="embed_dim",gc="last_synced_at",lh="last_synced_commit"});function yc(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 dh(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of yc(e.name))t.add(i);for(let i of yc(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function uh(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 yc(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var _c=_(()=>{"use strict";a(yc,"splitIdentifier");a(dh,"buildSearchText");a(uh,"toFtsMatchQuery")});import{readFileSync as ph}from"node:fs";import{posix as fh}from"node:path";function mh(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function zt(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function hh(e){return e==="added"?0:e==="modified"?1:2}function k0(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let o of n.addedRanges){let c=Math.max(o.start,e.startLine),l=Math.min(o.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(o=>o>=e.startLine-1&&o<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Ur,bc=_(()=>{"use strict";xr();df();Xo();pf();gf();Qo();xf();oe();Df();ua();va();Or();pc();Lr();ah();jr();_c();Ur=class{static{a(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(Un),i=await this.store.countFiles()>0;(t.full||i&&r!==jn)&&await this.wipe();let s=await this.store.getAllFiles(),o;if(t.onlyChangedSince!==void 0){if(s.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let w=aa(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(w===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");o=w}else o=Rf(this.repoRoot);let c=new Set(o.map(w=>w.path)),l=new Map(s.map(w=>[w.path,w])),d=s.length>0&&!t.full,u={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},p=!1,h=a(async()=>{p||(p=!0,await this.store.setMeta(is,"1"))},"markEdgesDirty");for(let w of s)c.has(w.path)||(await h(),await this.store.deleteFile(w.path),u.filesDeleted++);let m=0;for(let w of o){m++;let b=Nf(this.repoRoot,w.path);if(!b){u.filesSkipped++;continue}let k=l.get(w.path);if(k&&k.mtimeMs===b.mtimeMs&&k.size===b.size){u.filesSkipped++;continue}let S=this.readRepoFile(w.path);if(S===null){u.filesSkipped++;continue}let R=Gi(S);if(k&&k.contentHash===R){await this.store.upsertFile({...k,mtimeMs:b.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let D=await this.parser.parse(w.path,S,w.language),F=new Map;for(let U of D.nodes)F.set(U.nodeKey,dh(U));let H={path:w.path,language:w.language,contentHash:R,mtimeMs:b.mtimeMs,size:b.size,indexedAt:n};await h(),await this.store.replaceFileNodes(H,D.nodes,F,{contains:D.edges,refs:D.refs,imports:D.imports,exports:D.exports}),u.filesParsed++,t.onProgress?.({path:w.path,done:m,total:o.length})}let g=ff(this.repoRoot),y=await this.store.getMeta(hc)!==g.fingerprint;if(p||y||await this.store.getMeta(is)==="1"){let w=vf(await this.store.getNameIndex()),b=new On(g.config,w.files),k=kf(await this.store.getAllFacts(),w,b);await this.store.replaceCrossFileEdges(k),await this.store.setMeta(hc,g.fingerprint),await this.store.setMeta(is,"0")}if(this.embedder&&t.embed){let w=await this.store.getNodesByKinds([...Jo]),b=await this.store.getEmbeddingContentHashes(),k=[];for(let R of w){let D=lf(R),F=Gi(`${this.embedder.recipeVersion}\0${D}`);b.get(R.nodeKey)!==F&&k.push({nodeKey:R.nodeKey,text:D,hash:F})}let S=64;for(let R=0;R<k.length;R+=S){let D=k.slice(R,R+S),F=await this.embedder.embedDocuments(D.map(U=>U.text));await this.store.upsertEmbeddings(D.map((U,N)=>({nodeKey:U.nodeKey,dim:this.embedder.dim,vec:F[N],contentHash:U.hash})));let H=Math.min(R+S,k.length);t.onProgress?.({path:"embedding symbols",done:H,total:k.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(ss,this.embedder.recipeVersion),await this.store.setMeta(os,this.embedder.model),await this.store.setMeta(as,String(this.embedder.dim))}await this.store.setMeta(Un,jn),await this.store.setMeta(mc,String(n));let v=Ar(this.repoRoot);return v&&await this.store.setMeta(Hn,v),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(mc);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(Un),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=zt(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let o of i){let c=await this.store.getNode(o.nodeKey);c&&s.push({...mh(c),score:o.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=zt(n.limit,20,100),i=await this.embedder.embedQuery(t),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:uf(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({...mh(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=zt(n.maxDepth,3,5),s=zt(n.limit,100,1e3),o=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let h=[];for(let m of u){let g=await this.store.neighbors(m,r,o,s);for(let y of g){let v=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(v))continue;if(l.add(v),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let w=r==="out"?y.dstKey:y.srcKey;d.has(w)||(d.add(w),h.push(w))}}u=h}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=ph(fh.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let o of n)i[o.kind]=o.count;let s={};for(let o of r)s[o.language]=o.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(zt(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=aa(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=zt(t.limit,64,200),i=[],s=0;for(let o of n){let c=await this.store.getNodesByFile(o.path);c.length>0&&s++,i.push(...c)}return i.sort((o,c)=>o.filePath.localeCompare(c.filePath)||o.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Hi(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(Ar(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return jf(this.repoRoot,n,t)}async checkDivergence(t={}){return Nr(this.repoRoot,t)}async checkNumberCollisions(t={}){return Bt(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Wt(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Kt(this.repoRoot,t)}async reviewDetectors(t={}){return dc(this.repoRoot,t)}async reviewDetectorScopes(t={}){return uc(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Hi(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Of(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",o=oh({paths:n,hunks:i,readUntracked:a(h=>this.readRepoFileHead(h,Cf),"readUntracked")}),c=Af(n.keys()),l=zt(t.limit,64,t.attest?ft:200),d=[],u=0,p=0;for(let h of c){let m=await this.store.getNodesByFile(h.path);if(m.length===0)continue;u++;let g=await this.store.getFile(h.path),y=this.readRepoFile(h.path),v=g!==null&&y!==null&&Gi(y)!==g.contentHash;v&&(p++,s==="full"&&(s="partial"));let w=n.get(h.path)??"modified",b=i.get(h.path);for(let k of m)d.push(k0(k,w,b,v))}return d.sort((h,m)=>hh(h.change)-hh(m.change)||(h.filePath<m.filePath?-1:h.filePath>m.filePath?1:0)||h.startLine-m.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:o,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:Ar(this.repoRoot),dirty:ca(this.repoRoot),baseSha:t.since?Bi(this.repoRoot,t.since):null,mergeBaseSha:t.since?oa(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return ph(fh.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};a(mh,"toHit");a(zt,"clampLimit");a(hh,"changeRank");a(k0,"classifyReviewSymbol")});var gh=_(()=>{"use strict";oe()});var x0,l1,yh=_(()=>{"use strict";oe();x0=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],l1=new RegExp(x0.join("|"),"g")});import{existsSync as wc,readdirSync as S0,readFileSync as E0}from"node:fs";import{spawnSync as T0}from"node:child_process";import{dirname as A0,join as cs,posix as vc}from"node:path";function bh(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 ${kc} 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 ${kc} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,h=r!==null&&r.ok===!1?r.detail:void 0,g={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${h?`: ${h}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),s=new Set(e.fileVersions),o=e.fileVersions.filter(p=>!i.has(p)).sort(We);o.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${o.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${o.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:o});let c=r.versions.filter(p=>!s.has(p)).sort(We),l=new Map,d=[];for(let p of c){let h=e.siblingVersions.get(p);if(h){let m=l.get(h)??[];m.push(p),l.set(h,m)}else d.push(p)}for(let[p,h]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${h.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${h.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:h});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),h=e.fileVersions.filter(g=>!p.has(g)).sort(We),m=e.remote.versions.filter(g=>!s.has(g)).sort(We);h.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${h.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${h.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:h}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function wh(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function kh(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
|
|
129
|
+
`).filter(Boolean).slice(-1)[0]}}function _h(e,t,n){let r=e(t,R0,n);return r.ok===!1?kh(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
130
|
+
`).map(i=>i.trim()).filter(Boolean)}}function xh(e){for(let t of e.split(/^\[/m)){if(!/^db\]/.test(t))continue;let n=/^\s*port\s*=\s*(\d+)/m.exec(t.slice(t.indexOf("]")+1));if(n)return Number(n[1])}return null}function I0(e){let t=A(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=A0(t);return n===e?null:n}function N0(e,t,n){let r=vc.dirname(t),s=[{path:cs(e,r,"config.toml"),source:"worktree"}],o=I0(e);o&&s.push({path:cs(o,r,"config.toml"),source:"main_worktree"});for(let c of s)if(wc(c.path))try{let l=xh(E0(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 C0(e,t){let n=new Map,r=A(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=A(e,["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||!wc(o))continue;let c=cs(o,t);if(wc(c))try{for(let l of S0(c)){let d=Pn(l);d!==null&&!n.has(d)&&n.set(d,o)}}catch{}}return n}function xc(e,t={}){let n=t.runPsql??vh,r=t.timeoutMs??15e3,i=[],s=Gt(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let o=[],c=[],l=[];for(let p of s){let h=N0(e,p.dir,i),m=h.source==="missing"?null:_h(n,`postgresql://postgres:postgres@127.0.0.1:${h.port}/postgres`,r),g=t.remoteDbUrl!==void 0?_h(n,t.remoteDbUrl,r):null,y=bh({dir:p.dir,projectRoot:cs(e,vc.dirname(vc.dirname(p.dir))),fileVersions:p.files.map(v=>v.version),config:h,ledger:m,siblingVersions:C0(e,p.dir),remote:g});o.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let d=wh(l),u={open:0,warn:1,info:2};return o.sort((p,h)=>u[p.status]-u[h.status]||p.id.localeCompare(h.id)),{ok:d==="in_sync",verdict:d,findings:o,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var kc,vh,R0,Sh=_(()=>{"use strict";oe();Ir();kc=54322;a(bh,"evaluateLedgerProject");a(wh,"deriveLedgerVerdict");vh=a((e,t,n)=>{let r=T0("psql",[e,"-tAc",t],{encoding:"utf8",timeout:n,env:{...process.env,PGCONNECT_TIMEOUT:"5"}});return r.error&&r.error.code==="ENOENT"?{ok:!1,code:"enoent",stderr:""}:r.status!==0?{ok:!1,code:"error",stderr:(r.stderr??"").trim()}:{ok:!0,stdout:r.stdout??""}},"defaultRunPsql"),R0="select version from supabase_migrations.schema_migrations order by version";a(kh,"classifyLedgerError");a(_h,"readLedger");a(xh,"parseDbPort");a(I0,"mainWorktreeRoot");a(N0,"resolveConfig");a(C0,"gatherSiblingVersions");a(xc,"checkMigrationLedgerDrift")});var Sc,Ec=_(()=>{"use strict";Sc="0.2.0"});function Tc(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:ft,attest:!0}}function Ac(e,t){let n=0,r=[];for(let s of e.symbols){let o=s.qualifiedName?s.qualifiedName:void 0;if(s.name.length===0||s.name.length>ls||o!==void 0&&o.length>ds){n+=1;continue}r.push({name:s.name,...o!==void 0?{qualified_name:o}:{},...s.kind&&s.kind.length<=Th?{kind:s.kind}:{},...s.language&&s.language.length<=Ah?{language:s.language}:{},change:s.change,changed_line_count:Math.min(Math.max(0,s.changedLineCount),Rh)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(s=>({detector_id:s.detector_id,detector_version:s.detector_version,state:s.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Sc},dropped:n}}function Rc(e,t,n){return e?{persist:!1,skipped:"no_report"}:n.headSha?t?n.baseKind==="ref"&&typeof n.mergeBaseSha!="string"?{persist:!1,skipped:"no_merge_base"}:{persist:!0,skipped:null}:{persist:!1,skipped:"no_project_key"}:{persist:!1,skipped:"no_head"}}function Ic(e,t,n){let r=t,i=[];r===0?i.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):i.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&i.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&i.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let s=e.changedFiles-e.indexedFiles;return s>0&&i.push(`${s} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&i.push(`Symbol list truncated at ${ft} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&i.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),i.join(" ")}function Nc(e){let t=/^MCP error (-?\d+):\s*([\s\S]*)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]??"";return n===Eh&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===Eh?{kind:"invalid_params",code:n,detail:r,issues:O0(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function O0(e){let t=e.indexOf("[");if(t===-1)return[];try{let n=JSON.parse(e.slice(t));return Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null):[]}catch{return[]}}function Cc(e){if(e.kind!=="invalid_params"||e.issues.length!==1)return!1;let t=e.issues[0],n=t.path??[];return n.length===1&&n[0]==="findings"&&t.code==="invalid_type"&&(t.received===void 0||t.received==="undefined")}var ls,ds,Th,Ah,Rh,Eh,D0,Ih=_(()=>{"use strict";xr();Ec();ls=200,ds=512,Th=64,Ah=32,Rh=1e4;a(Tc,"attestReviewOptions");a(Ac,"buildAttestPayload");a(Rc,"attestPersistDecision");a(Ic,"attestCoverageNote");Eh=-32602;a(Nc,"classifyMcpErrorText");a(O0,"parseIssues");a(Cc,"isLegacyAttestRejection");D0=`MCP error -32602: Input validation error: Invalid arguments for tool review_verdict: ${JSON.stringify([{code:"invalid_type",expected:"array",received:"undefined",path:["findings"],message:"Required"}],null,2)}`});var Yt=_(()=>{"use strict";tu();bc();ua();fc();oe();Qi();za();Ba();Va();va();gh();yh();ha();Or();ns();Lr();Ir();ts();Sh();Ma();pc();Or();Lr();ns();ts();$i();Xo();jr();ji();Ec();Ih()});import{execFileSync as P0}from"node:child_process";import{createHash as M0}from"node:crypto";import{mkdirSync as L0,readFileSync as $0,renameSync as F0,writeFileSync as j0}from"node:fs";import{dirname as Nh,join as Ch}from"node:path";function Ye(e=process.cwd()){try{let t=P0("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function Gn(e){return M0("sha256").update(e).digest("hex").slice(0,16)}function us(e){return Ch(e,U0)}function Oh(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Dh(e,t,n,r=new Date().toISOString()){try{if(!Oh(n))return;let i={version:Oc,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},s=us(e);L0(Nh(s),{recursive:!0}),Tr(Nh(s));let o=`${s}.${process.pid}.tmp`;j0(o,JSON.stringify(i,null,2),"utf8"),F0(o,s)}catch{}}function Ph(e,t){try{let n=$0(us(e),"utf8"),r=JSON.parse(n);return r.version!==Oc||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Oh(r.result)?null:{version:Oc,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Mh(e,t,n=new Date){let r=H0(t.cached_at,n),i=t.result.instructions??"",s={...t.result,instructions:`${r}
|
|
132
|
+
|
|
133
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:s})}function H0(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${G0(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function G0(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let s=Math.floor(i/60);if(s<24)return`${s} hour${s===1?"":"s"} ago`;let o=Math.floor(s/24);return`${o} day${o===1?"":"s"} ago`}var Oc,U0,Jt=_(()=>{"use strict";Yt();Oc=1,U0=Ch(".maind","conventions-cache.json");a(Ye,"resolveRepoRoot");a(Gn,"keyFingerprint");a(us,"cachePath");a(Oh,"hasInstructions");a(Dh,"writeConventionsCache");a(Ph,"readConventionsCache");a(Mh,"buildCachedInitializeResponse");a(H0,"fallbackMarker");a(G0,"relativeAge")});import{existsSync as hs,mkdirSync as Q0,readFileSync as Fh,writeFileSync as $c,chmodSync as jh}from"node:fs";import{homedir as eT,hostname as tT,platform as Lc,release as nT}from"node:os";import{randomUUID as rT}from"node:crypto";import{join as Xt}from"node:path";function Se(){let e=eT(),t=process.env;if(Lc()==="darwin")return Xt(e,"Library","Application Support","maind");if(Lc()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Xt(e,"AppData","Roaming");return Xt(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Xt(e,".config");return Xt(n,"maind")}function Uh(e){hs(e)||Q0(e,{recursive:!0,mode:448})}function X(){let e=Se();Uh(e);let t=Xt(e,iT);if(hs(t)){let r=Fh(t,"utf8").trim();if(aT(r))return r}let n=rT();$c(t,n+`
|
|
134
|
+
`,{encoding:"utf8",mode:384});try{jh(t,384)}catch{}return n}function aT(e){return oT.test(e)}function Fc(){return Xt(Se(),sT)}function Zt(e){let t=Se();Uh(t);let n=Fc();$c(n,e+`
|
|
135
|
+
`,{encoding:"utf8",mode:384});try{jh(n,384)}catch{}}function K(){let e=Fc();if(!hs(e))return null;let t=Fh(e,"utf8").trim();return t.length>0?t:null}function Br(){let e=Fc();hs(e)&&$c(e,"",{encoding:"utf8",mode:384})}function Hh(){try{return`mcp-bridge-${tT()}`}catch{return"mcp-bridge"}}function gs(e){return{os:`${Lc()} ${nT()}`,ide:"mcp-bridge",ext_version:e,device_id:X()}}var iT,sT,oT,se=_(()=>{"use strict";a(Se,"configDir");a(Uh,"ensureDir");iT="device-id",sT="api-key";a(X,"ensureDeviceId");oT=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;a(aT,"isUuid");a(Fc,"apiKeyPath");a(Zt,"writeApiKey");a(K,"readApiKey");a(Br,"clearApiKey");a(Hh,"bridgeLabel");a(gs,"clientMeta")});function Wr(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:cT}function Bn(e){return`${Wr()}/${e.replace(/^\/+/,"")}`}var cT,Wn=_(()=>{"use strict";cT="https://fn.maind.dev/functions/v1";a(Wr,"functionsOrigin");a(Bn,"functionsUrl")});import{mkdirSync as hT,readFileSync as gT,renameSync as yT,writeFileSync as _T}from"node:fs";import{join as bT}from"node:path";function Bh(e=Se()){return bT(e,vT)}function xT(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,kT)}function Qt(e,t,n){try{let r=n.dir??Se();hT(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:xT(t),bridge_version:n.version},s=Bh(r),o=`${s}.${process.pid}.tmp`;_T(o,JSON.stringify(i)+`
|
|
136
|
+
`,{encoding:"utf8",mode:384}),yT(o,s)}catch{}}function Wh(e=Se()){try{let t=JSON.parse(gT(Bh(e),"utf8"));return t.v!==1||typeof t.at!="string"||!wT.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 wT,vT,kT,jc=_(()=>{"use strict";se();wT=["ok","paired","auth_failed","not_paired"],vT="connection-state.json",kT=200;a(Bh,"connectionStatePath");a(xT,"redactDetail");a(Qt,"writeConnectionState");a(Wh,"readConnectionState")});var G,Je=_(()=>{"use strict";G="0.82.0"});import{execFileSync as Kh}from"node:child_process";import{createHash as ST}from"node:crypto";function ET(e){return ST("sha256").update(e).digest("hex")}function TT(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 ys(e){let t=TT(e);return t?ET(t):null}function q(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&AT.test(e))return e;let t;try{t=Kh("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?ys(t):null}function Vh(e){let t;try{t=Kh("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?ys(t):null}var AT,De=_(()=>{"use strict";a(ET,"sha256Hex");a(TT,"normalizeRemoteUrl");a(ys,"projectKeyFromRemote");AT=/^[a-f0-9]{64}$/;a(q,"computeProjectKey");a(Vh,"projectKeyForRepo")});import IT from"node:path";import{fileURLToPath as NT}from"node:url";function CT(e,t=IT.sep){return e.split(t).includes("_npx")}function Me(e){let t=e.extraArgs??[],n=a(r=>({command:"npx",args:["-y",ng,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):CT(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function Le(){try{let e=NT(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}=${tg(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:tg(n)).join(" ")}function bs(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(ng)}function ws(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function tg(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var ng,qn=_(()=>{"use strict";ng="@maind-dev/mcp-bridge";a(CT,"isEphemeralEntry");a(Me,"resolveBridgeLaunch");a(Le,"currentBridgeEntry");a(Vn,"launchToShellCommand");a(bs,"isNpxForm");a(ws,"isLegacyHookForm");a(tg,"shellQuote")});import*as Ee from"node:path";function ig(e){let t=e.launch??Me({entryPath:Le(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}function OT(e){switch(e.platform){case"darwin":return Ee.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??Ee.join(e.homeDir,"AppData","Roaming");return Ee.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??Ee.join(e.homeDir,".config");return Ee.join(t,"Claude","claude_desktop_config.json")}}}function vs(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:Ee.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:Ee.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:OT(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:Ee.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:Ee.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Ee.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function sg(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function ks(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:rg(e.env.XDG_CONFIG_HOME),appData:rg(e.env.APPDATA)}}function rg(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}var Uc=_(()=>{"use strict";qn();a(ig,"buildMaindServerEntry");a(OT,"claudeDesktopConfigPath");a(vs,"getClientTargets");a(sg,"filterTargetsByFamily");a(ks,"makeDefaultContext");a(rg,"nonEmpty")});import*as Z from"node:fs/promises";import*as xs from"node:path";async function ae(e){try{return await Z.readFile(e,"utf8")}catch(t){if(DT(t))return null;throw t}}async function Hc(e){await Z.mkdir(e,{recursive:!0})}async function Q(e,t,n){let r=xs.dirname(e);await Hc(r);let i=xs.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await Z.writeFile(i,t,{encoding:"utf8",mode:n});try{await Z.rename(i,e)}catch(s){if(PT(s))try{await Z.copyFile(i,e),await Z.unlink(i).catch(()=>{}),n!==void 0&&await Z.chmod(e,n).catch(()=>{});return}catch(o){throw await Z.unlink(i).catch(()=>{}),o}throw await Z.unlink(i).catch(()=>{}),s}}async function og(e,t){let n=await ae(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function DT(e){return ag(e)&&e.code==="ENOENT"}function PT(e){return!ag(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function ag(e){return typeof e=="object"&&e!==null&&"code"in e}var Xe=_(()=>{"use strict";a(ae,"readFileSafe");a(Hc,"ensureDir");a(Q,"atomicWriteFile");a(og,"hasLinePrefix");a(DT,"isNoEnt");a(PT,"isWindowsRenameFailure");a(ag,"isNodeError")});import{existsSync as XT}from"node:fs";import*as fg from"node:path";function tn(e,t={},n=Kc){let r=t.fileExists??XT,i=t.expectedCommand??ZT,s={};if(e!==null&&e.trim().length>0)try{let o=JSON.parse(e);Wc(o)&&(s=o)}catch{}return n.map(o=>{let c={event:o.event,subcommand:o.subcommand},l=QT(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(ws(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(bs(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=eA(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 Vc(e){return e.some(t=>t.status!=="ok")}function Ts(e){return e.some(t=>t.remedy==="run-install")}function ZT(e){return Vn(Me({entryPath:Le(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function QT(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Wc(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!Wc(o))continue;let c=o.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function eA(e){for(let t of tA(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return fg.isAbsolute(t)?t:null;return null}function tA(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 Wc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Kc,Es,zn=_(()=>{"use strict";qn();Kc=[{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."}],Es=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. With the guard-difficulty hook also installed (ADR-360), block mode may in addition deny edits during an open difficulty episode until a maind consultation happens \u2014 reading only that hook's local log. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."},{event:"PostToolUseFailure",subcommand:"guard-difficulty",label:"Guard difficulty hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-difficulty' after a tool call FAILS (ADR-360). For Bash and for MCP tools other than maind's own it reads the tool NAME and, for Bash, the PROGRAM and subcommand of the command line (e.g. `pnpm test`) \u2014 never paths, flags, values, the error text or any output \u2014 and appends one line (time, 'fail', that program name) to a local per-session log in ~/.maind/guard/triggers/. File tools, lookups such as grep or ls, interrupts you caused and subagent calls are not counted. When four failed attempts follow each other without a ten-minute pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key like guard-inject \u2014 never tool data \u2014 and, if conv_consult_on_difficulty is on for you, adds ONE hint for the model to consult maind before the next attempt. Only in block mode ('guard mode block') and only if that convention is required does the gate hook then deny edits until a consultation happens (override: 'guard skip --kind difficulty'). Off on this machine: 'guard difficulty off'; off everywhere: switch the convention off in your maind settings. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-outcome",label:"Guard outcome hook",timeout:10,matcher:"Bash|mcp__.*",consentDescription:"It runs 'maind-mcp-bridge guard-outcome' after a Bash or MCP tool call SUCCEEDS (ADR-360). Test and build runs often end with exit code 0 because their output is piped through `tail` or `grep`, so for Bash it reads the LAST 8 KB of stdout/stderr on this machine to recognise a failure summary (e.g. '2 failed', 'error TS2322', 'ELIFECYCLE') and then discards it \u2014 no output is stored or sent. It writes the same kind of line as guard-difficulty (time, fail or ok, a program name such as `pnpm test`), and an 'ok' only for a program that already failed in this session: that is how a fixed problem is recognised. The log stays in ~/.maind/guard/triggers/; nothing leaves the machine. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-capture",label:"Guard capture hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-capture' when a turn ends (ADR-360). Only after a hard-won fix recorded by the guard-difficulty and guard-outcome hooks \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it holds the end of the turn ONCE per episode with a reason asking the agent to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'; off everywhere: the convention switch. Inactive while guard mode is off."}];a(tn,"inspectHookWiring");a(Vc,"hasWiringDrift");a(Ts,"needsInstallRun");a(ZT,"defaultExpectedCommand");a(QT,"findCommand");a(eA,"extractScriptPath");a(tA,"tokenize");a(Wc,"isObject")});import*as Yc from"node:path";import*as hg from"node:readline";async function gg(e,t){let n=Yc.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 ae(n)}catch(h){return{target:r,action:"merge",status:"failed",detail:`read: ${qc(h)}`}}let s,o="create";if(i===null||i.trim().length===0)s={};else{o="merge";try{let h=JSON.parse(i);if(!zc(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: ${qc(h)}`}}}let c=rA(s,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:o==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await iA(e.out,`
|
|
137
|
+
Merge a ${t.event} hook into ${n}?
|
|
138
|
+
${t.consentDescription}
|
|
139
|
+
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=s.hooks?.[t.event]??[],u={...s,hooks:{...s.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
140
|
+
`;if(e.dryRun)return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:n};try{await Q(n,p,384)}catch(h){return{target:r,action:"merge",status:"failed",detail:`write: ${qc(h)}`}}return{target:r,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:n}}async function yg(e){let t=Yc.join(e.homeDir,mg);return gg(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:a(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${mg} into every new Claude Code session.`})}function nA(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Jc(e,t){let n=e.launch??Me({entryPath:Le(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Vn(n);return gg(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:nA(t),skipDetail:a(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return ws(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}`:bs(i)?`${s}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:s},"skipDetail"),consentDescription:t.consentDescription})}async function _g(e){let t=[];for(let n of Kc)t.push(await Jc(e,n));return t}function rA(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!zc(i))continue;let s=i.hooks;if(Array.isArray(s))for(let o of s){if(!zc(o))continue;let c=o.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function iA(e,t){e.write(t);let n=hg.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function zc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qc(e){return e instanceof Error?e.message:String(e)}var mg,Xc=_(()=>{"use strict";Xe();qn();zn();mg=".claude/maind-session-start-reminder.md";a(gg,"mergeClaudeHook");a(yg,"mergeSessionStartHook");a(nA,"targetKeyFor");a(Jc,"mergeSubcommandHook");a(_g,"mergeAllSubcommandHooks");a(rA,"findExistingHookCommand");a(iA,"promptYesNo");a(zc,"isObject");a(qc,"errMessage")});import{existsSync as sA,readFileSync as oA}from"node:fs";import{join as aA}from"node:path";function Qe(){return aA(Se(),"config.json")}function $e(){try{let e=Qe();if(!sA(e))return null;let t=JSON.parse(oA(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),typeof n.guard_difficulty=="boolean"&&(r.guard_difficulty=n.guard_difficulty),typeof n.guard_capture=="boolean"&&(r.guard_capture=n.guard_capture),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),r}catch{return null}}var Yn=_(()=>{"use strict";se();a(Qe,"bridgeConfigPath");a($e,"readBridgeConfig")});function As(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function vt(e){return e+1}function Rs(e){return(e.text.split(`
|
|
141
|
+
`,1)[0]??"").trim().slice(0,200)}function hA(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 gA(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=hA(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Zc(e,t,n,r){for(let i of gA(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function zr(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let i=n;for(;i?.type==="member_expression";)i=i.childForFieldName("object");return i?.type==="this"?{name:t,receiver:"this.*"}:i?.type==="identifier"?{name:t,receiver:`${i.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function wt(e){if(!e)return null;let t=e.type==="type_annotation"?e.namedChildren[0]??null:e;if(!t)return null;switch(t.type){case"type_identifier":return t.text;case"nested_type_identifier":return t.text.replace(/\s+/g,"");case"generic_type":return wt(t.childForFieldName("name"));case"parenthesized_type":return wt(t.namedChildren[0]??null);case"union_type":{let n=t.namedChildren.filter(r=>!(r.type==="literal_type"&&/^(null|undefined)$/.test(r.text))&&!(r.type==="predefined_type"&&/^(null|undefined|void)$/.test(r.text)));return n.length===1?wt(n[0]):"#"}default:return"#"}}function _A(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function Qc(e){if(e?.type!=="new_expression")return null;let t=e.childForFieldName("constructor");return t?.type==="identifier"||t?.type==="member_expression"?t.text:null}function Yr(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),s=wt(n.childForFieldName("type"))??Qc(i)??(_A(i)?"#":null);s&&t.set(r.text,s)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=wt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function kt(e,t,n,r,i={locals:Yr(n)}){let s=new Set,o=a(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(s.has(d))return;s.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...yA]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")o(zr(l.childForFieldName("function")));else if(l.type==="new_expression")o(zr(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;o(zr(d))}}var yA,Is=_(()=>{"use strict";a(As,"newResult");a(vt,"line1");a(Rs,"signatureOf");a(hA,"calleeName");a(gA,"collectCallTargets");a(Zc,"addCallRefs");a(zr,"calleeRef");yA=["jsx_opening_element","jsx_self_closing_element"];a(wt,"typeNameOf");a(_A,"isMethodCallResult");a(Qc,"newTypeOf");a(Yr,"collectTypeHints");a(kt,"addTsRefs")});function Ag(e,t){let n=As();for(let r of e.namedChildren)bA(r,t,n);return n}function Rg(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function bA(e,t,n){let r=Rg(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??vA(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=Ns(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=r.childForFieldName("body");o&&Zc(n,s.nodeKey,o,Tg);return}case"class_definition":wA(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(o=>o.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let o=Ns(r,t,s.text,s.text,"variable");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}return}default:return}}function wA(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Ns(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let o=e.childForFieldName("body");if(o)for(let c of o.namedChildren){let l=Rg(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=Ns(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&Zc(n,p.nodeKey,h,Tg)}}function Ns(e,t,n,r,i){return{nodeKey:Ce(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vt(e.startPosition.row),endLine:vt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Rs(e),doc:null}}function vA(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var Tg,Ig=_(()=>{"use strict";Dn();Is();Tg="call";a(Ag,"extractPython");a(Rg,"unwrapDecorated");a(bA,"handleTopLevel");a(wA,"addClass");a(Ns,"makeNode");a(vA,"firstDottedName")});function Cg(e,t){let n=As(),r=t.language!=="typescript";for(let i of e.namedChildren)xA(i,t,n,r);return TA(e,t,n),n}function kA(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function xA(e,t,n,r){if(e.type==="export_statement"&&SA(e,t,n,r))return;let i=kA(e),s=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":EA(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let o=Ng(i,t,n,"function",r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"class_declaration":case"abstract_class_declaration":{let o=RA(i,t,n,r);s&&o&&n.exports.push({exportedName:"default",localName:o.name});return}case"interface_declaration":el(i,t,n,"interface");return;case"type_alias_declaration":el(i,t,n,"type_alias");return;case"enum_declaration":el(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let o of i.namedChildren){if(o.type!=="variable_declarator")continue;let c=o.childForFieldName("name"),l=o.childForFieldName("value");if(!c||c.type!=="identifier"){l&&kt(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";Ng(o,t,n,d?"function":"variable",r,c,l)}return}default:kt(n,t.moduleKey,i,r);return}}function SA(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=nl(e.childForFieldName("source")),s=e.namedChildren.find(l=>l.type==="export_clause"),o=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),s)for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(o){let l=o.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(s){for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):kt(n,t.moduleKey,c,r),!0):!1}function EA(e,t,n){let r=nl(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),s=[],o=a((c,l)=>{s.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")o("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&o("*",l)}else if(c.type==="named_imports")for(let l of c.namedChildren.filter(d=>d.type==="import_specifier")){let d=l.childForFieldName("name")?.text;d&&o(d,l.childForFieldName("alias")?.text??d)}s.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...s)}function TA(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,s=i?.type==="string"?nl(i):null;if(s===null)continue;let c=AA(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:s})}}function AA(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function Ng(e,t,n,r,i,s,o){let l=(s??e.childForFieldName("name"))?.text;if(!l)return null;let d=Cs(e,t,l,l,r);if(n.nodes.push(d),n.edges.push({srcKey:t.moduleKey,dstKey:d.nodeKey,kind:"contains"}),r==="function"){let u=o??e.childForFieldName("body")??e;kt(n,d.nodeKey,u,i,{locals:Yr(e)})}else o&&kt(n,d.nodeKey,o,i);return d}function el(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Cs(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function RA(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let s=Cs(e,t,i,i,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of o?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(p=>({kind:"implements",ref:tl(p)})):[{kind:"extends",ref:tl(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:h}of u)h&&n.refs.push({fromKey:s.nodeKey,kind:p,targetName:h.name,receiver:h.receiver})}let c=e.childForFieldName("body");if(!c)return s;let l=IA(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&kt(n,s.nodeKey,g,r,{locals:Yr(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,h=Cs(d,t,u,p,"method");n.nodes.push(h),n.edges.push({srcKey:s.nodeKey,dstKey:h.nodeKey,kind:"contains"});let m=d.childForFieldName("body");m&&kt(n,h.nodeKey,m,r,{locals:Yr(d),thisFields:l})}return s}function IA(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),i=wt(n.childForFieldName("type"))??Qc(n.childForFieldName("value"));r&&i&&t.set(r.text,i)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(o=>o.type==="accessibility_modifier"||o.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),s=wt(r.childForFieldName("type"));i?.type==="identifier"&&s&&t.set(i.text,s)}return t}function Cs(e,t,n,r,i){return{nodeKey:Ce(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vt(e.startPosition.row),endLine:vt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Rs(e),doc:null}}function tl(e){if(!e)return null;switch(e.type){case"generic_type":return tl(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return zr(e);default:return null}}function nl(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var Og=_(()=>{"use strict";Dn();Is();a(Cg,"extractTypescript");a(kA,"unwrapExport");a(xA,"handleTopLevel");a(SA,"handleExportForm");a(EA,"addImport");a(TA,"collectDynamicImports");a(AA,"enclosingDeclarator");a(Ng,"addFunctionLike");a(el,"addSimpleNamed");a(RA,"addClass");a(IA,"classFieldTypes");a(Cs,"makeNode");a(tl,"heritageRef");a(nl,"stringValue")});import{createRequire as NA}from"node:module";import{join as CA}from"node:path";function Mg(e,t){return t?CA(t,Dg[e]):NA(import.meta.url).resolve(`tree-sitter-wasms/out/${Dg[e]}`)}var Dg,Pg,Lg=_(()=>{"use strict";Dg={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Pg="tree-sitter.wasm";a(Mg,"grammarPath")});import{join as OA}from"node:path";import rl from"web-tree-sitter";var DA,Os,$g=_(()=>{"use strict";Dn();$i();Ig();Og();Is();Lg();DA=["typescript","tsx","javascript","python"],Os=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await rl.init(this.assetDir?{locateFile:a(t=>OA(this.assetDir,t||Pg),"locateFile")}:void 0),this.parser=new rl,this.initialized=!0)}supports(t){return DA.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let o=s.rootNode,c=mt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:vt(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?Ag(o,d):Cg(o,d);return s.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await rl.Language.load(Mg(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as PA}from"node:module";function jg(){return Fg("node:sqlite")}function Jn(){if(Jr)return Jr;try{let{DatabaseSync:e}=jg(),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(),Jr={ok:!0}}finally{t.close()}}catch(e){Jr={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Jr}function MA(e){let{DatabaseSync:t}=jg(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function LA(e){let t=Fg("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}function $A(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Ds(e){let t=$A(),n=a(i=>{let s=i==="node:sqlite"?MA(e):LA(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=Jn();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=Jn();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 Fg,Jr,il=_(()=>{"use strict";Fg=PA(import.meta.url);a(jg,"loadBuiltin");Jr=null;a(Jn,"probeBuiltinSqlite");a(MA,"openBuiltin");a(LA,"openBetter");a($A,"backendOverride");a(Ds,"openSqliteDatabase")});function qg(e,t){return{refs:t.refs.map(n=>[e,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:t.imports.map(n=>[e,n.specifier,n.importedName??null,n.localName??null]),exports:t.exports.map(n=>[e,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function zg(e,t,n,r){let i=new Map;for(let o of e)i.set(o.path,{filePath:o.path,language:o.language,refs:[],imports:[],exports:[]});let s=a(o=>i.get(String(o.file_path)),"entry");for(let o of t)s(o)?.refs.push({fromKey:String(o.src_key),kind:String(o.kind),targetName:String(o.target_name),receiver:rn(o.receiver),receiverType:rn(o.receiver_type)});for(let o of n){let c=s(o);if(!c)continue;let l={fromModuleKey:mt(c.filePath),specifier:String(o.specifier),importedName:rn(o.imported_name),localName:rn(o.local_name)};c.imports.push(l)}for(let o of r){let c={exportedName:String(o.exported_name),localName:rn(o.local_name),specifier:rn(o.specifier),importedName:rn(o.imported_name)};s(o)?.exports.push(c)}return[...i.values()]}var Ug,Hg,Gg,Bg,Wg,Kg,Vg,rn,Yg=_(()=>{"use strict";Dn();Ug=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],Hg="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",Gg="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",Bg="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",Wg="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",Kg="SELECT file_path, specifier, imported_name, local_name FROM file_imports",Vg="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";a(qg,"factRows");rn=a(e=>e==null?null:String(e),"str");a(zg,"assembleFacts")});function Ps(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 Jg,Xr,Xg=_(()=>{"use strict";il();jr();Yg();_c();a(Ps,"toNodeRow");Jg=400,Xr=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Ds(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(ch)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,i){this.db.transaction(()=>{this.deleteFileGraph(t.path);let o=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)o.run(l.nodeKey,l.kind,l.name,l.qualifiedName,l.filePath,l.language,l.startLine,l.endLine,l.startByte,l.endByte,l.signature,l.doc),c.run(l.nodeKey,r.get(l.nodeKey)??l.name);if(i){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let m of i.contains)l.run(m.srcKey,m.dstKey,m.kind);let d=qg(t.path,i),u=this.db.prepare(Hg);for(let m of d.refs)u.run(...m);let p=this.db.prepare(Gg);for(let m of d.imports)p.run(...m);let h=this.db.prepare(Bg);for(let m of d.exports)h.run(...m)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return zg(t,this.db.prepare(Wg).all(),this.db.prepare(Kg).all(),this.db.prepare(Vg).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let i of t)r.run(i.srcKey,i.dstKey,i.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let o of t)i.run(o);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of n)s.run(o.srcKey,o.dstKey,o.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?Ps(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Ps)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Ps)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Ps)}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=uh(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
142
142
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
143
143
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
144
144
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
145
145
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
146
146
|
WHERE nodes_fts MATCH ?
|
|
147
|
-
ORDER BY score LIMIT ?`,o=this.db.prepare(s);return(n?o.all(i,n,r):o.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(
|
|
147
|
+
ORDER BY score LIMIT ?`,o=this.db.prepare(s);return(n?o.all(i,n,r):o.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let o=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(o+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),o+=" LIMIT ?",c.push(i),this.db.prepare(o).all(...c).map(d=>({srcKey:d.src_key,dstKey:d.dst_key,kind:d.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
|
|
148
148
|
(SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
|
|
149
149
|
(SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
|
|
150
150
|
(SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
|
|
151
151
|
FROM nodes n
|
|
152
152
|
WHERE n.kind = 'module'
|
|
153
153
|
ORDER BY imports_in DESC, symbol_count DESC
|
|
154
|
-
LIMIT ?`).all(
|
|
154
|
+
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=Jg)for(let o of n.slice(s,s+Jg))r.run(o),i.run(o);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let s of Ug)this.db.prepare(s).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
155
155
|
node_key, kind, name, qualified_name, file_path, language,
|
|
156
156
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
157
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)
|
|
@@ -161,150 +161,163 @@ ${e.consentDescription}
|
|
|
161
161
|
content_hash = excluded.content_hash,
|
|
162
162
|
mtime_ms = excluded.mtime_ms,
|
|
163
163
|
size = excluded.size,
|
|
164
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as AT}from"node:crypto";function Hn(t){return AT("sha256").update(t,"utf8").digest("hex")}function lg(t){return{node_key_hash:Hn(t.nodeKey),name:t.name,qualified_name:t.qualifiedName,path_hash:Hn(t.filePath),kind:t.kind,language:t.language,start_line:t.startLine,end_line:t.endLine,signature_hash:t.signature?Hn(t.signature):null}}function dg(t){return{src_key_hash:Hn(t.srcKey),dst_key_hash:Hn(t.dstKey),kind:t.kind}}function ug(t,e,n){return{node_key_hash:Hn(t.nodeKey),embedding:Array.from(t.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:e}}var pg=_(()=>{"use strict";a(Hn,"sha256");a(lg,"toCloudNode");a(dg,"toCloudEdge");a(ug,"toCloudEmbedding")});import{randomUUID as RT}from"node:crypto";function $c(t,e){let n=[];for(let r=0;r<t.length;r+=e)n.push(t.slice(r,r+e));return n}function fg(t){if(t===null)return null;let e=Number(t);return Number.isFinite(e)?e:null}function mg(t){return typeof t=="number"&&Number.isFinite(t)?t:0}var Bn,Wn,IT,Fc=_(()=>{"use strict";Nr();pg();Bn=class extends Error{static{a(this,"SyncError")}status;code;constructor(e,n,r){super(e),this.status=n,this.code=r,this.name="SyncError"}},Wn=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(Cn),lastSyncedAt:fg(await this.store.getMeta(za))}}async push(){await this.store.init();let e=(await this.store.getAllNodes()).map(lg),n=(await this.store.getAllEdges()).map(dg),r=await this.store.getMeta(Nn)??In,i=await this.store.getMeta(Cn),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(v=>[v.language,v.count])),c=RT(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},d=0,u=$c(e,this.chunk),p=$c(n,this.chunk*2),h=Math.max(1,u.length+p.length);for(let v of u)await this.post("/api/codebase/push",{...l,nodes:v,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:h});for(let v of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:v,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:h});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let m=e.map(v=>v.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:h,total:h});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(za,String(Date.now())),i&&await this.store.setMeta(wm,i),{nodes:e.length,edges:n.length,pruned:mg(g.nodes_deleted),edgesPruned:mg(g.edges_deleted),embeddings:y,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=>ug(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=$c(o,IT),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(Gi),n=await this.store.getMeta(Ki),r=fg(await this.store.getMeta(Vi));if(!e||!n||!r)throw new Bn("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 Bn(`${n} failed (HTTP ${e.status})${s?`: ${s}`:""}`,e.status,s)}return i}},IT=250;a($c,"chunkArray");a(fg,"numOrNull");a(mg,"numOr0")});var hg={};ae(hg,{CodeIndexSync:()=>Wn,DEFAULT_DB_RELPATH:()=>jc,SyncError:()=>Bn,createCodeIndexSync:()=>CT,createNodeCodeIndex:()=>ks,openSqliteDatabase:()=>bs,probeBuiltinSqlite:()=>Un});import{mkdirSync as NT}from"node:fs";import{posix as vs}from"node:path";function ks(t){let e=t.dbPath??vs.join(t.repoRoot,jc);NT(vs.dirname(e),{recursive:!0}),t.dbPath===void 0&&yr(vs.dirname(e));let n=new Br(e),r=new _s;return new Cr({store:n,parser:r,repoRoot:t.repoRoot,embedder:t.embedder})}function CT(t){let e=t.dbPath??vs.join(t.repoRoot,jc),n=t.projectKey??gf(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 Br(e);return new Wn(r,{endpoint:t.endpoint,apiKey:t.apiKey,projectKey:n,deviceId:t.deviceId,chunkSize:t.chunkSize,onProgress:t.onProgress})}var jc,Uc=_(()=>{"use strict";ca();zh();Xa();cg();Fc();Si();Fc();Lc();jc=".maind/code-index.sqlite";a(ks,"createNodeCodeIndex");a(CT,"createCodeIndexSync")});import{execFileSync as gg}from"node:child_process";import{existsSync as yg,realpathSync as _g}from"node:fs";import{createRequire as OT}from"node:module";import{basename as DT,dirname as MT,isAbsolute as bg,join as PT,relative as wg,resolve as xs,sep as vg}from"node:path";function kg(){let t=Un();if(t.ok)return{ok:!0,backend:"node:sqlite"};try{return OT(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 xg(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 de(t=process.cwd()){try{let e=gg("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 Eg(t,e=de(),n=process.cwd()){let r=bg(t)?[t]:[xs(e,t),xs(n,t)];for(let i of r){let s=MT(i);if(!yg(s))continue;let o;try{o=_g(s)}catch{continue}let c=Tg(o);if(c===null)continue;let l=wg(c,PT(o,DT(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(vg).join("/")}}return null}function Gn(t,e=de(),n=process.cwd()){let r=bg(t)?[t]:[xs(e,t),xs(n,t)];for(let i of r){if(!yg(i))continue;let s;try{s=_g(i)}catch{continue}let o=Tg(s);if(o===null)continue;let c=wg(o,s);if(!c.startsWith(".."))return{repoRoot:o,repoRelDir:c===""?"":c.split(vg).join("/")}}return null}function Tg(t){try{let e=gg("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 Ag(){return ks({repoRoot:de()})}function Rg(t){return ks({repoRoot:t})}var Sg,Jt=_(()=>{"use strict";Uc();a(kg,"probeNativeStore");a(xg,"isNativeStoreUnavailable");Sg="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(de,"resolveRepoRoot");a(Eg,"resolveRepoRootForPath");a(Gn,"resolveRepoRootForDir");a(Tg,"gitToplevelOf");a(Ag,"defaultEngineFactory");a(Rg,"engineForRoot")});import{mkdirSync as Pg,rmdirSync as Lg,statSync as jT}from"node:fs";import{join as $g}from"node:path";import{setTimeout as UT}from"node:timers/promises";function Fg(t){return $g(t,".maind","index-refresh.lock")}function Ts(t,e=Date.now()){let n=Fg(t);try{if(e-jT(n).mtimeMs<HT)return!1;Lg(n)}catch{}try{return Pg(n,{recursive:!1}),!0}catch{return!1}}function Wr(t){try{Lg(Fg(t))}catch{}}async function jg(t,e,n={}){let r=n.now??Date.now,i=n.sleep??(o=>UT(o).then(()=>{})),s=r()+(n.waitMs??3e4);try{Pg($g(t,".maind"),{recursive:!0})}catch{}for(;!Ts(t,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await e()}}finally{Wr(t)}}var HT,Hc=_(()=>{"use strict";HT=30*6e4;a(Fg,"lockPath");a(Ts,"acquireLock");a(Wr,"releaseLock");a(jg,"withIndexLock")});import{execFile as ty}from"node:child_process";import{randomUUID as dA}from"node:crypto";function gA(t){let e=(t.MAIND_SESSION_ID??"").trim().toLowerCase();return qc.test(e)?e:dA()}function zc(t,e){let n=(t.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:e?.auto_announce===!1}function yA(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 _A(t){return await new Promise(e=>{ty("git",["config","--get",`branch.${t}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return e(null);e(bA(r))})})}function bA(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 wA(){return await new Promise(t=>{ty("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 vA(t){if(typeof t!="string")return null;let e=t.trim().slice(0,100);return e.length>0?e:null}function kA(t,e){let n=e,r=(t.MAIND_SESSION_ID??"").trim().toLowerCase(),i=qc.test(r)&&r===e?"env":"random";return{current:a(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:a(()=>!1,"tryUpgrade"),adopt:a(s=>{qc.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:a(()=>null,"activityAtMs")}}var ey,ny,uA,pA,fA,mA,hA,qc,Ns,Yc=_(()=>{"use strict";jn();ey=45e3,ny=3e4,uA=5,pA=120,fA=3e4,mA=15*6e4,hA=1500,qc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(gA,"resolveClientSessionId");a(zc,"autoAnnounceDisabled");a(yA,"autoWorkingPathsEnabled");Ns=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??Pe)();this.projectKey=e.projectKey,this.postToolCall=e.postToolCall,this.now=e.now??Date.now,this.gitBranch=e.gitBranch??wA,this.gitBranchObject=e.gitBranchObject??_A,this.log=e.log??(i=>process.stderr.write(i+`
|
|
165
|
-
`)),this.machineLabel=
|
|
166
|
-
`,{mode:384}),
|
|
167
|
-
`)}function yR(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 _R(t,e,n){return lR.test(t)?{polarity:-1,magnitude:Yn.rework,kind:"rework"}:n&&dR.test(t)?{polarity:-1,magnitude:Yn.correction,kind:"correction"}:uR.test(t)?{polarity:1,magnitude:Yn.acceptance,kind:"acceptance"}:e!==null&&yR(e,t)?{polarity:-1,magnitude:Yn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function bR(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:Ey,behaviour_measured:!0}}async function wR(t,e){for(let n of Ps(t))await new Promise(r=>{let i=Sy({input:xy(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 $s(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Fs))continue;let d=l.name.slice(Fs.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 nl(t,e={}){let n=bR("");if(!t||!cR(t))return n;let r=e.turns??(await qr(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=xy(t,{encoding:"utf-8"}),y=Sy({input:g}),v=a(b=>{let w=b.trim();if(!w)return;let k;try{k=JSON.parse(w)}catch{return}if(n.lines_seen++,!n.session_id){let j=k.sessionId??k.session_id;typeof j=="string"&&j&&(n.session_id=j)}k.type==="ai-title"&&typeof k.aiTitle=="string"&&k.aiTitle&&(n.ai_title=k.aiTitle),typeof k.slug=="string"&&k.slug&&(n.session_slug=k.slug);let S=k.message?.role,R=k.isSidechain===!0;if(S==="assistant")for(let j of $s(k.message?.content)){if(j.type!=="tool_use"||typeof j.name!="string"||!j.name.startsWith(Fs))continue;let ue=j.name.slice(Fs.length);ue&&(n.maind_tool_calls??={},n.maind_tool_calls[ue]=(n.maind_tool_calls[ue]??0)+1)}if(R)return;if(S==="assistant"){let j=$s(k.message?.content),ue=!1;for(let ln of j)ln.type==="tool_use"&&(n.tool_calls++,ue=!0,ln.name==="AskUserQuestion"&&n.agent_questions++);c=ue;return}if(S!=="user")return;let D=$s(k.message?.content),F=gR(D);if(F.includes(pR)){n.interrupts++,i.push({polarity:-1,magnitude:Yn.interrupt,kind:"interrupt"});return}if(D.some(j=>j.type==="tool_result"&&j.is_error===!0&&typeof j.content=="string"&&j.content.includes(fR))){n.tool_denials++,i.push({polarity:-1,magnitude:Yn.denial,kind:"denial"});return}if(D.some(j=>j.type==="tool_result")||!F.trim())return;n.user_turns++,n.user_chars+=F.length;let U=Vr(F);U&&(o=U);let N=_R(F,l,c);l=F,N.kind==="correction"?n.corrections++:N.kind==="rework"?n.reworks++:N.kind==="repeat"?n.repeated_instructions++:N.kind==="acceptance"&&n.acceptances++,N.polarity!==0&&i.push(N),c=!1},"processLine");y.on("line",b=>{try{v(b)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await wR(t,n),n.effort_at_end=o;for(let m of r)m.synthetic||m.model==="<unknown>"||hR(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*mR+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 Fs,Ey,lR,dR,uR,pR,fR,mR,Yn,Ty=_(()=>{"use strict";Ms();Ls();Fs="mcp__maind__",Ey="2026-09-09",lR=/(\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,dR=/(\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,uR=/(\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,pR="[Request interrupted by user",fR="The user doesn't want to proceed with this tool use",mR=.7,Yn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};a(hR,"bumpModel");a($s,"asBlocks");a(gR,"textOf");a(yR,"isRepeat");a(_R,"classifyGenuine");a(bR,"emptyAnalysis");a(wR,"tallySubagentMaindCalls");a(nl,"analyzeSession")});function rl(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 il(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 sl(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 Ay=_(()=>{"use strict";a(rl,"parseIngestResponse");a(il,"describeSliceVerdict");a(sl,"ingestBody")});import{homedir as vR}from"node:os";import{join as kR}from"node:path";var xR,ol=_(()=>{"use strict";xR=kR(vR(),".codex","sessions")});var Ry=_(()=>{"use strict";ol()});import{isAbsolute as ll,relative as ER,resolve as Iy,sep as dl}from"node:path";function Ny(t){return t.trim().replace(/\[[^\]]*\]$/,"")}function js(t){if(typeof t!="string"||!t)return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function ul(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=js(d.from);typeof d.object_id!="string"||!al.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:js(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=js(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:js(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"||!al.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"&&al.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 Oy(t,e){if(!ll(t))return null;let n=ER(Iy(e),Iy(t));return!n||n==="."||n.startsWith("..")||ll(n)?null:dl==="/"?n:n.split(dl).join("/")}function TR(t,e){return e===""||t===e||t.startsWith(e+"/")}function pl(t,e){return t===e||t===""||e===""||t.startsWith(e+"/")||e.startsWith(t+"/")}function Dy(t){return[...t].sort((e,n)=>n.path_prefix.length-e.path_prefix.length||e.object_id.localeCompare(n.object_id))}function fl(t,e){for(let n of Dy(e))if(TR(t,n.path_prefix))return n.object_id;return null}function AR(t,e){for(let n of Dy(e))if(pl(t,n.path_prefix))return n.object_id;return null}function cl(t,e){return t>=e.from&&(e.to===null||t<e.to)}function My(t,e,n,r){let i=t.ts,s=r?.anchors??[],o=e.map(c=>fl(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>cl(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=>cl(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=>cl(i,u));if(d.length){let u=e[0]??n?.rel??null,p=(u===null?d:d.filter(h=>pl(h.path_prefix,u))).sort((h,m)=>m.path_prefix.length-h.path_prefix.length);for(let h of p){let m=AR(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 ml(t,e,n){let r=e?.anchors??[],i=a(g=>{if(!n.repoRoot)return[];let y=[];for(let v of g.edited_paths){let b=Oy(v,n.repoRoot);b!==null&&!y.includes(b)&&y.push(b)}return y},"relOf"),s=a(g=>{for(let y of g){let v=fl(y,r);if(v)return{object_id:v,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===Qt?-1:y===Qt?1:0),l=[],d=a(g=>{let y=null;for(let v of l){if(v.ts>g&&g>0)break;y=v.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let v=y.map((w,k)=>({t:w,i:k,rels:i(w)})).sort((w,k)=>w.t.ts-k.t.ts||w.i-k.i),b=null;for(let w of v){let k=s(w.rels);if(k){b=k;break}}!b&&g!==Qt&&v.length&&(b=d(v[0].t.ts));for(let w of v){let k=s(w.rels);k&&(b=k),g===Qt&&l.push({ts:w.t.ts,seg:b});let S=w.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let D=My(S,w.rels,b,e),F=S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens>Cy?"above_200k":"standard",H=Ny(S.model),U=`${D.object_id??""}|${D.source}|${H}|${F}`,N=u.get(U);N||(N={object_id:D.object_id,attribution_source:D.source,model:H,context_tier:F,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},u.set(U,N)),N.input_tokens+=S.input_tokens,N.output_tokens+=S.output_tokens,N.cache_read_tokens+=S.cache_read_tokens,N.cache_creation_tokens+=S.cache_creation_tokens,N.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,N.turns+=1,S.ts>0&&((N.firstMs===0||S.ts<N.firstMs)&&(N.firstMs=S.ts),S.ts>N.lastMs&&(N.lastMs=S.ts))}}let p=n.nowMs??Date.now(),h=[];for(let g of u.values()){let{firstMs:y,lastMs:v,...b}=g;b.first_ts=new Date(y>0?y:p).toISOString(),b.last_ts=new Date(v>0?v:p).toISOString(),h.push(b)}let m={lease:0,binding:1,claim:2,path:3,none:4};return h.sort((g,y)=>m[g.attribution_source]-m[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),h}function hl(t,e){let n=new Map;for(let s of t){let o=new Set;for(let c of s.edited_paths){if(!ll(c))continue;let l=e(RR(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 RR(t){let e=t.split(dl).join("/"),n=e.lastIndexOf("/");return n<=0?e:e.slice(0,n)}var Cy,al,Py=_(()=>{"use strict";Ls();a(Ny,"normalizeModelId");Cy=2e5,al=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(js,"msOf");a(ul,"parseCostContext");a(Oy,"toRepoRelative");a(TR,"underPrefix");a(pl,"prefixesOverlap");a(Dy,"sortedAnchors");a(fl,"anchorFor");a(AR,"bestAnchorOverlapping");a(cl,"inWindow");a(My,"assignTurn");a(ml,"sliceSession");a(hl,"dominantCheckoutRoot");a(RR,"dirOf")});import{createReadStream as IR,existsSync as NR}from"node:fs";import{createInterface as CR}from"node:readline";function Ly(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(e=>typeof e=="object"&&e!==null):[]}function MR(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
168
|
-
`)}function
|
|
169
|
-
`)}return""}async function yl(t,e={}){if(!t||!$R(t))return{events:[],bytesRead:e.start??0,effortAtEnd:e.initialEffort??null,modesAtEnd:e.initialModes?{...e.initialModes}:Zc(),seenMessagesAtEnd:new Set(e.initialSeenMessages??[])};let n=[],r=new Set(e.initialSeenMessages??[]),i=e.initialEffort??null,s=e.initialModes?{...e.initialModes}:Zc(),o=e.start??0;return await new Promise(c=>{let l=LR(t,{encoding:"utf-8",start:e.start??0}),d=FR({input:l});d.on("line",p=>{o+=Buffer.byteLength(p,"utf-8")+1;let h=p.trim();if(!h)return;let m;try{m=JSON.parse(h)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),v=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=jR[m.attachment.type];b&&(s[UR(b.mode)]=b.active,n.push({kind:"mode",session_id:g,ts:y,mode:b.mode,active:b.active}));return}if(v==="user"){let b=HR(m.message?.content),w=Vr(b);w&&(i=w);let k={session_id:g,ts:y,text:b,effort_directive:w};n.push({kind:"user",...k});return}if(v==="assistant"){let b=m.message?.usage,w=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,k=typeof m.requestId=="string"&&m.requestId?m.requestId:null,S=w??k,R=S!==null&&r.has(S);S!==null&&!R&&r.add(S);let D={session_id:g,ts:y,model:m.message?.model??null,input_tokens:R?0:Us(b?.input_tokens),output_tokens:R?0:Us(b?.output_tokens),cache_read_input_tokens:R?0:Us(b?.cache_read_input_tokens),cache_creation_input_tokens:R?0:Us(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...s.ultracode?{ultracode:!0}:{},...s.planMode?{planMode:!0}:{},...s.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...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 jR,Hy=_(()=>{"use strict";Ms();Qc();jR={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(UR,"modeFlagKey");a(Us,"num");a(HR,"extractUserText");a(yl,"streamTranscript")});var By=_(()=>{"use strict"});import{homedir as BR}from"node:os";import{join as WR}from"node:path";function bl(t){return t.replace(/[/.]/g,"-")}var GR,_l,Wy=_(()=>{"use strict";GR=BR(),_l=WR(GR,".claude","projects");a(bl,"projectPathFromCwd")});var Jn=_(()=>{"use strict";Qc();_y();by();Ty();Ay();Ls();ol();Ry();Py();Uy();Hy();Ms();By();Wy()});function wl(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 eI(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 Xn(t,e){let n=`npm i -g ${zr}@${t}`;return e?`nvm use ${e} && ${n}`:n}function Bs(t){let e=[],n=[t.runningVersion,...t.nodeTrees.map(u=>u.bridgeVersion).filter(u=>u!==null)],r=t.latestVersion??n.sort(wl).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:Xn(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(g=>wl(g.bridgeVersion,r)<0))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:Xn(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=eI(u);if(p===null)continue;if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(g=>g.includes(zr))){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:`${Xn(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 ${zr}@${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 ${Xn(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:Xn(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 ${zr} 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(wl(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?Xn(t.latestVersion,m):`npx -y ${zr}@${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||!Vy.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"}):QR.test(l)?e.push({check:"credentials",level:t.deviceId!==null&&Vy.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=qt(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 qy(t){let e=t.filter(i=>i.level==="error"&&vl.includes(i.check)).sort((i,s)=>vl.indexOf(i.check)-vl.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 zy(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(`
|
|
164
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as FA}from"node:crypto";function Xn(e){return FA("sha256").update(e,"utf8").digest("hex")}function Zg(e){return{node_key_hash:Xn(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Xn(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Xn(e.signature):null}}function Qg(e){return{src_key_hash:Xn(e.srcKey),dst_key_hash:Xn(e.dstKey),kind:e.kind}}function ey(e,t,n){return{node_key_hash:Xn(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var ty=_(()=>{"use strict";a(Xn,"sha256");a(Zg,"toCloudNode");a(Qg,"toCloudEdge");a(ey,"toCloudEmbedding")});import{randomUUID as jA}from"node:crypto";function sl(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ny(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function ry(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Zn,Qn,UA,ol=_(()=>{"use strict";jr();ty();Zn=class extends Error{static{a(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Qn=class{static{a(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(Hn),lastSyncedAt:ny(await this.store.getMeta(gc))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Zg),n=(await this.store.getAllEdges()).map(Qg),r=await this.store.getMeta(Un)??jn,i=await this.store.getMeta(Hn),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(v=>[v.language,v.count])),c=jA(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},d=0,u=sl(t,this.chunk),p=sl(n,this.chunk*2),h=Math.max(1,u.length+p.length);for(let v of u)await this.post("/api/codebase/push",{...l,nodes:v,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:h});for(let v of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:v,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:h});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let m=t.map(v=>v.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:h,total:h});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(gc,String(Date.now())),i&&await this.store.setMeta(lh,i),{nodes:t.length,edges:n.length,pruned:ry(g.nodes_deleted),edgesPruned:ry(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},o=(await this.store.allEmbeddings()).map(d=>ey(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&s[d.node_key_hash]!==d.content_hash);if(o.length===0)return 0;let c=sl(o,UA),l=0;for(let d of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:d}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return o.length}async embedMeta(){let t=await this.store.getMeta(ss),n=await this.store.getMeta(os),r=ny(await this.store.getMeta(as));if(!t||!n||!r)throw new Zn("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 Zn(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},UA=250;a(sl,"chunkArray");a(ny,"numOrNull");a(ry,"numOr0")});var iy={};te(iy,{CodeIndexSync:()=>Qn,DEFAULT_DB_RELPATH:()=>al,SyncError:()=>Zn,createCodeIndexSync:()=>GA,createNodeCodeIndex:()=>Ls,openSqliteDatabase:()=>Ds,probeBuiltinSqlite:()=>Jn});import{mkdirSync as HA}from"node:fs";import{posix as Ms}from"node:path";function Ls(e){let t=e.dbPath??Ms.join(e.repoRoot,al);HA(Ms.dirname(t),{recursive:!0}),e.dbPath===void 0&&Tr(Ms.dirname(t));let n=new Xr(t),r=new Os;return new Ur({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function GA(e){let t=e.dbPath??Ms.join(e.repoRoot,al),n=e.projectKey??sm(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 Xr(t);return new Qn(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var al,cl=_(()=>{"use strict";Na();$g();bc();Xg();ol();ji();ol();il();al=".maind/code-index.sqlite";a(Ls,"createNodeCodeIndex");a(GA,"createCodeIndexSync")});import{execFileSync as sy}from"node:child_process";import{existsSync as oy,realpathSync as ay}from"node:fs";import{createRequire as BA}from"node:module";import{basename as WA,dirname as KA,isAbsolute as cy,join as VA,relative as ly,resolve as $s,sep as dy}from"node:path";function uy(){let e=Jn();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return BA(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 py(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 pe(e=process.cwd()){try{let t=sy("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 my(e,t=pe(),n=process.cwd()){let r=cy(e)?[e]:[$s(t,e),$s(n,e)];for(let i of r){let s=KA(i);if(!oy(s))continue;let o;try{o=ay(s)}catch{continue}let c=hy(o);if(c===null)continue;let l=ly(c,VA(o,WA(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(dy).join("/")}}return null}function er(e,t=pe(),n=process.cwd()){let r=cy(e)?[e]:[$s(t,e),$s(n,e)];for(let i of r){if(!oy(i))continue;let s;try{s=ay(i)}catch{continue}let o=hy(s);if(o===null)continue;let c=ly(o,s);if(!c.startsWith(".."))return{repoRoot:o,repoRelDir:c===""?"":c.split(dy).join("/")}}return null}function hy(e){try{let t=sy("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 gy(){return Ls({repoRoot:pe()})}function yy(e){return Ls({repoRoot:e})}var fy,sn=_(()=>{"use strict";cl();a(uy,"probeNativeStore");a(py,"isNativeStoreUnavailable");fy="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(pe,"resolveRepoRoot");a(my,"resolveRepoRootForPath");a(er,"resolveRepoRootForDir");a(hy,"gitToplevelOf");a(gy,"defaultEngineFactory");a(yy,"engineForRoot")});import{mkdirSync as Sy,rmdirSync as Ey,statSync as JA}from"node:fs";import{join as Ty}from"node:path";import{setTimeout as XA}from"node:timers/promises";function Ay(e){return Ty(e,".maind","index-refresh.lock")}function Us(e,t=Date.now()){let n=Ay(e);try{if(t-JA(n).mtimeMs<ZA)return!1;Ey(n)}catch{}try{return Sy(n,{recursive:!1}),!0}catch{return!1}}function Zr(e){try{Ey(Ay(e))}catch{}}async function Ry(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(o=>XA(o).then(()=>{})),s=r()+(n.waitMs??3e4);try{Sy(Ty(e,".maind"),{recursive:!0})}catch{}for(;!Us(e,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Zr(e)}}var ZA,ll=_(()=>{"use strict";ZA=30*6e4;a(Ay,"lockPath");a(Us,"acquireLock");a(Zr,"releaseLock");a(Ry,"withIndexLock")});import{execFile as Wy}from"node:child_process";import{randomUUID as vR}from"node:crypto";function AR(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return hl.test(t)?t:vR()}function gl(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function RR(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 IR(e){return await new Promise(t=>{Wy("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(NR(r))})})}function NR(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 CR(){return await new Promise(e=>{Wy("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 OR(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function DR(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=hl.test(r)&&r===t?"env":"random";return{current:a(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:a(()=>!1,"tryUpgrade"),adopt:a(s=>{hl.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:a(()=>null,"activityAtMs")}}var By,Ky,kR,xR,SR,ER,TR,hl,Ws,yl=_(()=>{"use strict";Yn();By=45e3,Ky=3e4,kR=5,xR=120,SR=3e4,ER=15*6e4,TR=1500,hl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(AR,"resolveClientSessionId");a(gl,"autoAnnounceDisabled");a(RR,"autoWorkingPathsEnabled");Ws=class{static{a(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??$e)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??CR,this.gitBranchObject=t.gitBranchObject??IR,this.log=t.log??(i=>process.stderr.write(i+`
|
|
165
|
+
`)),this.machineLabel=OR(r?.machine_label),this.enabled=this.projectKey!==null&&!gl(n,r),this.workingPathsEnabled=RR(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??DR(n,AR(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<By||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<By||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<kR||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,TR).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(SR*2**(this.consecutiveFailures-1),ER);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let s=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${s} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:xR,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let s=await this.gitBranch();if(s&&(r.branch=s),this.lastBranch=s,s)try{let o=await this.gitBranchObject(s);o!==null&&o!==this.lastSentObjectId&&(r.object_ids=[o],this.lastSentObjectId=o)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let o=await this.sessionMeta();o?.model&&(r.model=o.model),o?.title&&(r.title=o.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let o=await this.deriveWorkingPaths();o&&o.length>0&&(r.working_paths=o)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let s=i;if(s.ok===!0&&typeof s.session_id=="string")try{this.identity.adopt(s.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let s={sessionId:this.sessionId,branch:this.lastBranch},o=typeof i=="object"?i:null;if(o!==null&&o.ok===!0)this.snapshot.write(i,s);else if(this.snapshot.markFailed){let c=o!==null&&typeof o.error=="string"?o.error:"announce_failed";this.snapshot.markFailed(c,s)}}}catch{}}};a(IR,"defaultGitBranchObject");a(NR,"normalizeObjectId");a(CR,"defaultGitBranch");a(OR,"normalizeMachineLabel");a(DR,"staticIdentity")});import{mkdirSync as Vy,readdirSync as Jy,readFileSync as PR,renameSync as qy,statSync as MR,unlinkSync as _l,writeFileSync as zy}from"node:fs";import{homedir as LR}from"node:os";import{join as tr}from"node:path";function Xy(){return tr(LR(),".maind","presence")}function Zy(e,t){return tr(e,t)}function Qy(e){let t=e.baseDir??Xy(),n=Zy(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,s=e.cwd??process.cwd(),o=e.now??Date.now,c=null,l=a(d=>{if(c!==null&&c!==d)try{_l(c)}catch{}c=d},"replaceOwn");return{write(d,u){try{if(typeof d!="object"||d===null)return;let p=d;if(p.ok!==!0)return;let h={v:1,written_at:new Date(o()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[]};Vy(n,{recursive:!0,mode:448});let m=tr(n,`${u.sessionId}.json`),g=`${m}.tmp-${r}`;zy(g,JSON.stringify(h),{mode:384}),qy(g,m),l(m),Yy(n,o(),m)}catch{}},endSession(){try{c&&_l(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(o()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};Vy(n,{recursive:!0,mode:448});let h=tr(n,`${u.sessionId}.json`),m=`${h}.tmp-${r}`;zy(m,JSON.stringify(p),{mode:384}),qy(m,h),l(h),Yy(n,o(),h)}catch{}}}}function Yy(e,t,n){try{for(let r of Jy(e)){if(!r.endsWith(".json"))continue;let i=tr(e,r);if(i!==n)try{t-MR(i).mtimeMs>$R&&_l(i)}catch{}}}catch{}}function nr(e,t=Xy()){try{let n=Zy(t,e),r=[];for(let i of Jy(n))if(i.endsWith(".json"))try{let s=JSON.parse(PR(tr(n,i),"utf8")),o=FR(s);o&&r.push(o)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function FR(e){if(typeof e!="object"||e===null)return null;let t=e;return t.v!==1||typeof t.written_at!="string"||typeof t.project_key!="string"||typeof t.own_session_id!="string"||typeof t.own_pid!="number"||typeof t.own_ppid!="number"||typeof t.cwd!="string"?null:{v:1,written_at:t.written_at,project_key:t.project_key,own_session_id:t.own_session_id,own_pid:t.own_pid,own_ppid:t.own_ppid,cwd:t.cwd,branch:typeof t.branch=="string"?t.branch:null,peers:Array.isArray(t.peers)?t.peers:[],conflicts:Array.isArray(t.conflicts)?t.conflicts:[],...typeof t.announce_error=="string"?{announce_error:t.announce_error}:{}}}var $R,Ks=_(()=>{"use strict";$R=120*6e4;a(Xy,"presenceSnapshotBaseDir");a(Zy,"projectDir");a(Qy,"createSnapshotStore");a(Yy,"pruneStale");a(nr,"readSnapshots");a(FR,"parseSnapshot")});import{execFileSync as jR}from"node:child_process";import{createHash as UR,randomUUID as HR}from"node:crypto";import{existsSync as GR,mkdirSync as BR,readdirSync as WR,readFileSync as t_,renameSync as KR,statSync as bl,unlinkSync as n_,writeFileSync as VR}from"node:fs";import{homedir as qR}from"node:os";import{basename as zR,join as xt}from"node:path";function rr(e){return xt(e??xt(qR(),".maind","presence"),"identity")}function ei(e,t){if(e){let n=zR(e).replace(/\.jsonl$/i,"");if(Qr.test(n))return n.toLowerCase()}return t&&Qr.test(t)?t.toLowerCase():null}function r_(e){let t=e.nowMs??Date.now();BR(e.dir,{recursive:!0,mode:448});let n=xt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(t_(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=e.transcriptPath??i.transcript_path,o=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...s?{transcript_path:s}:{},...o?{model:o}:{}};VR(r,JSON.stringify(c,null,2)+`
|
|
166
|
+
`,{mode:384}),KR(r,n),QR(e.dir,t)}function i_(e,t,n,r=Date.now()){try{let i=bl(xt(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function s_(e,t){try{n_(xt(e,`${t}.json`))}catch{}}function QR(e,t){try{for(let n of WR(e))if(n.endsWith(".json"))try{let r=bl(xt(e,n));t-r.mtimeMs>JR&&n_(xt(e,n))}catch{}}catch{}}function eI(e){return o_(e)?.file??null}function o_(e){let t=xt(e.dir,`${e.agentPid}.json`);try{if(!GR(t))return null;let n=bl(t);if(n.mtimeMs<e.bridgeStartMs-XR)return null;let r=JSON.parse(t_(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Qr.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!tI(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function e_(e){return e.replace(/\/+$/,"")}function tI(e,t){let n=e_(e),r=e_(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function nI(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=UR("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=i.toString("hex");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function rI(e){if(process.platform==="win32")return null;try{let t=jR("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function iI(){try{return X()}catch{return null}}var Qr,YR,JR,XR,ZR,Vs,qs=_(()=>{"use strict";se();Qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,YR=8,JR=48*60*6e4,XR=6e4,ZR="9f3c72da-2f10-4b8f-9c31-ad291c0de291";a(rr,"identityDirPath");a(ei,"transcriptStemOf");a(r_,"writeAgentIdentityFile");a(i_,"identityFileStale");a(s_,"deleteAgentIdentityFile");a(QR,"pruneIdentityDir");a(eI,"readAgentIdentityFile");a(o_,"readAgentIdentityEntry");a(e_,"normDir");a(tI,"sameSessionTree");a(nI,"uuidV5");a(rI,"processStartTime");Vs=class{static{a(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];stem=null;constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??rr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Qr.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.stem=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??iI)(),s=(t.ppidStart??rI)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=nI(`${i}|${this.agentPid}|${s}|${t.projectKey}`,ZR),this.source="derived";return}this.id=HR(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){return this.resync()!=="unchanged"}resync(){let t=this.readStem();if(t===null)return"unchanged";if(this.source==="client_native")return t===this.stem?"unchanged":(this.id=t,this.stem=t,this.aliases=this.envId!==null&&this.envId!==t?[this.envId]:[],"switched");if(t===this.id)return"unchanged";let n=this.id;return this.id=t,this.stem=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),"upgraded"}adopt(t){let n=t.trim().toLowerCase();if(!Qr.test(n)||n===this.id)return;let r=this.id;this.id=n,!(this.source==="client_native"&&r===this.stem)&&this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>YR&&this.aliases.shift())}activityAtMs(){return o_({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=this.sideChannel();return t===null?null:t.transcript_stem.toLowerCase()}sideChannel(){return eI({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};a(iI,"defaultDeviceId")});function wl(){return{ultracode:!1,planMode:!1,autoMode:!1}}var vl=_(()=>{"use strict";a(wl,"newModeState")});import{createReadStream as sI,existsSync as oI}from"node:fs";import{stat as aI}from"node:fs/promises";import{createInterface as cI}from"node:readline";async function kl(e){if(!e||!oI(e))return null;let t;try{t=await aI(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(o=>{let c=sI(e,{encoding:"utf-8"}),l=cI({input:c});l.on("line",d=>{let u=d.trim();if(u){s++;try{let p=JSON.parse(u),h=p.message?.usage;if(!h)return;let m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=m??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof h.input_tokens=="number"&&(r+=h.input_tokens),typeof h.output_tokens=="number"&&(i+=h.output_tokens)}catch{}}}),l.on("close",()=>{o({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:s,last_modified_ms:t.mtimeMs})}),l.on("error",()=>o(null)),c.on("error",()=>o(null))})}var a_=_(()=>{"use strict";a(kl,"summariseTranscript")});var c_=_(()=>{"use strict"});function ti(e){if(!e)return null;let t=null;for(let n of e.matchAll(dI)){let r=n[1].toLowerCase();lI.has(r)&&(t=r)}return t}var lI,dI,zs=_(()=>{"use strict";lI=new Set(["low","medium","high","xhigh","max"]),dI=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;a(ti,"detectEffortLevel")});import{createReadStream as uI,existsSync as pI,readdirSync as fI}from"node:fs";import{basename as u_,dirname as mI,join as l_}from"node:path";import{createInterface as hI}from"node:readline";function ir(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function _I(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=yI[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&t.push(s)}return t}function Ys(e){let t=u_(e).replace(/\.jsonl$/,""),n=l_(mI(e),t,"subagents"),r;try{r=fI(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>l_(n,i))}async function d_(e,t,n,r,i){pI(e)&&await new Promise(s=>{let o=uI(e,{encoding:"utf-8"}),c=hI({input:o}),l=0;c.on("line",d=>{l++;let u=d.trim();if(!u)return;let p;try{p=JSON.parse(u)}catch{return}if(p.message?.role!=="assistant")return;let h=typeof p.message.id=="string"&&p.message.id?p.message.id:null,m=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=h??m??`${e}#${l}`,y=_I(p.message.content),v=r.get(g);if(v){for(let R of y)v.edited_paths.includes(R)||v.edited_paths.push(R);return}if(n.has(g))return;n.add(g);let w=p.message.usage??{},b=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,k=typeof p.message.model=="string"&&p.message.model?p.message.model:"",S={ts:Number.isFinite(b)?b:0,model:k||"<unknown>",synthetic:k===gI,input_tokens:ir(w.input_tokens),output_tokens:ir(w.output_tokens),cache_read_tokens:ir(w.cache_read_input_tokens),cache_creation_tokens:ir(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(ir(w.cache_creation?.ephemeral_1h_input_tokens),ir(w.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:y,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(g,S),i.push(S)}),c.on("close",()=>s()),c.on("error",()=>s()),o.on("error",()=>s())})}function xl(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function ni(e){let t=new Set,n=new Map,r=[],i=e?Ys(e):[];if(!e)return{turns:r,subagent_files:i};let s=[];await d_(e,cn,t,n,s),xl(s),r.push(...s);for(let o of i){let c=[],l=u_(o).replace(/\.jsonl$/,"");await d_(o,l,t,n,c),xl(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var cn,gI,yI,Js=_(()=>{"use strict";cn="main",gI="<synthetic>",yI={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};a(ir,"num");a(_I,"editedPathsOf");a(Ys,"subagentFilesOf");a(d_,"readStream");a(xl,"fillTimestamps");a(ni,"collectTurns")});import{createReadStream as p_,existsSync as bI}from"node:fs";import{createInterface as f_}from"node:readline";function TI(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,o=e.get(s);if(!o){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}o.turns++,o.output_tokens+=r,i>0&&((o.first_ts===0||i<o.first_ts)&&(o.first_ts=i),i>o.last_ts&&(o.last_ts=i))}function Xs(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function AI(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
167
|
+
`)}function RI(e,t){let n=a(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,o]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)o.has(l)&&c++;return c/s.size>=.8}function II(e,t,n){return wI.test(e)?{polarity:-1,magnitude:sr.rework,kind:"rework"}:n&&vI.test(e)?{polarity:-1,magnitude:sr.correction,kind:"correction"}:kI.test(e)?{polarity:1,magnitude:sr.acceptance,kind:"acceptance"}:t!==null&&RI(t,e)?{polarity:-1,magnitude:sr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function NI(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:m_,behaviour_measured:!0}}async function CI(e,t){for(let n of Ys(e))await new Promise(r=>{let i=f_({input:p_(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(Zs))continue;let d=l.name.slice(Zs.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Sl(e,t={}){let n=NI("");if(!e||!bI(e))return n;let r=t.turns??(await ni(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],s=new Map,o=null,c=!1,l=null;await new Promise(m=>{let g=p_(e,{encoding:"utf-8"}),y=f_({input:g}),v=a(w=>{let b=w.trim();if(!b)return;let k;try{k=JSON.parse(b)}catch{return}if(n.lines_seen++,!n.session_id){let j=k.sessionId??k.session_id;typeof j=="string"&&j&&(n.session_id=j)}k.type==="ai-title"&&typeof k.aiTitle=="string"&&k.aiTitle&&(n.ai_title=k.aiTitle),typeof k.slug=="string"&&k.slug&&(n.session_slug=k.slug);let S=k.message?.role,R=k.isSidechain===!0;if(S==="assistant")for(let j of Xs(k.message?.content)){if(j.type!=="tool_use"||typeof j.name!="string"||!j.name.startsWith(Zs))continue;let me=j.name.slice(Zs.length);me&&(n.maind_tool_calls??={},n.maind_tool_calls[me]=(n.maind_tool_calls[me]??0)+1)}if(R)return;if(S==="assistant"){let j=Xs(k.message?.content),me=!1;for(let bn of j)bn.type==="tool_use"&&(n.tool_calls++,me=!0,bn.name==="AskUserQuestion"&&n.agent_questions++);c=me;return}if(S!=="user")return;let D=Xs(k.message?.content),F=AI(D);if(F.includes(xI)){n.interrupts++,i.push({polarity:-1,magnitude:sr.interrupt,kind:"interrupt"});return}if(D.some(j=>j.type==="tool_result"&&j.is_error===!0&&typeof j.content=="string"&&j.content.includes(SI))){n.tool_denials++,i.push({polarity:-1,magnitude:sr.denial,kind:"denial"});return}if(D.some(j=>j.type==="tool_result")||!F.trim())return;n.user_turns++,n.user_chars+=F.length;let U=ti(F);U&&(o=U);let N=II(F,l,c);l=F,N.kind==="correction"?n.corrections++:N.kind==="rework"?n.reworks++:N.kind==="repeat"?n.repeated_instructions++:N.kind==="acceptance"&&n.acceptances++,N.polarity!==0&&i.push(N),c=!1},"processLine");y.on("line",w=>{try{v(w)}catch{}}),y.on("close",()=>m()),y.on("error",()=>m()),g.on("error",()=>m())}),await CI(e,n),n.effort_at_end=o;for(let m of r)m.synthetic||m.model==="<unknown>"||TI(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*EI+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 Zs,m_,wI,vI,kI,xI,SI,EI,sr,h_=_(()=>{"use strict";zs();Js();Zs="mcp__maind__",m_="2026-10-01",wI=/(\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,vI=/(\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,kI=/(\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,xI="[Request interrupted by user",SI="The user doesn't want to proceed with this tool use",EI=.7,sr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};a(TI,"bumpModel");a(Xs,"asBlocks");a(AI,"textOf");a(RI,"isRepeat");a(II,"classifyGenuine");a(NI,"emptyAnalysis");a(CI,"tallySubagentMaindCalls");a(Sl,"analyzeSession")});function El(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 Tl(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 Al(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 g_=_(()=>{"use strict";a(El,"parseIngestResponse");a(Tl,"describeSliceVerdict");a(Al,"ingestBody")});import{homedir as OI}from"node:os";import{join as DI}from"node:path";var PI,Rl=_(()=>{"use strict";PI=DI(OI(),".codex","sessions")});var y_=_(()=>{"use strict";Rl()});import{isAbsolute as Cl,relative as LI,resolve as __,sep as Ol}from"node:path";function b_(e){return e>eo[1]?"above_272k":e>eo[0]?"band_200k_272k":"standard"}function w_(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Qs(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Dl(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=a(o=>{if(!Array.isArray(o))return[];let c=[];for(let l of o){if(!l||typeof l!="object")continue;let d=l,u=Qs(d.from);typeof d.object_id!="string"||!Il.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:Qs(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=Qs(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:Qs(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"||!Il.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"&&Il.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 v_(e,t){if(!Cl(e))return null;let n=LI(__(t),__(e));return!n||n==="."||n.startsWith("..")||Cl(n)?null:Ol==="/"?n:n.split(Ol).join("/")}function FI(e,t){return t===""||e===t||e.startsWith(t+"/")}function Pl(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function k_(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Ml(e,t){for(let n of k_(t))if(FI(e,n.path_prefix))return n.object_id;return null}function jI(e,t){for(let n of k_(t))if(Pl(e,n.path_prefix))return n.object_id;return null}function Nl(e,t){return e>=t.from&&(t.to===null||e<t.to)}function x_(e,t,n,r){let i=e.ts,s=r?.anchors??[],o=t.map(c=>Ml(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Nl(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=>Nl(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=>Nl(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(h=>Pl(h.path_prefix,u))).sort((h,m)=>m.path_prefix.length-h.path_prefix.length);for(let h of p){let m=jI(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 Ll(e,t,n){let r=t?.anchors??[],i=a(g=>{if(!n.repoRoot)return[];let y=[];for(let v of g.edited_paths){let w=v_(v,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),s=a(g=>{for(let y of g){let v=Ml(y,r);if(v)return{object_id:v,rel:y}}return null},"firstAnchoredEdit"),o=new Map;for(let g of e){let y=o.get(g.stream)??[];y.push(g),o.set(g.stream,y)}let c=[...o.entries()].sort(([g],[y])=>g===cn?-1:y===cn?1:0),l=[],d=a(g=>{let y=null;for(let v of l){if(v.ts>g&&g>0)break;y=v.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let v=y.map((b,k)=>({t:b,i:k,rels:i(b)})).sort((b,k)=>b.t.ts-k.t.ts||b.i-k.i),w=null;for(let b of v){let k=s(b.rels);if(k){w=k;break}}!w&&g!==cn&&v.length&&(w=d(v[0].t.ts));for(let b of v){let k=s(b.rels);k&&(w=k),g===cn&&l.push({ts:b.t.ts,seg:w});let S=b.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let D=x_(S,b.rels,w,t),F=b_(S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens),H=w_(S.model),U=`${D.object_id??""}|${D.source}|${H}|${F}`,N=u.get(U);N||(N={object_id:D.object_id,attribution_source:D.source,model:H,context_tier:F,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},u.set(U,N)),N.input_tokens+=S.input_tokens,N.output_tokens+=S.output_tokens,N.cache_read_tokens+=S.cache_read_tokens,N.cache_creation_tokens+=S.cache_creation_tokens,N.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,N.turns+=1,S.ts>0&&((N.firstMs===0||S.ts<N.firstMs)&&(N.firstMs=S.ts),S.ts>N.lastMs&&(N.lastMs=S.ts))}}let p=n.nowMs??Date.now(),h=[];for(let g of u.values()){let{firstMs:y,lastMs:v,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(v>0?v:p).toISOString(),h.push(w)}let m={lease:0,binding:1,claim:2,path:3,none:4};return h.sort((g,y)=>m[g.attribution_source]-m[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),h}function $l(e,t){let n=new Map;for(let s of e){let o=new Set;for(let c of s.edited_paths){if(!Cl(c))continue;let l=t(UI(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 UI(e){let t=e.split(Ol).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var eo,$I,Il,S_=_(()=>{"use strict";Js();eo=[2e5,272e3];a(b_,"contextTierOf");a(w_,"normalizeModelId");$I=eo[0],Il=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Qs,"msOf");a(Dl,"parseCostContext");a(v_,"toRepoRelative");a(FI,"underPrefix");a(Pl,"prefixesOverlap");a(k_,"sortedAnchors");a(Ml,"anchorFor");a(jI,"bestAnchorOverlapping");a(Nl,"inWindow");a(x_,"assignTurn");a(Ll,"sliceSession");a($l,"dominantCheckoutRoot");a(UI,"dirOf")});import{createReadStream as HI,existsSync as GI}from"node:fs";import{createInterface as BI}from"node:readline";function E_(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function VI(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
168
|
+
`)}function R_(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function qI(e){let t=e.message?.role;if(t==="assistant")return{holder:E_(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=E_(e.message?.content),r=VI(n);return r.includes(WI)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(KI))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Fl(e){let t=R_("");if(!e||!GI(e))return t;let n=null,r=0,i=0,s=null,o="human",c=[];return await new Promise(l=>{let d=HI(e,{encoding:"utf-8"}),u=BI({input:d}),p=a(h=>{let m=h.trim();if(!m)return;let g;try{g=JSON.parse(m)}catch{return}if(!t.session_id){let w=g.sessionId??g.session_id;typeof w=="string"&&w&&(t.session_id=w)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||s!==null&&y<s)return;let v=qI(g);if(v!==null){if(t.event_count++,v.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let w=y-s;o==="agent"?i+=w:w>=T_*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(w/1e3),c.length<A_&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(w/1e3)}))}s=y,o=v.holder}},"processLine");u.on("line",h=>{try{p(h)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var WI,KI,T_,A_,I_=_(()=>{"use strict";WI="[Request interrupted by user",KI="The user doesn't want to proceed with this tool use",T_=60,A_=200;a(E_,"asBlocks");a(VI,"textOf");a(R_,"emptySpan");a(qI,"classify");a(Fl,"analyzeSpan")});import{createReadStream as zI,existsSync as YI}from"node:fs";import{createInterface as JI}from"node:readline";function ZI(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function to(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function QI(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
|
|
169
|
+
`)}return""}async function jl(e,t={}){if(!e||!YI(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:wl(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:wl(),o=t.start??0;return await new Promise(c=>{let l=zI(e,{encoding:"utf-8",start:t.start??0}),d=JI({input:l});d.on("line",p=>{o+=Buffer.byteLength(p,"utf-8")+1;let h=p.trim();if(!h)return;let m;try{m=JSON.parse(h)}catch{return}let g=m.sessionId??m.session_id??"",y=m.timestamp?Date.parse(m.timestamp):Date.now(),v=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let w=XI[m.attachment.type];w&&(s[ZI(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(v==="user"){let w=QI(m.message?.content),b=ti(w);b&&(i=b);let k={session_id:g,ts:y,text:w,effort_directive:b};n.push({kind:"user",...k});return}if(v==="assistant"){let w=m.message?.usage,b=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,k=typeof m.requestId=="string"&&m.requestId?m.requestId:null,S=b??k,R=S!==null&&r.has(S);S!==null&&!R&&r.add(S);let D={session_id:g,ts:y,model:m.message?.model??null,input_tokens:R?0:to(w?.input_tokens),output_tokens:R?0:to(w?.output_tokens),cache_read_input_tokens:R?0:to(w?.cache_read_input_tokens),cache_creation_input_tokens:R?0:to(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 XI,N_=_(()=>{"use strict";zs();vl();XI={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(ZI,"modeFlagKey");a(to,"num");a(QI,"extractUserText");a(jl,"streamTranscript")});var C_=_(()=>{"use strict"});import{homedir as eN}from"node:os";import{join as tN}from"node:path";function Hl(e){return e.replace(/[/.]/g,"-")}var nN,Ul,O_=_(()=>{"use strict";nN=eN(),Ul=tN(nN,".claude","projects");a(Hl,"projectPathFromCwd")});var or=_(()=>{"use strict";vl();a_();c_();h_();g_();Js();Rl();y_();S_();I_();N_();zs();C_();O_()});function Gl(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 pN(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 ar(e,t){let n=`npm i -g ${ri}@${e}`;return t?`nvm use ${t} && ${n}`:n}function ro(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(u=>u.bridgeVersion).filter(u=>u!==null)],r=e.latestVersion??n.sort(Gl).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=e.nodeTrees.filter(u=>u.bridgeVersion!==null);if(e.nodeTrees.length>0){let u=e.pathWinner?.node??null,p=e.nodeTrees.find(m=>m.node===u);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):p&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${p.node} tree (${p.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let m=e.nodeTrees.find(g=>g.node===e.nvmDefault);m&&m.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${m.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:ar(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(g=>Gl(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:ar(r,m.node)})}let s=!1,o=new Map,c=a((u,p)=>{let h=o.get(u)??{version:e.installVersionOf(u),clients:[]};h.clients.push(p),o.set(u,h)},"noteInstall");for(let u of e.clientConfigs){let p=pN(u);if(p===null)continue;if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(g=>g.includes(ri))){t.push({check:"client-config",level:"warn",message:`${u.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${ar(r)}, then set "command": "maind-mcp-bridge" (no args) in ${u.path}`});continue}let m=/(^|[\\/])node(\.exe)?$/.test(p.command);if(m&&p.args.length>0){let g=p.args[0];if(!e.fileExists(g)){t.push({check:"client-config",level:"error",message:`${u.label} runs ${g}, which does not exist.`,fix:`re-run \`npx -y ${ri}@${r} install\` to rewrite the entry`});continue}c(g,u.label)}else if(p.command.includes("/")||p.command.includes("\\")){if(!e.fileExists(p.command)){t.push({check:"client-config",level:"error",message:`${u.label} points at ${p.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${u.path} (after ${ar(r)})`});continue}}else if(p.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${u.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:ar(r,e.nvmDefault)});continue}m||(p.command.includes("/")||p.command.includes("\\")?c(p.command,u.label):p.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,u.label)),t.push({check:"client-config",level:"ok",message:`${u.label}: ${[p.command,...p.args].join(" ")}`})}if(s||t.push({check:"client-config",level:"warn",message:"no MCP client config names a `maind` server.",fix:`npx -y ${ri} install`}),e.latestVersion!==null)for(let[u,p]of o){let h=p.clients.join(", ");if(p.version===null)t.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${u} is.`});else if(Gl(p.version,e.latestVersion)<0){let m=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(u)?.[1]??null;t.push({check:"version",level:"warn",message:`${h} run bridge ${p.version} (${u}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:m?ar(e.latestVersion,m):`npx -y ${ri}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${h} run bridge ${p.version} (published: ${e.latestVersion}).`})}for(let{dir:u,maind:p}of e.npxStaleDirs)t.push({check:"npx-cache",level:p?"error":"info",message:p?`a half-built better-sqlite3 was left in ${u} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${u} (another tool's npx entry, not maind's).`,fix:`rm -rf '${u.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!M_.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"}):uN.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&M_.test(e.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=e.connection;if(d===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):d.outcome==="ok"||d.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):t.push({check:"connection",level:"error",message:d.outcome==="auth_failed"?`the server rejected the last connection (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"}),e.claudeSettings!==null){let u=tn(e.claudeSettings,{fileExists:a(h=>e.fileExists(h),"fileExists")}),p=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let h of u){if(h.status==="missing")continue;if(h.status!=="ok"){t.push({check:"hooks",level:h.status==="broken"?"error":"warn",message:h.detail});continue}let m=h.command?/(\S+\/build\/index\.js)/.exec(h.command)?.[1]??null:null,g=m?e.installVersionOf(m):null;g!==null&&p!==null&&g!==p&&t.push({check:"hooks",level:"warn",message:`${h.event}/${h.subcommand} runs bridge ${g}, the MCP server runs ${p} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${h.subcommand}`})}t.some(h=>h.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}return t}function L_(e){let t=e.filter(i=>i.level==="error"&&Bl.includes(i.check)).sort((i,s)=>Bl.indexOf(i.check)-Bl.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 $_(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((o,c)=>n[o.level]-n[c.level]).flatMap(o=>[`${t[o.level]} [${o.check}] ${o.message}`,...o.fix?[` fix: ${o.fix}`]:[]]),i=e.filter(o=>o.level==="error").length,s=e.filter(o=>o.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
170
170
|
`)+`
|
|
171
|
-
`}var
|
|
172
|
-
`):process.stdout.write(
|
|
173
|
-
`).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await
|
|
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
|
|
171
|
+
`}var ri,uN,M_,Bl,Wl=_(()=>{"use strict";zn();ri="@maind-dev/mcp-bridge",uN=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,M_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Gl,"compareVersions");a(pN,"maindEntry");a(ar,"installFix");a(ro,"diagnose");Bl=["connection","client-config","npx-cache","hooks"];a(L_,"sessionStartLine");a($_,"renderFindings")});var H_={};te(H_,{realProbe:()=>so,resolveNvmAlias:()=>U_,runDoctor:()=>xN});import{execFileSync as fN}from"node:child_process";import{existsSync as ql,readFileSync as mN,readdirSync as Kl,realpathSync as hN}from"node:fs";import{homedir as ii,platform as io}from"node:os";import{delimiter as gN,dirname as F_,join as ce}from"node:path";function ln(e){try{return ql(e)?mN(e,"utf8"):null}catch{return null}}function yN(){try{let e=fN(io()==="win32"?"npm.cmd":"npm",["view",j_,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function Vl(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ce(ii(),".nvm")}function _N(){let e=ce(Vl(),"versions","node"),t=[];try{t=Kl(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=ln(ce(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),i=null;try{i=r?JSON.parse(r).version??null:null}catch{i=null}return{node:n,bridgeVersion:i}})}function U_(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(d[p]!==u[p])return(d[p]??0)-(u[p]??0);return 0});if(r==="node"||r==="stable")return i.at(-1)??null;let s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return s;let o=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(o)).at(-1)??null}function bN(e){let t=ln(ce(Vl(),"alias","default"));return t===null?null:U_(t,e.map(n=>n.node),n=>{let r=ln(ce(Vl(),"alias",n));return r===null?null:r})}function wN(){let e=io()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(gN))if(t)for(let n of e){let r=ce(t,n);if(ql(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function vN(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:io()==="win32"?ce(process.env.LOCALAPPDATA??ce(ii(),"AppData","Local"),"npm-cache"):ce(ii(),".npm"),t=ce(e,"_npx"),n=[],r=[];try{r=Kl(t)}catch{return[]}for(let i of r)try{let s=Kl(ce(t,i,"node_modules"));s.some(o=>o.startsWith(".better-sqlite3-"))&&n.push({dir:ce(t,i),maind:s.includes("@maind-dev")})}catch{}return n}function kN(e){let t;try{t=F_(hN(e))}catch{return null}for(let n=0;n<6;n++){let r=ln(ce(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===j_)return s.version??null}catch{}let i=F_(t);if(i===t)break;t=i}return null}function so(e=process.cwd(),t={}){let n=_N(),r=ln(ce(Se(),"device-id")),i=ks({projectRoot:e,homeDir:ii(),platform:io(),env:process.env}),s=null;try{s=K()}catch{s=null}let o=(process.env.MAIND_API_KEY??"").trim();return{runningVersion:G,latestVersion:t.offline===!0?null:yN(),nodeTrees:n,nvmDefault:bN(n),pathWinner:wN(),clientConfigs:vs(i).map(c=>({label:c.label,path:c.path,kind:c.kind,raw:ln(c.path)})),npxStaleDirs:vN(),connection:Wh(),claudeSettings:ln(ce(ii(),".claude","settings.json")),fileExists:a(c=>ql(c),"fileExists"),installVersionOf:kN,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:o.length>0?o:null}}async function xN(e){let t=ro(so());return e.includes("--json")?process.stdout.write(JSON.stringify({version:G,findings:t},null,2)+`
|
|
172
|
+
`):process.stdout.write($_(t)),t.some(n=>n.level==="error")?1:0}var j_,zl=_(()=>{"use strict";jc();se();Uc();Je();Wl();j_="@maind-dev/mcp-bridge";a(ln,"readOrNull");a(yN,"latestVersion");a(Vl,"nvmDir");a(_N,"nodeTrees");a(U_,"resolveNvmAlias");a(bN,"nvmDefault");a(wN,"pathWinner");a(vN,"npxStaleDirs");a(kN,"installVersionOf");a(so,"realProbe");a(xN,"runDoctor")});async function B_(e){return et("get_session_briefing",{tools:["claude-code"]},e)}async function et(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??si,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:SN,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id"),d=(c.headers.get("content-type")??"").startsWith("text/event-stream")?await G_(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let v=null;try{let w=JSON.parse(d);typeof w.result?.instructions=="string"&&(v=w.result.instructions)}catch{v=null}n.onInitialize(v)}if(!c.ok||!l)return null;let u={...o,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(v=>v.text().catch(()=>"")).catch(()=>"");let p=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!p.ok)return null;let m=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await G_(p):await p.text();if(m.trim().length===0)return null;let g=JSON.parse(m);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(v=>v.type==="text"&&typeof v.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(s)}}async function G_(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",o=a(()=>{if(i.length===0)return;let c=i.join(`
|
|
173
|
+
`).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
174
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){o();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return o(),s}var si,SN,cr=_(()=>{"use strict";si="https://mcp.maind.dev/mcp",SN="2025-06-18";a(B_,"fetchSessionBriefing");a(et,"fetchToolText");a(G_,"readSseMessage")});function EN(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":X()}}async function W_(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:EN(t),body:JSON.stringify({metrics:n})});if(!r.ok){let s=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:s.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var oo,Yl=_(()=>{"use strict";se();Wn();oo=process.env.MAIND_ENDPOINT??Bn("mcp-client-metrics-ingest");a(EN,"ingestHeaders");a(W_,"postMetrics")});function K_(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function q_(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,s=Array.isArray(i.active_claims)?i.active_claims:[],o=[];for(let c of s){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||o.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(u)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:o,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function lr(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function oi(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function z_(e,t,n){let r=n.maxAgeMs??V_,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,o=q_(e,s),c=[];for(let l of o)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)K_(t,d.path_prefix)&&c.push(`'${d.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${oi(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${oi(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(K_(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${oi(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${oi(s)} ago, advisory \u2014 never a lock):
|
|
175
175
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
176
176
|
`)+`
|
|
177
|
-
Verify live before large edits: check_path_conflicts({project_key: "${
|
|
178
|
-
${m}`:m}var
|
|
179
|
-
`)
|
|
177
|
+
Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function Y_(e,t){let n=typeof e?.own_session_id=="string"?e.own_session_id.toLowerCase():null,r=t!==null?t.toLowerCase():null;return r!==null&&n!==null&&n!==r?{id:r,announceError:null}:{id:e?.own_session_id??null,announceError:e?.announce_error??null}}function J_(e,t,n,r=V_,i=null){if(!e)return null;let s=n-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let o=s/1e3,c=q_(e,o),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",h=u>0?`, ${u} presence-only`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${h}) as of ${oi(o)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
178
|
+
${m}`:m}var V_,Jl=_(()=>{"use strict";a(K_,"prefixConflict");V_=10*6e4;a(q_,"parsePeers");a(lr,"selectOwnSnapshot");a(oi,"ageDisplay");a(z_,"adviseOnPath");a(Y_,"claimedIdentity");a(J_,"sessionStartSummary")});async function W(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=a(s=>{n||(n=!0,clearTimeout(i),t(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>e.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(e).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function dr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Fe(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var be=_(()=>{"use strict";a(W,"readHookInput");a(dr,"transcriptPathOf");a(Fe,"toolFilePathOf")});function Z_(e){let t=[];for(let n of Q_(e)){let r=ON(n);r&&!t.includes(r)&&t.push(r)}return t}function Q_(e){let t=[],n="",r=null,i=0,s=[],o=a(()=>{n.trim()&&t.push(n),n=""},"flush");for(;i<e.length;){let c=e[i];if(r){if(c==="\\"&&r==='"'){n+=c+(e[i+1]??""),i+=2;continue}c===r&&(r=null),n+=c,i+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,i+=1;continue}if(c==="<"&&e[i+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(i));if(l){s.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
|
|
179
|
+
`){if(s.length>0){let d=e.slice(i+1).split(`
|
|
180
|
+
`),u=0;for(;s.length>0&&u<d.length;)d[u].trim()===s[0]&&s.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,h)=>p+h.length+1,0),s=[],o();continue}o(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){o(),i+=2;continue}if(c===";"||c==="|"){o(),i+=1;continue}n+=c,i+=1}return o(),t}function ON(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let o=t[n];if(o===void 0)return null;if(AN.test(o)){n+=1;continue}if(IN.has(o)){n+=1;continue}if(NN.has(o))return null;let c=o.split("/").pop()??o;if(RN.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!X_.test(i))return null;if(!TN.test(i))return Xl;if(!CN.has(i))return i;let s=t[n+1];return s&&X_.test(s)?`${i} ${s}`:i}function Zl(e){let t=Z_(e).filter(n=>n!==Xl&&!eb.has(n));return t.length>0?t[t.length-1]:null}var X_,TN,Xl,AN,RN,IN,NN,CN,eb,Ql=_(()=>{"use strict";X_=/^[A-Za-z][A-Za-z0-9._-]*$/,TN=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,Xl="?",AN=/^[A-Za-z_][A-Za-z0-9_]*=/,RN=new Set(["sudo","env","time","nohup","nice","command","exec"]),IN=new Set(["do","then","else","elif","if","while","until","!","{","("]),NN=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),CN=new Set(["git","gh","npm","pnpm","yarn","npx","bun","deno","docker","kubectl","terraform","aws","gcloud","cargo","go","pip","poetry","uv","dotnet","mvn","supabase","vercel","brew","apt","systemctl"]);a(Z_,"shellPrograms");a(Q_,"commandSegments");a(ON,"programOf");eb=new Set(["echo","printf","cat","head","tail","less","more","grep","egrep","fgrep","rg","ag","sed","awk","cut","sort","uniq","wc","tr","tee","xargs","jq","yq","column","nl","diff","cmp","comm","ls","tree","find","fd","stat","file","du","df","basename","dirname","realpath","readlink","rm","cp","mv","mkdir","rmdir","touch","chmod","chown","ln","cd","pushd","popd","test","true","false","read","set","export","source","sleep","wait","which","whereis","type","date","printenv","ps","pgrep","lsof","kill","pkill","killall","id","whoami","uname","open","git log","git show","git status","git diff","git grep","git cat-file","git rev-parse","git ls-files","git blame","git branch","git remote","git config","git worktree","git stash","git merge-base","git describe","git reflog","git ls-remote","git for-each-ref","git symbolic-ref","git check-ignore"]);a(Zl,"primaryVerb")});function tb(e){let t=e.length>ed?e.slice(-ed):e;return DN.some(n=>n.test(t))}function td(e){return e.includes("maind")?PN.some(t=>e.includes(t)):!1}function nb(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function rb(e,t){if(!nb(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?Zl(n):null}function nd(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=rb(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&tb(e.output)?"fail":"ok",verb:t}}var ed,DN,PN,ib=_(()=>{"use strict";Ql();ed=8192,DN=[/\b[1-9]\d* (?:failed|failing)\b/,/^# fail [1-9]\d*/m,/\berror TS\d{4}\b/,/^npm ERR!/m,/\bERR_PNPM_[A-Z_]+/,/\bELIFECYCLE\b/,/\bCommand failed with exit code [1-9]/,/^Traceback \(most recent call last\):/m,/✖ [1-9]\d* problems? \([1-9]\d* errors?/,/^ERROR: {1,2}\S/m,/^--- FAIL: /m,/^error(?:\[E\d{4}\])?: /m,/^(?:Type|Reference|Syntax|Range)Error: /m,/^fatal: /m];a(tb,"outputShowsFailure");PN=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];a(td,"isConsultationTool");a(nb,"isCountedTool");a(rb,"verbOfCall");a(nd,"observe")});function sb(e){let t=[...e].reverse().find(n=>typeof n.v=="string");return{start:e[0].t,end:e[e.length-1].t,failures:e,lastVerb:t?.v??null}}function rd(e,t=-1/0){let n=e.filter(s=>s.k==="fail"&&s.t>t).slice().sort((s,o)=>s.t-o.t),r=[],i=[];for(let s of n)i.length>0&&s.t-i[i.length-1].t>6e5&&(r.push(sb(i)),i=[]),i.push(s);return i.length>0&&r.push(sb(i)),r}function id(e,t,n){if(t===null)return null;let r=null;for(let i of e)i.k==="ok"&&i.v===t&&i.t>n&&(r===null||i.t<r)&&(r=i.t);return r}function ob(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function ur(e,t,n){let r=ob(e,t),i=rd(e,r),s=i.length>0?i[i.length-1]:null,o=s!==null&&n-s.end<=6e5?s:null;if(o===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=id(e,o.lastVerb,o.end)!==null,l=e.some(d=>d.k==="nudge"&&d.t>=o.start);return{open:o.failures.length>=4&&!c,chain:o,nudged:l,resolved:c}}function sd(e){return e.open&&!e.nudged}function od(e,t){let n=-1/0;for(let s of e)s.k==="prompt"&&s.t>n&&(n=s.t);let r=Math.max(t,n),i=rd(e,r);for(let s=i.length-1;s>=0;s--){let o=i[s];if(o.failures.length<5||o.end-o.start<3e5)continue;let c=id(e,o.lastVerb,o.end);if(c!==null)return{...o,resolvedAt:c}}return null}function ai(e){let t=new Map;for(let n of e.failures){let r=n.v??"?";t.set(r,(t.get(r)??0)+1)}return[...t.entries()].map(([n,r])=>r>1?`${n} \xD7${r}`:n).join(", ")}var ad=_(()=>{"use strict";a(sb,"chainOf");a(rd,"failureChains");a(id,"succeededAfter");a(ob,"resetPoint");a(ur,"difficultyStatus");a(sd,"shouldNudge");a(od,"captureCandidate");a(ai,"verbSummary")});function LN(e){let t=e.id;if(typeof t!="string")return null;let n=e.version,r=typeof n=="number"&&Number.isInteger(n)&&n>=1?n:1,i=e.severity,s=typeof i=="string"&&MN.has(i)?i:"recommended",o=e.enabled!==!1;return{id:t,version:r,severity:s,enabled:o}}function co(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return li;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let s=LN(i);s!==null&&(s.id===ci?n=s:s.id===ao&&(r=s))}return{difficulty:n,capture:r}}function pr(e){return e!==null&&e.enabled}function cd(e){return pr(e)&&e.severity==="required"}var ci,ao,li,MN,ld=_(()=>{"use strict";ci="conv_consult_on_difficulty",ao="conv_learning_capture_offer",li={difficulty:null,capture:null},MN=new Set(["required","recommended","info"]);a(LN,"ruleOf");a(co,"extractTriggerPolicy");a(pr,"isActive");a(cd,"isDenyCapable")});function $N(e){return Math.max(1,Math.round(e/6e4))}function di(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${ai(e)}) and no maind consultation since they started (${ci}). Before the next attempt, consult maind: search_lessons with the symptom \u2014 error code, tool or library, the failing program \u2014 never paths, file contents or secrets. If a hit applies, use it; if none does, say so in one line and go on. This hint appears once per episode.`}function dd(e){return`difficulty episode (${e.failures.length} failed attempts: ${ai(e)}) without a maind consultation since it started (${ci}, required)`}function ud(e,t="guard"){let n=$N(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${ao}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${ai(e)}), then ${r}. Before you finish, ask the user whether the finding should be recorded: (1) private memory (keep_memory), (2) lesson draft (run the submission routing gate first, then submit_content_draft), (3) project documentation (ADR or code note), or (4) no. Record nothing without an explicit yes. If the finding is trivial or already recorded, say so in one line instead (\`maind-skip: learning-capture <reason>\`). This hold happens once per episode.`}var ab=_(()=>{"use strict";ad();ld();a($N,"minutes");a(di,"nudgeText");a(dd,"difficultyDenyHead");a(ud,"captureText")});var fr=_(()=>{"use strict";Ql();ib();ad();ld();ab()});import{mkdir as FN,readFile as jN,writeFile as UN,rename as HN}from"node:fs/promises";import{existsSync as db}from"node:fs";import{homedir as GN}from"node:os";import{join as ub}from"node:path";function lb(){return{config:null,sessions:{},pending_metrics:[]}}async function z(){if(!db(lo))return lb();try{let e=await jN(lo,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
|
|
181
|
+
`),lb()}}async function je(e){db(dn)||await FN(dn,{recursive:!0,mode:448});let t=`${lo}.tmp`;await UN(t,JSON.stringify(e,null,2),{mode:384}),await HN(t,lo)}function pd(e){return e.thresholds??e.config?.thresholds??BN}var dn,lo,BN,tt=_(()=>{"use strict";dn=ub(GN(),".maind"),lo=ub(dn,"state.json"),BN={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};a(lb,"emptyState");a(z,"loadState");a(je,"saveState");a(pd,"resolveThresholds")});import{existsSync as fb}from"node:fs";import{mkdir as WN,readFile as KN,readdir as VN,rename as qN,stat as zN,unlink as YN,writeFile as JN}from"node:fs/promises";import{join as ui}from"node:path";function mb(e){return ui(fd,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function rt(e){try{let t=mb(e);if(!fb(t))return{};let n=JSON.parse(await KN(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function fe(e,t){await WN(fd,{recursive:!0,mode:448});let n=mb(e),r=`${n}.tmp`;await JN(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await qN(r,n)}async function hb(e=7*24*60*60*1e3,t=Date.now()){await pb(fd,".json",e,t),await pb(md,".jsonl",e,t)}async function pb(e,t,n,r){try{if(!fb(e))return;for(let i of await VN(e)){if(!i.endsWith(t))continue;let s=ui(e,i);try{let o=await zN(s);r-o.mtimeMs>n&&await YN(s)}catch{}}}catch{}}var nt,fd,md,St=_(()=>{"use strict";tt();nt=ui(dn,"guard"),fd=ui(nt,"sessions"),md=ui(nt,"triggers");a(mb,"sessionFile");a(rt,"loadGuardSession");a(fe,"saveGuardSession");a(hb,"sweepOldGuardSessions");a(pb,"sweepDir")});import{existsSync as XN}from"node:fs";import{appendFile as ZN,mkdir as QN,open as eC}from"node:fs/promises";import{join as tC}from"node:path";async function V(e){try{await QN(nt,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
182
|
+
`;await ZN(un,t,{mode:384})}catch{}}async function gb(e=256*1024){let t={inject_ok:0,inject_fail:0,warn:0,deny:0,override:0,stop_block:0,gate_override:0,cross_session_warn:0,cross_session_deny:0,difficulty_nudge:0,difficulty_deny:0,difficulty_resolved:0,capture_prompt:0,capture_taken:0};try{if(!XN(un))return t;let n=await eC(un,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
|
|
183
|
+
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var un,it=_(()=>{"use strict";St();un=tC(nt,"events.jsonl");a(V,"appendGuardEvent");a(gb,"readGuardEventCounts")});function pn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function st(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function uo(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function yb(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}var fn=_(()=>{"use strict";a(pn,"denyPayload");a(st,"advisoryPayload");a(uo,"postAdvisoryPayload");a(yb,"postFailureAdvisoryPayload")});import{realpathSync as nC}from"node:fs";import{basename as _b,dirname as bb,join as rC}from"node:path";function mn(e){let t=bb(e),n=[_b(e)];for(;;)try{let r=nC(t);return rC(r,...n.reverse())}catch{let r=bb(t);if(r===t)return e;n.push(_b(t)),t=r}}var po=_(()=>{"use strict";a(mn,"realpathOfUnwritten")});import{existsSync as iC,realpathSync as sC,statSync as oC}from"node:fs";import{dirname as wb,isAbsolute as aC,join as cC}from"node:path";function uC(e,t){let n=e.filter(i=>vb.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
|
|
180
184
|
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
181
|
-
${i.detail}${s}`});return`maind repo-health (${
|
|
185
|
+
${i.detail}${s}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
182
186
|
|
|
183
187
|
`+r.join(`
|
|
184
188
|
|
|
185
189
|
`)+`
|
|
186
190
|
|
|
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
|
|
191
|
+
This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function pC(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function fC(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},s=i[t]??{};s[n]=new Date(r).toISOString(),i[t]=s,e.repo_health_seen=i}function hd(e){let t=wb(e);for(;;){try{if(oC(t).isDirectory())return t}catch{}let n=wb(t);if(n===t)return t;t=n}}async function mC(e,t,n){let r=await n.load();if(pC(r,e,t))return null;fC(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let s=i.filter(c=>vb.includes(c.id)).length,o=await n.load();return o.pending_metrics.push({session_id:e,metric_key:lC,metric_value:1},{session_id:e,metric_key:dC,metric_value:s}),await n.save(o),uC(i,t)}async function kb(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=Fe(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=aC(r)?r:cC(i,r),o=iC(s)?sC(s):mn(s),c=Ye(hd(o)),l=await mC(n,c,{load:z,save:je,check:a(async d=>(await Nr(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(st(l)),0}catch{return 0}}var vb,lC,dC,gd=_(()=>{"use strict";Yt();Jt();fn();be();po();tt();vb=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],lC="repo_health_hook_runs",dC="repo_health_hook_findings";a(uC,"formatRepoHealth");a(pC,"alreadySeen");a(fC,"markSeen");a(hd,"nearestExistingDir");a(mC,"repoHealthForEdit");a(kb,"runOnRepoHealth")});import{existsSync as hC,readFileSync as gC,realpathSync as yC}from"node:fs";import{isAbsolute as Sb,join as Eb,posix as _C,relative as bC,sep as wC}from"node:path";function xb(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function EC(e,t){return{contracts:t.filter(r=>xb(r.spec)===e||xb(r.impl)===e).map(r=>r.id),theme:xC.test(e),acl:SC.test(e)}}function TC(e){return e.contracts.length===0&&!e.theme&&!e.acl}function AC(e,t,n,r,i=Date.now()){let s=e.write_health_seen??{},o=s[t]??{},c=new Set(o[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);o[n]={at:new Date(i).toISOString(),keys:[...c]},s[t]=o,e.write_health_seen=s}return l}function RC(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
|
|
188
192
|
|
|
189
|
-
`+
|
|
193
|
+
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
190
194
|
`)+`
|
|
191
195
|
|
|
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
|
|
193
|
-
`)}catch{}let
|
|
194
|
-
`)}}catch{}try{let r=
|
|
195
|
-
`)}}catch{}return 0}function
|
|
196
|
-
`);return`${
|
|
196
|
+
Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function IC(e,t){let n=bC(e,t);return!n||n.startsWith("..")||Sb(n)?null:n.split(wC).join(_C.sep)}function NC(e){try{let t=gC(Eb(e,zi),"utf8"),{manifest:n}=Zi(t);return n?.contracts??[]}catch{return[]}}async function Tb(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=Fe(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=Sb(r)?r:Eb(i,r),o=hC(s)?yC(s):mn(s),c=Ye(hd(o)),l=IC(c,o);if(l===null)return 0;let d=EC(l,NC(c));if(TC(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await Kt(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=qt(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=Vt(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 z(),h=AC(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:vC,metric_value:1},{session_id:n,metric_key:kC,metric_value:h.length}),await je(p);let m=RC(h,l);return m!==null&&process.stdout.write(uo(m)),0}catch{return 0}}var vC,kC,xC,SC,Ab=_(()=>{"use strict";Yt();Jt();fn();be();gd();po();tt();vC="write_health_hook_runs",kC="write_health_hook_findings",xC=/\.(tsx?|jsx?|css)$/,SC=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;a(xb,"declPath");a(EC,"routesForPath");a(TC,"routesAreEmpty");a(AC,"takeUnreported");a(RC,"formatWriteHealth");a(IC,"repoRelative");a(NC,"readContracts");a(Tb,"runOnWriteHealth")});var jb={};te(jb,{agentHostPidCandidates:()=>ot,closeTrackedSession:()=>Pb,effectiveConfig:()=>hn,grandparentPid:()=>Lb,isCaptureTool:()=>yd,recordGuardSignals:()=>Db,runFlush:()=>VC,runHookStatus:()=>qC,runOnFileEdit:()=>BC,runOnFileWrite:()=>GC,runOnRepoHealth:()=>kb,runOnSessionStart:()=>$C,runOnToolUse:()=>UC,runOnWriteHealth:()=>Tb,runSessionEndMetrics:()=>bd,runSyncConfig:()=>YC,writeIdentitySideChannel:()=>_d});import{execFileSync as Ib}from"node:child_process";import{existsSync as ho,readFileSync as Nb,realpathSync as CC}from"node:fs";import{writeFile as OC}from"node:fs/promises";import{homedir as Cb}from"node:os";import{isAbsolute as mo,join as pi,relative as Ob}from"node:path";function Db(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=td(n),s=n.includes("review_changes")||n.includes("review_verdict"),o=yd(n);if(!i&&!s&&!o)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),s&&(l.reviewed_at=d),o&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function yd(e){return e.includes("maind")?e.includes("keep_memory")||e.includes("update_memory")||e.includes("graduate_memory")||e.includes("submit_content_draft")||e.includes("submit_convention_draft")||e.includes("revise_content_draft"):!1}function Pb(e,t,n=Date.now()){LC(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function LC(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-i>fo&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));t-i>fo&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));t-i>fo&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>fo&&delete e.sessions[n]}}function hn(e){if(e.config)return e.config;let t=K();return t===null?null:{api_key:t,endpoint:oo}}function Mb(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function $C(){try{let r=L_(ro(so(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
|
|
197
|
+
`)}catch{}let e=await z();if(hn(e)===null)return 0;let t=await W(),n=Fb(t);if(n===null)return 0;Mb(e,n),await je(e);try{_d(t,n)}catch{}try{let r=q();if(r!==null){let i=nr(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),o=lr(i,{hostPids:ot(),cwd:s}),c=Y_(o?.snap??null,ei(dr(t)||null,n)),l=J_(o?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
|
|
198
|
+
`)}}catch{}try{let r=tn(FC());if(Vc(r)&&Ts(r)){let i=r.filter(s=>s.remedy==="run-install").map(s=>s.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
199
|
+
`)}}catch{}return 0}function FC(){try{let e=pi(Cb(),".claude","settings.json");return ho(e)?Nb(e,"utf8"):null}catch{return null}}function _d(e,t,n,r=rr()){let i=n??ot();if(i.length===0)return;let s=ei(dr(e)||null,t);if(s===null)return;let o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=dr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)r_({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:o,transcriptPath:c,model:l})}function Lb(){try{if(process.platform==="win32")return null;let e=Ib("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function ot(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Lb();return n!==null&&n>1&&n!==t&&e.push(n),e}async function UC(){let e=await z();if(hn(e)===null)return 0;let t=await W(),n=Fb(t)??"unknown",r=Mb(e,n);r.tool_call_count+=1;try{let o=ot().filter(c=>i_(rr(),c,jC));n!=="unknown"&&o.length>0&&_d(t,n,o)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Db(e,n,i),yd(i)&&n!=="unknown"&&await V({event:"capture_taken",session_id:n,detail:i});let s=t.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let o=await kl(r.transcript_path);o&&(r.token_count=o.total_tokens,await KC(e,r))}return await je(e),0}function HC(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
200
|
+
`);return`${t.prefix}${e.number} is already taken:
|
|
197
201
|
${n}
|
|
198
202
|
|
|
199
|
-
Next free number in ${
|
|
203
|
+
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
200
204
|
|
|
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
|
|
205
|
+
Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function GC(){try{let e=await W();if((e.tool_name??"")!=="Write")return 0;let t=Fe(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=mo(t)?t:pi(n,t);if(ho(r))return 0;let i=Ye(n),s=Ob(i,mn(r));if(s.length===0||s.startsWith("..")||mo(s))return 0;let o=await Wt(i,s);return!o.taken||o.namespace===null||process.stdout.write(pn(HC(o,o.namespace))),0}catch{return 0}}async function BC(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Fe(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=mo(n)?n:pi(r,n),s=q();if(s===null)return 0;let o=nr(s);if(o.length===0)return 0;let c=lr(o,{hostPids:ot(),cwd:r});if(c===null)return 0;let l=Ye(r),d=ho(i)?CC(i):mn(i),u=Ob(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||mo(u))return 0;let p=z_(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?WC(r):null,nowMs:Date.now()});return p===null||process.stdout.write(st(p)),0}catch{return 0}}function WC(e){try{let n=Ib("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function KC(e,t){let n=pd(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,s="ok";if(i>=n.handoff_at_pct/100?s="handoff_recommended":i>=n.warn_at_pct/100&&(s="warn"),t.last_advisory_status===s||(t.last_advisory_status=s,s==="ok"))return;let o=Math.round(i*100),c={session_id:t.session_id,status:s,tokens:r,ratio:Number(i.toFixed(3)),pct:o,thresholds:n,suggested_next:s==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await OC(pi(dn,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
|
|
202
206
|
`)}s==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${o}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
203
207
|
`):process.stderr.write(`[maind] \u26D4 Token usage at ~${o}% (handoff threshold ${n.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
|
|
204
|
-
`)}async function
|
|
205
|
-
`)}}async function
|
|
206
|
-
`),n.ok?0:1}async function
|
|
208
|
+
`)}async function bd(e){try{let t=await z(),n=hn(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Pb(t,r),await je(t)),await $b(n,PC)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
209
|
+
`)}}async function VC(){let e=await z(),t=hn(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await $b(t,MC);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
210
|
+
`),n.ok?0:1}async function $b(e,t){let n=await z();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=W_(e.endpoint,e.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),o=await Promise.race([i,s]);if(o.ok){let c=await z();return c.pending_metrics=c.pending_metrics.slice(r.length),await je(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 qC(){let e=await z(),t=hn(e),n=zC(),r=Vc(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:pd(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...Ts(n.findings)?{remedy:Rb}:{}}},null,2)+`
|
|
207
211
|
`),r){process.stderr.write(`
|
|
208
212
|
[maind] Claude Code hook wiring is incomplete:
|
|
209
213
|
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
210
|
-
`);
|
|
211
|
-
`)}return 0}function
|
|
214
|
+
`);Ts(n.findings)&&process.stderr.write(` ${Rb}
|
|
215
|
+
`)}return 0}function zC(){let e=pi(Cb(),".claude","settings.json"),t=null;try{ho(e)&&(t=Nb(e,"utf8"))}catch{}return{settingsPath:e,findings:tn(t)}}async function YC(){let e=await z(),t=hn(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??DC,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(o){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${o instanceof Error?o.message:String(o)}
|
|
212
216
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
213
217
|
`);let o=await r.text().catch(()=>"");return o&&process.stderr.write(o.slice(0,500)+`
|
|
214
218
|
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
215
219
|
`),1}let s=i;return typeof s.warn_at_pct!="number"||typeof s.handoff_at_pct!="number"||typeof s.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
216
|
-
`),1):(
|
|
217
|
-
`),0)}function
|
|
218
|
-
`)}).catch(()=>{}),o=new Promise(c=>setTimeout(c,r));await Promise.race([s,o])}async function
|
|
219
|
-
`)}return await
|
|
220
|
-
`,384)}var
|
|
221
|
-
`),1;let i={homeDir:
|
|
220
|
+
`),1):(e.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await je(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
221
|
+
`),0)}function Fb(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var DC,PC,MC,fo,jC,Rb,wd=_(()=>{"use strict";or();fr();Yt();Jt();it();se();zn();Ks();De();Yl();Jl();qs();be();fn();po();tt();Wn();Wl();zl();gd();Ab();DC=process.env.MAIND_THRESHOLDS_ENDPOINT??Bn("get-context-thresholds"),PC=1500,MC=1e4,fo=7*24*60*60*1e3;a(Db,"recordGuardSignals");a(yd,"isCaptureTool");a(Pb,"closeTrackedSession");a(LC,"gcState");a(hn,"effectiveConfig");a(Mb,"getOrCreateSession");a($C,"runOnSessionStart");a(FC,"readSettingsRaw");a(_d,"writeIdentitySideChannel");jC=6e4;a(Lb,"grandparentPid");a(ot,"agentHostPidCandidates");a(UC,"runOnToolUse");a(HC,"denyReason");a(GC,"runOnFileWrite");a(BC,"runOnFileEdit");a(WC,"currentGitBranch");a(KC,"maybeEmitAdvisory");a(bd,"runSessionEndMetrics");a(VC,"runFlush");a($b,"flushPending");a(qC,"runHookStatus");Rb="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(zC,"readHookWiring");a(YC,"runSyncConfig");a(Fb,"sessionIdOf")});function Ub(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Hb=_(()=>{"use strict";a(Ub,"resolveConnection")});function Bb(e,t,n,r=Date.now()){let i=t===null?null:Dl(t),s=Ll(e,i,{repoRoot:n,nowMs:r});return s.length===0?null:{slices:s,context_ok:i!==null}}var Gb,vd=_(()=>{"use strict";or();Gb=2e3;a(Bb,"buildCostPayload")});function Kb(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!Wb.test(n))return null;let r=n.toLowerCase();return t!==null&&Wb.test(t)&&r!==t.toLowerCase()?null:r}var Wb,Vb=_(()=>{"use strict";Wb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Kb,"snapshotSessionId")});async function qb(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await ni(e.transcriptPath),i=e.resolveRoot?$l(r,e.resolveRoot):null,s=i&&e.projectKeyOf?e.projectKeyOf(i):null,o=i!==null&&s!==null&&s!==e.projectKey;o&&n.catch(()=>{});let[c,l,d]=await Promise.all([Sl(e.transcriptPath,{turns:r}),Fl(e.transcriptPath),o?e.fetchContext(s):n]),u=i??e.repoRoot;if(e.sessionId&&(c.session_id=e.sessionId,l.session_id=e.sessionId),c.maind_connected=e.connection(c.maind_connected==="connected",t()),!c.session_id)return{posted:!1,contextOk:d!==null,sentSlices:!1};let p=Bb(r,d,u,t()),h=Al(c,l,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",p);return await e.post(h,p!==null),{posted:!0,contextOk:p?.context_ok??d!==null,sentSlices:p!==null}}var zb=_(()=>{"use strict";or();vd();a(qb,"ingestSessionEnd")});var Xb={};te(Xb,{runOnSessionEnd:()=>iO});import{execFileSync as kd}from"node:child_process";function XC(e,t){try{let n=q(),r=n!==null&&!gl(process.env,$e()),i=null;if(n!==null){let s=lr(nr(n),{hostPids:ot(),cwd:process.cwd()});if(s){let o=Date.parse(s.snap.written_at);i=Number.isFinite(o)?Math.max(0,t-o):null}}return Ub({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function ZC(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let r=q();if(r!==null){let i=lr(nr(r),{hostPids:ot(),cwd:process.cwd()}),s=Kb(i?.snap,e);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function QC(){try{let e=kd("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function eO(e){let t=Yb.get(e);if(t!==void 0)return t;let n=null;try{let r=kd("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return Yb.set(e,n),n}function tO(e){let t=Jb.get(e);if(t!==void 0)return t;let n=null;try{let r=kd("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=ys(r))}catch{n=null}return Jb.set(e,n),n}async function nO(e,t,n,r){if(n===null)return null;try{return await et("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:G,timeoutMs:Gb})}catch{return null}}async function rO(e,t,n,r,i){let s=fetch(JC,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":G},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=Tl(El(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
|
|
222
|
+
`)}).catch(()=>{}),o=new Promise(c=>setTimeout(c,r));await Promise.race([s,o])}async function iO(){try{for(let i of ot())s_(rr(),i)}catch{}let e=K();if(!e)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=dr(t);if(r)try{let i=X(),s=ZC(ei(r,n)),o=q();await qb({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:o,coordSessionId:s,repoRoot:QC(),resolveRoot:eO,projectKeyOf:tO,fetchContext:a(c=>nO(e,i,c,s),"fetchContext"),post:a((c,l)=>rO(e,i,c,1500,l),"post"),connection:XC})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
223
|
+
`)}return await bd(n),0}var JC,Yb,Jb,Zb=_(()=>{"use strict";or();Yn();se();cr();Yl();Jl();be();wd();yl();Ks();De();qs();Je();Hb();vd();Vb();zb();JC=oo;a(XC,"connectionVerdict");a(ZC,"presenceSessionId");a(QC,"sessionRepoRoot");Yb=new Map;a(eO,"gitRootOf");Jb=new Map;a(tO,"projectKeyOfRoot");a(nO,"fetchCostContext");a(rO,"postWithTimeout");a(iO,"runOnSessionEnd")});function Qb(e){return e==="on"?!0:e==="off"?!1:null}function le(e=process.env,t=$e()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0,difficulty:Qb(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:Qb(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function gn(e,t=Qe()){let n={};try{let i=await ae(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await Q(t,JSON.stringify(r,null,2)+`
|
|
224
|
+
`,384)}var at=_(()=>{"use strict";Yn();Xe();a(Qb,"envSwitch");a(le,"resolveGuardConfig");a(gn,"writeGuardConfig")});function sO(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function ew(e,t,n=process.stdout){let r=sO(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
225
|
+
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of Es)s.push(await Jc(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
222
226
|
`);let o=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
223
227
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
224
|
-
`),0):(await
|
|
228
|
+
`),0):(await gn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
225
229
|
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
226
230
|
flip: maind-mcp-bridge guard mode <warn|block>
|
|
227
231
|
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
228
232
|
check: maind-mcp-bridge guard status
|
|
229
233
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
230
234
|
`),o&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
231
|
-
`),c?1:0)}var
|
|
232
|
-
|
|
233
|
-
`)
|
|
234
|
-
`),1):(await
|
|
235
|
-
`),0)}case"off":return await
|
|
235
|
+
`),c?1:0)}var tw=_(()=>{"use strict";zn();Xc();at();a(sO,"parseGuardInstallFlags");a(ew,"runGuardInstall")});import{existsSync as nw}from"node:fs";import{appendFile as oO,mkdir as aO,readFile as cO}from"node:fs/promises";import{join as lO}from"node:path";function xd(e,t=go){return lO(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function mr(e,t=go){return nw(xd(e,t))}async function Et(e,t,n=go){try{await aO(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await oO(xd(e,n),r+`
|
|
236
|
+
`,{mode:384})}catch{}}async function yn(e,t=go){try{let n=xd(e,t);if(!nw(n))return[];let r=[];for(let i of(await cO(n,"utf8")).split(`
|
|
237
|
+
`))if(i.trim())try{let s=JSON.parse(i),o=s.t,c=s.k,l=s.v;if(typeof o!="number"||!Number.isFinite(o)||typeof c!="string"||!dO.has(c))continue;r.push(typeof l=="string"?{t:o,k:c,v:l}:{t:o,k:c})}catch{}return r}catch{return[]}}var go,dO,fi=_(()=>{"use strict";St();go=md,dO=new Set(["fail","ok","nudge","skip","prompt"]);a(xd,"triggerLogPath");a(mr,"hasTriggerLog");a(Et,"appendTriggerEvent");a(yn,"loadTriggerEvents")});import{existsSync as uO}from"node:fs";import{mkdir as pO,readFile as fO,rename as mO,writeFile as hO}from"node:fs/promises";import{dirname as gO,join as yO}from"node:path";function Sd(e=process.env){let t=K();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??si,keyFp:Gn(t)}}async function Ed(e,t=Date.now(),n=yo){try{if(!uO(n))return null;let r=JSON.parse(await fO(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let i=Date.parse(r.fetched_at);if(Number.isNaN(i))return null;let s=r.policy;return{policy:co([s?.difficulty,s?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<_O}}catch{return null}}async function wO(e,t,n,r){try{await pO(gO(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},s=`${r}.tmp`;await hO(s,JSON.stringify(i,null,2),{mode:384}),await mO(s,r)}catch{}}async function vO(){let e=K();if(e===null)return null;let t=null;try{t=q()}catch{t=null}let n=await et("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:kO(),projectKey:t,bridgeVersion:G,timeoutMs:bO});if(n===null)return null;try{return co(JSON.parse(n))}catch{return null}}async function hr(e,t={}){let n=t.nowMs??Date.now(),r=t.file??yo,i=t.identity===void 0?Sd():t.identity;if(i===null)return li;let s=await Ed(i,n,r);if(s?.fresh)return s.policy;if(e){let o=await(t.fetcher??vO)();if(o!==null)return await wO(i,o,n,r),o}return s?.policy??li}function kO(){try{return X()}catch{return null}}var yo,_O,bO,mi=_(()=>{"use strict";fr();Jt();se();De();Je();cr();St();yo=yO(nt,"trigger-policy.json"),_O=12*60*60*1e3,bO=3e3;a(Sd,"currentIdentity");a(Ed,"readCachedPolicy");a(wO,"writeCachedPolicy");a(vO,"fetchTriggerPolicy");a(hr,"resolveTriggerPolicy");a(kO,"safeDeviceId")});var iw={};te(iw,{runGuard:()=>AO});import{existsSync as xO,readFileSync as SO}from"node:fs";import{homedir as rw}from"node:os";import{join as EO}from"node:path";async function AO(e){let t=e[0],n=e.slice(1);switch(t){case"install":return ew(n,rw());case"status":return IO();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
238
|
+
`),1):(await gn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
239
|
+
`),0)}case"off":return await gn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
236
240
|
`),0;case"stop-gate":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard stop-gate <on|off>
|
|
237
|
-
`),1):(await
|
|
238
|
-
`),0)}case"
|
|
239
|
-
`),1
|
|
240
|
-
|
|
241
|
-
`),0}async function
|
|
242
|
-
`);let
|
|
241
|
+
`),1):(await gn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
242
|
+
`),0)}case"difficulty":case"capture":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard ${t} <on|off>
|
|
243
|
+
`),1):(await gn(t==="difficulty"?{guard_difficulty:r==="on"}:{guard_capture:r==="on"}),process.stdout.write(r==="on"?`${t} trigger follows your convention prefs again on this machine.
|
|
244
|
+
`:`${t} trigger disabled on this machine (your convention prefs are unchanged).
|
|
245
|
+
`),0)}case"skip":return RO(n);default:return process.stdout.write(TO),t===void 0||t==="--help"||t==="-h"?0:1}}async function RO(e){let t=null,n=null,r="consult";for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"?n=e[++o]??null:e[o]==="--kind"&&(r=e[++o]??"");if(!t||!n||n.trim().length===0||!["consult","difficulty","capture"].includes(r))return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why>" [--kind consult|difficulty|capture]
|
|
246
|
+
`),1;let i=n.trim().slice(0,500);if(r!=="consult")return await Et(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await V({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
|
|
247
|
+
logged (auditable) in ${un}
|
|
248
|
+
`),0;let s=await rt(t);return await fe(t,{...s,override_reason:i}),await V({event:"override",session_id:t,reason:i,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
|
|
249
|
+
logged (auditable) in ${un}
|
|
250
|
+
`),0}async function IO(){let e=le(),t=EO(rw(),".claude","settings.json"),n=null;try{xO(t)&&(n=SO(t,"utf8"))}catch{}let r=tn(n,{},Es),i=await gb(),s=Sd(),o=s?await Ed(s):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,policy:o?{difficulty:o.policy.difficulty,capture:o.policy.capture,fetched_at:o.fetchedAt,fresh:o.fresh}:null,policy_file:yo},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:un},null,2)+`
|
|
251
|
+
`);let c=r.filter(l=>l.status!=="ok");if(e.mode==="off"&&process.stderr.write("\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"),c.length>0&&e.mode!=="off"){process.stderr.write(`
|
|
243
252
|
[maind] guard hook wiring is incomplete:
|
|
244
|
-
`);for(let
|
|
245
|
-
`);
|
|
246
|
-
`);a(
|
|
247
|
-
`),n=
|
|
248
|
-
`):null}function
|
|
249
|
-
`),more:"get_session_briefing"}];let r=[];n.setup_advisory!==null&&n.setup_advisory!==void 0&&r.push({title:"Setup advisory (first session)",lines:[JSON.stringify(n.setup_advisory)],more:"get_agent_setup_guide"});let i=a((s,o)=>(s??[]).map(o).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,s=>s.title?`- ${s.title}${s.id?` (${s.id})`:""}${s.summary?` \u2014 ${s.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,s=>s.id?`- ${s.id}${s.summary?`: ${s.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,s=>s.title?`- ${s.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,s=>s.id?`- ${s.id}${s.title?`: ${s.title}`:""}`:null),more:"search_lessons"}),r.filter(s=>s.lines.length>0)}function
|
|
250
|
-
`);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...
|
|
251
|
-
|
|
252
|
-
${d.title}`;if(
|
|
253
|
-
${d.lines[p]}`;if(
|
|
254
|
-
(+${d.lines.length-p} more \u2014 via ${d.more})`;
|
|
255
|
-
\u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;
|
|
256
|
-
`,complete:l}}var
|
|
257
|
-
`),0;let d=
|
|
253
|
+
`);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
|
|
254
|
+
`);c.some(l=>l.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var TO,sw=_(()=>{"use strict";zn();at();tw();it();St();fi();mi();TO=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)"," difficulty <on|off>"," in-loop trigger 1 on this machine (ADR-360): repeated failures \u2192 consult maind"," capture <on|off>"," in-loop trigger 2 on this machine (ADR-360): hard-won fix \u2192 ask about a learning"," (on = follow your convention prefs, which are the declared opt-out)",' skip --session <id> --reason "<why>" [--kind consult|difficulty|capture]'," record a logged override for one session (default kind: consult \u2014"," the block-gate exit valve; difficulty closes the open episode;"," capture answers the pending learning question)",""].join(`
|
|
255
|
+
`);a(AO,"runGuard");a(RO,"runGuardSkip");a(IO,"runGuardStatus")});function ow(e){if(!e)return null;let t=e.split(`
|
|
256
|
+
`),n=t.findIndex(i=>i.startsWith("=== Project Conventions"));if(n<0)return null;let r=[];for(let i=n;i<t.length&&t[i].trim()!=="";i++)r.push(t[i]);return r.length>1?r.join(`
|
|
257
|
+
`):null}function NO(e){let t=e.indexOf("{"),n=null;if(t>=0)try{n=JSON.parse(e.slice(t))}catch{n=null}if(n===null)return[{title:"Session briefing",lines:e.split(`
|
|
258
|
+
`),more:"get_session_briefing"}];let r=[];n.setup_advisory!==null&&n.setup_advisory!==void 0&&r.push({title:"Setup advisory (first session)",lines:[JSON.stringify(n.setup_advisory)],more:"get_agent_setup_guide"});let i=a((s,o)=>(s??[]).map(o).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,s=>s.title?`- ${s.title}${s.id?` (${s.id})`:""}${s.summary?` \u2014 ${s.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,s=>s.id?`- ${s.id}${s.summary?`: ${s.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,s=>s.title?`- ${s.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,s=>s.id?`- ${s.id}${s.title?`: ${s.title}`:""}`:null),more:"search_lessons"}),r.filter(s=>s.lines.length>0)}function aw(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
|
|
259
|
+
`);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...NO(n));let o=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
|
|
260
|
+
|
|
261
|
+
${d.title}`;if(_o(c+u)>o){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let h=`
|
|
262
|
+
${d.lines[p]}`;if(_o(c+h)<=o){c+=h;continue}l=!1;let m=`
|
|
263
|
+
(+${d.lines.length-p} more \u2014 via ${d.more})`;_o(c+m)<=r&&(c+=m);break}if(!l)break}if(!l){let d=`
|
|
264
|
+
\u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;_o(c+d)<=r&&(c+=d)}return{text:c+`
|
|
265
|
+
`,complete:l}}var _o,cw=_(()=>{"use strict";_o=a(e=>Buffer.byteLength(e,"utf8"),"bytes");a(ow,"extractConventionsBlock");a(NO,"briefingSections");a(aw,"composeInjection")});var fw={};te(fw,{BRIEFING_CACHE_FILE:()=>dw,formatInjection:()=>pw,resolveBriefingInjection:()=>uw,runGuardInject:()=>UO});import{existsSync as CO}from"node:fs";import{mkdir as OO,readFile as DO,rename as PO,writeFile as MO}from"node:fs/promises";import{dirname as LO,join as $O}from"node:path";async function uw(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??dw,s=n.fetcher??B_,o=await HO(i),c=o!==null&&o.format===lw&&r-Date.parse(o.fetched_at)<FO&&o.project_key===e,l=a(p=>p.conventions?{conventions:p.conventions}:{},"withConventions");if(c)return{text:o.text,via:"cache",...l(o)};let d=null,u=await s({onInitialize:a(p=>{d=ow(p)},"onInitialize"),apiKey:t,deviceId:BO(),projectKey:e,bridgeVersion:G,timeoutMs:jO});if(u!==null){let p=d;return await GO(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:lw,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return o!==null?{text:o.text,via:"stale-cache",...l(o)}:{text:null,via:"none"}}async function UO(){try{if(le().mode==="off")return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await hb();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await rt(n);return await fe(n,{...u,carryover:!0}),0}let i=K();if(i===null)return 0;let s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),o=q(),c=await uw(o,i),l=await rt(n);if(c.text===null)return await fe(n,{...l,inject_failed:!0}),await V({event:"inject_fail",session_id:n,cwd:s,project_key:o??void 0}),process.stderr.write(`[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.
|
|
266
|
+
`),0;let d=pw(c.text,c.via,c.conventions??null);return process.stdout.write(d.text),await fe(n,{...l,injected:!0}),await V({event:"inject_ok",session_id:n,cwd:s,project_key:o??void 0,detail:d.complete?c.via:`${c.via}+budget`}),0}catch{return 0}}function pw(e,t,n=null){return aw(`[maind guard] Session briefing${n?" + project conventions":""}, injected deterministically (ADR-284)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`,n,e)}async function HO(e){try{if(!CO(e))return null;let t=JSON.parse(await DO(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text,...typeof t.format=="number"?{format:t.format}:{},...typeof t.conventions=="string"&&t.conventions.length>0?{conventions:t.conventions}:{}}}catch{return null}}async function GO(e,t){try{await OO(LO(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await MO(n,JSON.stringify(t,null,2),{mode:384}),await PO(n,e)}catch{}}function BO(){try{return X()}catch{return null}}var dw,FO,lw,jO,mw=_(()=>{"use strict";se();be();De();Je();at();cw();it();St();cr();dw=$O(nt,"briefing-cache.json"),FO=12*60*60*1e3,lw=2,jO=3e3;a(uw,"resolveBriefingInjection");a(UO,"runGuardInject");a(pw,"formatInjection");a(HO,"readCache");a(GO,"writeCache");a(BO,"safeDeviceId")});var yw={};te(yw,{bashOutputOf:()=>hw,consultedAtOf:()=>bo,outcomeFromHook:()=>gw,runGuardDifficulty:()=>KO});function hw(e){if(e===null||typeof e!="object")return{output:null,interrupted:!1};let t=e,n=[t.stdout,t.stderr].filter(r=>typeof r=="string"&&r.length>0);return{output:n.length>0?n.join(`
|
|
267
|
+
`):null,interrupted:t.interrupted===!0}}function gw(e){let t=e.hook_event_name;if(t!=="PostToolUse"&&t!=="PostToolUseFailure")return null;let n=typeof e.tool_name=="string"?e.tool_name:"",r=t==="PostToolUseFailure",i=!r&&n==="Bash"?hw(e.tool_response):{output:null,interrupted:!1},s=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:i.output,isInterrupt:e.is_interrupt===!0||i.interrupted,isSubagent:typeof s=="string"&&s.length>0}}}function bo(e,t){let n=e.guard_signals?.[t]?.consulted_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}async function WO(e,t,n){if(!mr(e))return;let r=await yn(e);if(!r.some(o=>o.k==="fail"&&o.v===t))return;let i=ur(r,null,n);await Et(e,{t:n,k:"ok",v:t});let s=i.chain;s!==null&&s.failures.length>=4&&!i.resolved&&s.lastVerb===t&&await V({event:"difficulty_resolved",session_id:e,detail:String(s.failures.length)})}async function KO(){try{let e=le();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=gw(t);if(r===null)return 0;let i=nd(r.outcome);if(i===null)return 0;let s=Date.now();if(i.kind==="ok")return await WO(n,i.verb,s),0;await Et(n,{t:s,k:"fail",v:i.verb});let o=await yn(n),c=ur(o,bo(await z(),n),s);if(!sd(c)||c.chain===null)return 0;let l=await hr(!0);if(!e.difficulty||!pr(l.difficulty))return 0;await Et(n,{t:s,k:"nudge"});let d=di(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?yb(d):uo(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await V({event:"difficulty_nudge",session_id:n,cwd:u,project_key:q()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Td=_(()=>{"use strict";fr();be();fn();tt();De();at();it();fi();mi();a(hw,"bashOutputOf");a(gw,"outcomeFromHook");a(bo,"consultedAtOf");a(WO,"recordSuccess");a(KO,"runGuardDifficulty")});var vw={};te(vw,{decideDifficultyGate:()=>ww,decideGate:()=>bw,runGuardGate:()=>zO});function bw(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:_w(n)}:(n.deny_count??0)>=wo?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. "+_w(n)}:{kind:"deny",reason:VO(e.sessionId,n)}}function _w(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function VO(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
|
|
258
268
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
259
|
-
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${
|
|
260
|
-
After ${
|
|
261
|
-
|
|
262
|
-
|
|
269
|
+
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
270
|
+
After ${wo} denies this gate downgrades itself to warn.`}function ww(e){let{mode:t,status:n,session:r}=e;return t!=="block"||!e.enabled||!e.denyCapable?{kind:"allow"}:!n.open||n.chain===null?{kind:"allow"}:(r.difficulty_deny_count??0)>=wo?r.difficulty_breaker_warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Difficulty-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+di(n.chain)}:{kind:"deny",reason:qO(n,e.sessionId)}}function qO(e,t){return`[maind guard | block] Edit denied \u2014 ${dd(e.chain)}. Two exits:
|
|
271
|
+
1. Consult: call search_lessons with the symptom \u2014 error code, tool or library, never paths or secrets \u2014 the gate opens on the next attempt.
|
|
272
|
+
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
|
|
273
|
+
After ${wo} denies this gate downgrades itself to warn.`}async function zO(){try{let e=le();if(e.mode==="off")return 0;let t=await W(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await rt(r),s=bo(await z(),r),o=s!==null,c=bw({mode:e.mode,session:i,consulted:o,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=q()??void 0;if(c.kind==="deny")return process.stdout.write(pn(c.reason)),await fe(r,{...i,deny_count:(i.deny_count??0)+1}),await V({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(st(c.context)),await fe(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await V({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&mr(r)){let u=ur(await yn(r),s,Date.now()),p=u.open?ww({mode:e.mode,enabled:e.difficulty,denyCapable:cd((await hr(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(pn(p.reason)),await fe(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await V({event:"difficulty_deny",session_id:r,cwd:l,project_key:d,detail:String(u.chain?.failures.length??0)}),0;if(p.kind==="warn")return process.stdout.write(st(p.context)),await fe(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await fe(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var wo,kw=_(()=>{"use strict";fr();be();fn();tt();De();at();Td();it();St();fi();mi();wo=3;a(bw,"decideGate");a(_w,"warnText");a(VO,"denyText");a(ww,"decideDifficultyGate");a(qO,"difficultyDenyText");a(zO,"runGuardGate")});var Sw={};te(Sw,{decideStopGate:()=>xw,runGuardStop:()=>JO});function xw(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function JO(){try{let e=le();if(e.mode==="off"||!e.stopGate)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await rt(n),i=(await z()).guard_signals?.[n]?.reviewed_at!==void 0;return xw({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:YO})),await fe(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var YO,Ew=_(()=>{"use strict";be();tt();at();it();St();a(xw,"decideStopGate");YO="[maind guard] Stop gate (strict, opt-in): this session edited files but no review ran. Run the review over the edit batches \u2014 attest_review_changes (one call, a server verdict; a clean pushed commit is also recorded), or codebase_review_changes then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";a(JO,"runGuardStop")});var Rw={};te(Rw,{capturedAtOf:()=>Tw,decideCapture:()=>Aw,runGuardCapture:()=>XO});function Tw(e,t){let n=e.guard_signals?.[t]?.captured_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}function Aw(e){if(e.stopHookActive||!pr(e.policy.capture))return null;let t=od(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:ud(t)}}async function XO(){try{let e=le();if(e.mode==="off"||!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!mr(n))return 0;let r=Aw({events:await yn(n),capturedAtMs:Tw(await z(),n),policy:await hr(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await Et(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await V({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var Iw=_(()=>{"use strict";fr();be();tt();at();it();fi();mi();a(Tw,"capturedAtOf");a(Aw,"decideCapture");a(XO,"runGuardCapture")});import{appendFile as ZO,mkdir as QO,readFile as Cw,rename as Ow,writeFile as Dw}from"node:fs/promises";import{homedir as Pw}from"node:os";import{join as Mw}from"node:path";function Lw(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},s=new Map,o=1/0,c=-1/0;for(let d of e){d.at<o&&(o=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=s.get(d.convention_id);(p===void 0||d.convention_version>p)&&s.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(o).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function _n(){return Mw(Pw(),".maind","gateway","attest-spool.jsonl")}async function Ad(e){let t=K();if(t===null)return!1;let n=await et("gateway_attest",{...e},{apiKey:t,deviceId:X(),projectKey:e.project_key??null,bridgeVersion:G,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function $w(e){try{await QO(Mw(Pw(),".maind","gateway"),{recursive:!0}),await ZO(_n(),JSON.stringify(e)+`
|
|
274
|
+
`,{mode:384}),await eD()}catch{}}async function eD(){try{let t=(await Cw(_n(),"utf8")).split(`
|
|
275
|
+
`).filter(r=>r.trim());if(t.length<=Nw)return;let n=`${_n()}.${process.pid}.tmp`;await Dw(n,t.slice(-Nw).join(`
|
|
263
276
|
`)+`
|
|
264
|
-
`,{mode:384}),await
|
|
265
|
-
`).filter(r=>r.trim())}catch{return}if(
|
|
277
|
+
`,{mode:384}),await Ow(n,_n())}catch{}}async function Fw(){let e;try{e=(await Cw(_n(),"utf8")).split(`
|
|
278
|
+
`).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await Ad(i)||(n=!0,t.push(r))}try{let r=`${_n()}.${process.pid}.tmp`;await Dw(r,t.length>0?t.join(`
|
|
266
279
|
`)+`
|
|
267
|
-
`:"",{mode:384}),await
|
|
268
|
-
`,384)}async function
|
|
269
|
-
`),2;let n=
|
|
270
|
-
`);continue}let o=
|
|
271
|
-
`);continue}if(!(
|
|
280
|
+
`:"",{mode:384}),await Ow(r,_n())}catch{}}var Nw,jw=_(()=>{"use strict";se();cr();Je();Nw=256;a(Lw,"aggregateWindow");a(_n,"attestSpoolPath");a(Ad,"postAttestation");a($w,"spoolAttestation");a(eD,"capSpool");a(Fw,"flushAttestSpool")});function hi(e=process.env,t=$e()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function vo(e=process.env,t=$e()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Uw(e,t=Qe()){let n={};try{let i=await ae(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await Q(t,JSON.stringify(r,null,2)+`
|
|
281
|
+
`,384)}async function Hw(e,t=Qe()){await Uw({gateway_mode:e},t)}async function Gw(e,t=Qe()){await Uw({gateway_attest:e},t)}function Bw(e=process.env,t=$e()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Rd=_(()=>{"use strict";Yn();Xe();a(hi,"resolveGatewayMode");a(vo,"resolveGatewayAttest");a(Uw,"writeGatewayConfigPatch");a(Hw,"writeGatewayMode");a(Gw,"writeGatewayAttest");a(Bw,"resolveShaProofMode")});function Kw(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,s=i.gateway_gate;if(typeof s!="object"||s===null)continue;let o=s;if(o.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let d=typeof i.severity=="string"&&tD.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 nD(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Vw(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)nD(s,e,t)&&(i===null||Ww[s.severity]>Ww[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function qw(e,t){let n=`${t.conventionId} v${t.conventionVersion}`,r=t.summary?` ("${t.summary}")`:"";return`maind gateway: tool '${e}' is denied by convention ${n}${r}. The call was not forwarded to the server. Exits: ask the user to run 'maind-mcp-bridge gateway mode warn' (observe instead of enforce), or to disable the convention for themselves (set_convention_pref) if it is not mandatory.`}var tD,Ww,Id=_(()=>{"use strict";tD=new Set(["required","recommended","info"]);a(Kw,"extractGatewayRules");Ww={required:2,recommended:1,info:0};a(nD,"ruleMatches");a(Vw,"decideToolCall");a(qw,"policyDenyText")});import{mkdirSync as rD,readFileSync as iD,renameSync as sD,writeFileSync as oD}from"node:fs";import{homedir as aD}from"node:os";import{dirname as cD,join as lD}from"node:path";function zw(){return lD(aD(),".maind","gateway","policy-cache.json")}function ko(e,t,n=new Date().toISOString()){try{let r={version:Nd,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=zw();rD(cD(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;oD(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),sD(s,i)}catch{}}function xo(e){try{let t=iD(zw(),"utf8"),n=JSON.parse(t);return n.version!==Nd||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Nd,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Nd,Cd=_(()=>{"use strict";Nd=1;a(zw,"policyCachePath");a(ko,"writePolicyCache");a(xo,"readPolicyCache")});function gi(e=process.env){let t=e.MAIND_MCP_URL??si,n=K();return{mcpUrl:t,keyFp:n?Gn(n):"anon"}}async function So(e=6e3){let t=K();if(t===null)return null;let n=null;try{n=q()}catch{n=null}let r=await et("get_conventions",{},{apiKey:t,deviceId:X(),projectKey:n,bridgeVersion:G,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Kw(i)}var Od=_(()=>{"use strict";Jt();se();cr();De();Je();Id();a(gi,"policyIdentity");a(So,"fetchGatewayRules")});function yi(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function dD(e){if(yi(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function uD(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:yi(e)?{action:"skip",reason:"already-wrapped"}:dD(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Yw(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],s=typeof e.env=="object"&&e.env!==null?e.env:void 0,o=s||t.env?{...s??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return o&&(c.env=o),c}function Jw(e){if(!yi(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function Xw(e){return Object.entries(e).map(([t,n])=>{let r=uD(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Zw=_(()=>{"use strict";a(yi,"isGatewayWrapped");a(dD,"isMaindProxyEntry");a(uD,"classifyServer");a(Yw,"wrapServerEntry");a(Jw,"unwrapServerEntry");a(Xw,"planRewrites")});var iv={};te(iv,{runGatewayInstall:()=>yD,runGatewayUninstall:()=>_D});import{existsSync as pD,readFileSync as fD}from"node:fs";import{homedir as mD}from"node:os";import{join as Qw}from"node:path";import{createInterface as hD}from"node:readline";function ev(e){let t={yes:!1,dryRun:!1};for(let n of e)if(n==="--yes")t.yes=!0;else if(n==="--dry-run")t.dryRun=!0;else return null;return t}function tv(){return[{label:"Claude Code (project .mcp.json)",path:Qw(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Qw(mD(),".claude.json")}]}async function nv(e){let t=hD({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>t.question(`${e} [y/N] `,r));return n.trim().toLowerCase()==="y"||n.trim().toLowerCase()==="yes"}finally{t.close()}}function rv(e){let t=gD(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function gD(e){try{return pD(e)?fD(e,"utf8"):null}catch{return null}}async function yD(e){let t=ev(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
282
|
+
`),2;let n=Me({entryPath:Le(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of tv()){let s=rv(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
283
|
+
`);continue}let o=Xw(s.servers);for(let c of o){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
284
|
+
`);continue}if(!(t.yes||await nv(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
272
285
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
273
286
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
274
|
-
`);continue}s.servers[c.key]=
|
|
275
|
-
`)}!
|
|
287
|
+
`);continue}s.servers[c.key]=Yw(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
288
|
+
`)}!t.dryRun&&o.some(c=>c.action==="wrap")&&await Q(i.path,JSON.stringify(s.raw,null,2)+`
|
|
276
289
|
`,384)}return process.stderr.write(r>0?`
|
|
277
|
-
${
|
|
290
|
+
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
278
291
|
`:`
|
|
279
292
|
Nothing to wrap.
|
|
280
|
-
`),0}async function
|
|
281
|
-
`),2;let n=0;for(let r of
|
|
282
|
-
`);continue}i.servers[o]=d,s=!0,n+=1,process.stderr.write(` ${
|
|
283
|
-
`)}!
|
|
293
|
+
`),0}async function _D(e){let t=ev(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
294
|
+
`),2;let n=0;for(let r of tv()){let i=rv(r.path);if(i===null)continue;let s=!1;for(let[o,c]of Object.entries(i.servers)){if(!yi(c)||!(t.yes||await nv(`Unwrap MCP server '${o}' in ${r.label}?`)))continue;let d=Jw(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${o} \u2014 wrapped shape unrecognized, left untouched
|
|
295
|
+
`);continue}i.servers[o]=d,s=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${o}
|
|
296
|
+
`)}!t.dryRun&&s&&await Q(r.path,JSON.stringify(i.raw,null,2)+`
|
|
284
297
|
`,384)}return process.stderr.write(n>0?`
|
|
285
|
-
${
|
|
298
|
+
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
286
299
|
`:`
|
|
287
300
|
Nothing wrapped \u2014 nothing to restore.
|
|
288
|
-
`),0}var
|
|
289
|
-
`),0}return
|
|
290
|
-
`),2):(await
|
|
291
|
-
`:
|
|
301
|
+
`),0}var sv=_(()=>{"use strict";Xe();qn();Zw();a(ev,"parseFlags");a(tv,"targets");a(nv,"confirm");a(rv,"loadConfig");a(gD,"readFileSafeSync");a(yD,"runGatewayInstall");a(_D,"runGatewayUninstall")});var ov={};te(ov,{runGatewayAttest:()=>wD,runGatewayMode:()=>bD,runGatewayPolicy:()=>xD});async function bD(e){let t=e[0];if(t===void 0){let n=hi(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
302
|
+
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
303
|
+
`),2):(await Hw(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
304
|
+
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
292
305
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
293
|
-
`)),0)}async function
|
|
306
|
+
`)),0)}async function wD(e){let t=e[0];if(t===void 0){let n=vo(),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)":""}.
|
|
294
307
|
`+(n?"":`maind: enable with 'gateway attest on' \u2014 reports observation windows (per-tool call/warn/deny COUNTERS, tool NAMES, convention citations, server label) to your maind account. Never tool arguments, results, paths, or prompts.
|
|
295
|
-
`)),0}return
|
|
296
|
-
`),2):(await
|
|
308
|
+
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
309
|
+
`),2):(await Gw(t==="on"),process.stdout.write(t==="on"?`maind: attestation reports ON. Each gateway now reports observation windows (tool-name counters + convention citations \u2014 never arguments) to your maind account, at gateway end and every 30 min.
|
|
297
310
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
298
|
-
`),0)}function
|
|
299
|
-
`;let
|
|
300
|
-
`}return
|
|
301
|
-
`):(
|
|
302
|
-
`))}let i=
|
|
311
|
+
`),0)}function vD(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
312
|
+
`;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
|
|
313
|
+
`}return t}function kD(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function xD(e){let t=e.includes("--refresh"),n=hi(),r=gi();if(t){let s=await So();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
314
|
+
`):(ko(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
|
|
315
|
+
`))}let i=xo(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
303
316
|
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
304
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
305
|
-
`),process.stdout.write(
|
|
306
|
-
`),0)}var
|
|
307
|
-
`,{mode:384})}catch{}}function
|
|
317
|
+
`),0):(process.stdout.write(`maind: policy from cache (${kD(i)}, ${r.mcpUrl}):
|
|
318
|
+
`),process.stdout.write(vD(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
|
|
319
|
+
`),0)}var av=_(()=>{"use strict";Rd();Cd();Od();a(bD,"runGatewayMode");a(wD,"runGatewayAttest");a(vD,"renderRules");a(kD,"cacheAge");a(xD,"runGatewayPolicy")});var pv={};te(pv,{gatewayEventsFile:()=>dv,parseGatewayArgs:()=>uv,runGateway:()=>ND});import{spawn as SD}from"node:child_process";import{appendFile as ED,mkdir as TD}from"node:fs/promises";import{homedir as cv}from"node:os";import{basename as AD,join as lv}from"node:path";import{createInterface as RD}from"node:readline";function dv(){return lv(cv(),".maind","gateway","events.jsonl")}async function ID(e){try{let t=dv();await TD(lv(cv(),".maind","gateway"),{recursive:!0}),await ED(t,JSON.stringify(e)+`
|
|
320
|
+
`,{mode:384})}catch{}}function uv(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let s=e[r+1];if(!s)return null;t.add(s),r+=2;continue}if(i==="--label"){let s=e[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=e[r+1];return s?{denyTools:t,label:n,command:s,args:e.slice(r+2)}:null}return null}return null}async function ND(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:R}=await Promise.resolve().then(()=>(sv(),iv));return e[0]==="install"?S(e.slice(1)):R(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:S,runGatewayMode:R,runGatewayPolicy:D}=await Promise.resolve().then(()=>(av(),ov));return e[0]==="mode"?R(e.slice(1)):e[0]==="attest"?S(e.slice(1)):D(e.slice(1))}let t=uv(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
308
321
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
309
322
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
310
323
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -314,55 +327,55 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
314
327
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
315
328
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
316
329
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
317
|
-
`),2;let{denyTools:n,label:r,command:i,args:s}=
|
|
318
|
-
`),process.exitCode=1});let
|
|
319
|
-
`),g(
|
|
320
|
-
`),g(
|
|
321
|
-
`),g(
|
|
322
|
-
`),g(
|
|
323
|
-
`)}),
|
|
324
|
-
`),await
|
|
325
|
-
`),o.warned[s]=c.current,await
|
|
326
|
-
`).trim();if(r=[],s.length!==0)try{n.push(JSON.parse(s))}catch{}},"flush");for(let s of
|
|
327
|
-
`)){let o=s.endsWith("\r")?s.slice(0,-1):s;if(o===""){i();continue}o.startsWith("data:")&&r.push(o.slice(5).replace(/^\s/,""))}return i(),n}a(
|
|
328
|
-
`);let g=r.params?.name;process.stdout.write(
|
|
329
|
-
`);return}i=
|
|
330
|
+
`),2;let{denyTools:n,label:r,command:i,args:s}=t,o=r??AD(i),c=hi(),l=Bw(),d=l==="off"?null:bi(),u=c==="off"?[]:xo(gi())?.rules??[];c!=="off"&&So().then(S=>{S!==null&&(u=S,ko(gi(),S))}).catch(()=>{});let p=[],h=vo()&&K()!==null&&c!=="off",m=null;try{m=q()}catch{m=null}let g=a(S=>{ID(S),h&&p.push(S)},"record"),y=a(async()=>{if(!h)return;let S=Lw(p.splice(0),c,o,m);S!==null&&(await Ad(S)||await $w(S))},"attestAndReset");h&&Fw().catch(()=>{});let v=setInterval(()=>{y()},30*6e4);v.unref();let w=SD(i,s,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(S)}
|
|
331
|
+
`),process.exitCode=1});let b=RD({input:process.stdin,terminal:!1});b.on("line",S=>{let R=zd(S);if(R.kind==="request"&&R.method==="tools/call"&&R.toolName){if(n.has(R.toolName)&&R.id!==void 0){process.stdout.write(wn(R.id,R.toolName)+`
|
|
332
|
+
`),g(Ao("deny",o,R.toolName,Date.now()));return}let D=Vw(R.toolName,o,u,c);if(D.kind==="deny"&&R.id!==void 0){process.stdout.write(wn(R.id,R.toolName,qw(R.toolName,D.rule))+`
|
|
333
|
+
`),g(Ro("policy_deny",o,R.toolName,Date.now(),D.rule.conventionId,D.rule.conventionVersion));return}(D.kind==="warn"||D.kind==="deny")&&g(Ro("policy_warn",o,R.toolName,Date.now(),D.rule.conventionId,D.rule.conventionVersion));let F=wi(S,d);if(F.length>0){let H=F.find(j=>j.verdict==="fabricated");if(H!==void 0&&l==="enforce"&&c==="enforce"&&R.id!==void 0&&H!==void 0&&R.id!==void 0){process.stdout.write(wn(R.id,R.toolName,vn(H,!0))+`
|
|
334
|
+
`),g(Io("sha_deny",o,R.toolName,Date.now()));return}let N=H??F[0];process.stderr.write(`[maind gateway] ${vn(N,!1)}
|
|
335
|
+
`),g(Io("sha_warn",o,R.toolName,Date.now()))}g(Ao("tool_call",o,R.toolName,Date.now()))}w.stdin.write(S+`
|
|
336
|
+
`)}),b.on("close",()=>{w.stdin.end()});let k=await new Promise(S=>{w.on("exit",(R,D)=>{S(R??(D?1:0))})});return clearInterval(v),await y(),k}var fv=_(()=>{"use strict";No();jw();Rd();Id();Co();Cd();Od();se();De();a(dv,"gatewayEventsFile");a(ID,"logEvent");a(uv,"parseGatewayArgs");a(ND,"runGateway")});var jd={};te(jd,{MAX_ENTRIES:()=>Dd,TTL_MS:()=>Ld,crossSessionDir:()=>$d,decideCrossSession:()=>gv,parseSessionDb:()=>hv,pruneDb:()=>Fd,runGuardCrossCheck:()=>jD,runGuardCrossObserve:()=>FD,staleReason:()=>Pd});import{mkdir as CD,readFile as OD,readdir as DD,stat as mv,unlink as PD,writeFile as MD}from"node:fs/promises";import{homedir as LD}from"node:os";import{join as Md}from"node:path";function $d(){return Md(LD(),".maind","cross-session")}function hv(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[s,o]of Object.entries(n.files)){if(typeof o!="object"||o===null)continue;let c=o;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[s]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[s,o]of Object.entries(n.warned))typeof o=="number"&&Number.isFinite(o)&&(i[s]=o);return{files:r,warned:i}}function Fd(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Ld);return n.length>Dd&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-Dd)),{files:Object.fromEntries(n),warned:e.warned}}function gv(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Pd(e,t){return`Cross-session guard: '${e}' changed on disk after this session last read it (mtime ${Math.floor(t.current/1e3)} > recorded ${Math.floor(t.baseline/1e3)}). Likely a parallel session, an editor, or git (checkout/pull). Re-read the file, reconcile with the external change, then retry.`}async function yv(e){let t=$d();return await CD(t,{recursive:!0}),Md(t,`${e}.json`)}async function _v(e,t){try{let n=await OD(await yv(e),"utf8");return Fd(hv(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function bv(e,t){try{await MD(await yv(e),JSON.stringify(t),{mode:384})}catch{}}async function $D(e){try{let t=$d();for(let n of await DD(t)){if(!n.endsWith(".json"))continue;let r=Md(t,n),i=await mv(r).catch(()=>null);i&&e-i.mtimeMs>Ld&&await PD(r).catch(()=>{})}}catch{}}async function wv(e){try{return(await mv(e)).mtimeMs}catch{return}}async function FD(e,t=Date.now()){try{if(le().mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=Fe(r);if(!i||!s)return 0;let o=await wv(s);if(o===void 0)return 0;let c=await _v(i,t);return c.files[s]={m:o,t},delete c.warned[s],await bv(i,Fd(c,t)),await $D(t),0}catch{return 0}}async function jD(e,t=Date.now()){try{let n=le();if(n.mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=Fe(r);if(!i||!s)return 0;let o=await _v(i,t),c=gv(o.files[s]?.m,await wv(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(pn(Pd(s,c))+`
|
|
337
|
+
`),await V({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(o.warned[s]===c.current||(process.stdout.write(st(Pd(s,c))+`
|
|
338
|
+
`),o.warned[s]=c.current,await bv(i,o),await V({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var Ld,Dd,Ud=_(()=>{"use strict";be();fn();at();it();Ld=48*3600*1e3,Dd=500;a($d,"crossSessionDir");a(hv,"parseSessionDb");a(Fd,"pruneDb");a(gv,"decideCrossSession");a(Pd,"staleReason");a(yv,"dbPath");a(_v,"loadDb");a(bv,"saveDb");a($D,"sweepStaleSessionFiles");a(wv,"fileMtime");a(FD,"runGuardCrossObserve");a(jD,"runGuardCrossCheck")});var Hd={};te(Hd,{INDEX_REFRESH_WORKER:()=>vv,acquireLock:()=>Us,releaseLock:()=>Zr,runIndexRefreshWorker:()=>KD,runOnIndexRefresh:()=>WD});import{spawn as UD}from"node:child_process";import{existsSync as HD}from"node:fs";import{join as GD}from"node:path";function BD(e){return GD(e,".maind","code-index.sqlite")}async function WD(){try{let e=await W(),t=pe(typeof e.cwd=="string"?e.cwd:process.cwd());if(!HD(BD(t))||!Us(t))return 0;let n=process.argv[1];if(n===void 0)return Zr(t),0;UD(process.execPath,[n,vv,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function KD(){let e=process.argv[3]??pe();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(cl(),iy)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Zr(e)}return 0}var vv,Gd=_(()=>{"use strict";be();sn();ll();vv="index-refresh-run";a(BD,"indexDbPath");a(WD,"runOnIndexRefresh");a(KD,"runIndexRefreshWorker")});import{randomUUID as VD}from"node:crypto";import{createInterface as B0}from"node:readline";var xv=[["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 Sv(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of xv)if(t.includes(n))return r;return null}a(Sv,"mapClientInfoNameToFamily");function qd(e){let t;try{t=JSON.parse(e)}catch{return null}if(!To(t)||t.method!=="initialize")return null;let n=t.params;if(!To(n))return null;let r=n.clientInfo;if(!To(r))return null;let i=r.name,s=Sv(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(qd,"tryExtractInitializeClient");function To(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(To,"isRecord");No();Co();function Oo(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let s=JSON.parse(t);return Array.isArray(s)?s:[s]}catch{return[]}let n=[],r=[],i=a(()=>{if(r.length===0)return;let s=r.join(`
|
|
339
|
+
`).trim();if(r=[],s.length!==0)try{n.push(JSON.parse(s))}catch{}},"flush");for(let s of t.split(`
|
|
340
|
+
`)){let o=s.endsWith("\r")?s.slice(0,-1):s;if(o===""){i();continue}o.startsWith("data:")&&r.push(o.slice(5).replace(/^\s/,""))}return i(),n}a(Oo,"rpcMessagesOf");function eu(e,t){for(let n of Oo(e)){if(typeof n!="object"||n===null)continue;let r=n;if(r.id!==t)continue;if(typeof r.error=="object"&&r.error!==null){let c=r.error;return{kind:"rpc_error",code:typeof c.code=="number"?c.code:-32603,message:typeof c.message=="string"?c.message:""}}let i=typeof r.result=="object"&&r.result!==null?r.result:{},o=(Array.isArray(i.content)?i.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:i.isError===!0,text:o?.text??""}}return null}a(eu,"parseCloudToolResponse");Jt();var W0="https://mcp.maind.dev/mcp",Gr=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{a(this,"BridgeReauthNeeded")}},ms=class{static{a(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;pendingFrame=null;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=Gn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=K0(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=V0(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.onConnectionOutcome=t.onConnectionOutcome??null;let s=t.carry??null;s!==null&&(this.initFrame=s.initFrame,this.clientFamily===null&&(this.clientFamily=s.clientFamily),this.clientVersion===null&&(this.clientVersion=s.clientVersion),this.replayFrame=s.pendingFrame),this.shaRepoRoot=bi(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??W0}async run(t=Mc()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r)return;let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let u=qd(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Hr(t)&&(this.initFrame=t);let r=Y0(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=wi(t,this.shaRepoRoot);if(u.length>0){let p=u.find(m=>m.verdict==="fabricated"),h=p??u[0];if(p!==void 0&&Zd(p)&&r.id!==null){let m=vn(p,!0);process.stderr.write(`[maind] ${m}
|
|
341
|
+
`);let g=r.params?.name;process.stdout.write(wn(r.id,typeof g=="string"?g:"unknown",m)+`
|
|
342
|
+
`);return}i=vn(h,!1),process.stderr.write(`[maind] ${i}
|
|
330
343
|
`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let u=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(u+`
|
|
331
|
-
`);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!
|
|
332
|
-
`);return}if(
|
|
333
|
-
`);return}if(i!==null){let u=d.startsWith("text/event-stream")?await
|
|
334
|
-
`);return}if(d.startsWith("text/event-stream"))await
|
|
335
|
-
`)}}}async handle401(
|
|
336
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
344
|
+
`);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!Hr(t)&&await this.recoverSession();let o=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:o,body:t})}catch(u){let p=ps(t);if(this.serveInitializeFromCache(t,p))return;fs(p,-32603,`bridge network error: ${$h(u)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.ok&&!this.connectionOkRecorded&&(this.connectionOkRecorded=!0,this.recordOutcome("ok",null)),c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!Hr(t)){let u=await c.text().catch(()=>"");if(Lh(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=ps(t);fs(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=ps(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;fs(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 Dc(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
345
|
+
`);return}if(Hr(t)){let u=d.startsWith("text/event-stream")?await Dc(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
346
|
+
`);return}if(i!==null){let u=d.startsWith("text/event-stream")?await Dc(c):await c.text(),p=z0(u,i);p.trim().length>0&&process.stdout.write(p+`
|
|
347
|
+
`);return}if(d.startsWith("text/event-stream"))await q0(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
348
|
+
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new Gr(X0(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let o=ps(n);fs(o,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(t,n){try{this.onConnectionOutcome?.(t,n)}catch{}}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),s=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return Z0(s)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,s=await this.postCloudToolCall(t,n,i);if(s.kind!=="session_lost")return s;if(!await this.recoverSession())return{kind:"http_error",status:404,body:s.body.slice(0,500)};let o=await this.postCloudToolCall(t,n,i);return o.kind==="session_lost"?{kind:"http_error",status:404,body:o.body.slice(0,500)}:o}async postCloudToolCall(t,n,r){this.cloudFrameId+=1;let i=`maind-bridge-${this.cloudFrameId}`,s=JSON.stringify({jsonrpc:"2.0",id:i,method:"tools/call",params:{name:t,arguments:n}});try{let o=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:s,signal:AbortSignal.timeout(r)}),c=o.headers.get("mcp-session-id");c&&c!==this.sessionId&&(this.sessionId=c);let l=await o.text();return o.status===404&&Lh(l)?{kind:"session_lost",body:l}:o.ok?eu(l,i)??{kind:"transport_error",message:`the response carried no answer to ${i}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:o.status,body:l.slice(0,500)}}catch(o){return{kind:"transport_error",message:$h(o),timedOut:J0(o)}}}buildHeaders(t){let n={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-device-id":this.deviceId,"x-maind-bridge-version":this.bridgeVersion};return this.clientFamily!==null&&(n["x-maind-client-family"]=this.clientFamily),this.clientVersion!==null&&(n["x-maind-client-version"]=this.clientVersion),this.projectKey!==null&&(n["x-maind-project-key"]=this.projectKey),t&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let t;try{t=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=t.headers.get("mcp-session-id");if(await t.text().catch(()=>""),!t.ok||!n)return!1;this.sessionId=n;try{await(await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})})).text().catch(()=>"")}catch{}return!0}getRepoRoot(){return this.repoRoot===null&&(this.repoRoot=Ye()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Dh(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Hr(t))return!1;let r=Ph(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Mh(n,r)+`
|
|
349
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${us(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Mc(){return B0({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}a(Mc,"stdinLines");function K0(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}a(K0,"normalizeClientFamily");function V0(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}a(V0,"normalizeClientVersion");async function q0(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=a(()=>{if(i.length===0)return;let o=i.join(`
|
|
337
350
|
`).trim();i=[],o.length>0&&process.stdout.write(o+`
|
|
338
|
-
`)},"flushEvent");try{for(;;){let{value:o,done:c}=await
|
|
339
|
-
`))!==-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(
|
|
340
|
-
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await
|
|
351
|
+
`)},"flushEvent");try{for(;;){let{value:o,done:c}=await t.read();if(c)break;r+=n.decode(o,{stream:!0});let l;for(;(l=r.indexOf(`
|
|
352
|
+
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){s();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{s()}}a(q0,"pipeSseToStdout");function z0(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return e;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?e:(r.content.push({type:"text",text:`[maind] ${t}`}),JSON.stringify(n))}catch{return e}}a(z0,"appendNoteToToolResult");function Y0(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}a(Y0,"parseRpc");async function Dc(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=[],o=a(()=>{if(s.length===0)return;let c=s.join(`
|
|
353
|
+
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
341
354
|
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){o();continue}p.startsWith(":")||p.startsWith("data:")&&s.push(p.slice(5).replace(/^\s/,""))}}}finally{o()}return i.join(`
|
|
342
|
-
`)}a(
|
|
343
|
-
`)}a(
|
|
344
|
-
`),null));if(p){if(p.status==="approved")return
|
|
345
|
-
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return
|
|
346
|
-
`),null;if(p.status==="expired"||p.status==="consumed")return
|
|
347
|
-
`),null}}return
|
|
348
|
-
`),null}a(
|
|
355
|
+
`)}a(Dc,"collectSseText");function ps(e){try{return JSON.parse(e).id??null}catch{return null}}a(ps,"tryExtractId");function Hr(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}a(Hr,"isInitializeRequest");function Lh(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}a(Lh,"isSessionLossBody");function $h(e){return e instanceof Error?e.message:String(e)}a($h,"stringifyErr");function J0(e){return e?.name==="TimeoutError"}a(J0,"isTimeoutError");function fs(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
356
|
+
`)}a(fs,"emitJsonRpcError");function X0(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}a(X0,"extractHint");function Z0(e){try{let t=Oo(e);if(t.length===0)return null;let r=t[t.length-1]?.result?.content?.[0]?.text;return typeof r!="string"?null:JSON.parse(r)}catch{return null}}a(Z0,"parsePresenceToolResult");se();se();Wn();import{spawn as lT}from"node:child_process";import{platform as dT}from"node:os";async function Kn(e,t=process.stderr){let n=Wr(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=gs(e),o=`mcp-bridge-${s.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:o,meta:s})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await mT(l.verification_uri_complete).catch(()=>{}),fT(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await pT(u);let p=await uT(i,l.device_code).catch(h=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(h)}
|
|
357
|
+
`),null));if(p){if(p.status==="approved")return Zt(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
358
|
+
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
359
|
+
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
360
|
+
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
361
|
+
`),null}a(Kn,"runDeviceFlow");async function uT(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}a(uT,"pollOnce");function pT(e){return new Promise(t=>setTimeout(t,e))}a(pT,"sleep");function fT(e,t){let n=[""," \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"," \u2502 \u2502"," \u2502 maind-mcp-bridge \u2014 first-time setup \u2502"," \u2502 \u2502"," \u2502 Approve this bridge to bind it to your maind account: \u2502"," \u2502 \u2502",` \u2502 Open: ${Gh(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Gh(e.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(e.expires_in/60)} minutes)`.padEnd(67)+"\u2502"," \u2502 \u2502"," \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",""];t.write(n.join(`
|
|
349
362
|
`)+`
|
|
350
|
-
`)}a(
|
|
351
|
-
`))}a(
|
|
352
|
-
`;let
|
|
363
|
+
`)}a(fT,"printAuthInstructions");function Gh(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}a(Gh,"pad");async function mT(e){let t,n;switch(dT()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let s=lT(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}a(mT,"openExternalBrowser");jc();Je();De();Je();import*as _y from"node:os";function qh(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Pe("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Pe("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Pe("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Pe("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Pe("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new Pe(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}a(qh,"parseInstallFlags");var Pe=class extends Error{static{a(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function zh(){let e=["","@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(e.join(`
|
|
364
|
+
`))}a(zh,"printInstallHelp");var _s=class{static{a(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
|
|
365
|
+
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),s=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),o=a((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(s)} |`,l=[];l.push(`| ${o(t[0],n)} | ${o(t[1],r)} | ${o(t[2],i)} | ${o(t[3],s)} |`),l.push(c);for(let d of this.results)l.push(`| ${o(d.target,n)} | ${o(d.action,r)} | ${o(d.status,i)} | ${o(d.detail??"",s)} |`);return l.join(`
|
|
353
366
|
`)+`
|
|
354
|
-
`}print(
|
|
355
|
-
`),
|
|
367
|
+
`}print(t){let n=this.summary();t.write(`
|
|
368
|
+
`),t.write(this.toMarkdownTable()),t.write(`
|
|
356
369
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
357
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as
|
|
370
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Yh from"node:fs/promises";import*as _t from"node:path";import*as Jh from"node:readline";var RT=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function Xh(e){let t=_t.resolve(e),n=t;for(;;){if(await Qh(n))return n;let r=_t.dirname(n);if(r===n)return t;n=r}}a(Xh,"detectProjectRoot");async function Zh(e){let n=_t.resolve(e),r=[];for(;;){await Qh(n)&&r.push(n);let i=_t.dirname(n);if(i===n)break;n=i}return r}a(Zh,"findAllProjectRoots");async function Qh(e){for(let t of RT)try{return await Yh.access(_t.join(e,t)),!0}catch{}return!1}a(Qh,"hasAnyMarker");async function eg(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
358
371
|
Multiple project roots found between cwd and the filesystem root:
|
|
359
|
-
`),
|
|
372
|
+
`),e.forEach((s,o)=>{process.stdout.write(` [${o+1}] ${s}
|
|
360
373
|
`)}),process.stdout.write(`
|
|
361
|
-
Which one should receive the MCP config and preamble files? [1-${
|
|
362
|
-
`),null):
|
|
363
|
-
`;if(n)return{target:
|
|
374
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Jh.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(s=>{n.question("",o=>s(o.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
|
|
375
|
+
`),null):e[i-1]}a(eg,"disambiguateProjectRoot");Uc();qn();Xe();var Kr="maind";async function dg(e,t,n=!1){if(e.kind!=="json")return{target:e.key,action:"merge",status:"failed",detail:`expected json target, got ${e.kind}`};let r;try{r=await ae(e.path)}catch(u){return Gc(e,"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 Gc(e,"parse",u)}}if(!bt(i))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let o=e.key==="claude-code-user"&&MT(i),c,l=!1;if(o){let u=i[Kr];bt(u)&&lg(u,t)&&(l=!0),c={...i,[Kr]:cg(u,t)}}else{let u=bt(i.mcpServers)?i.mcpServers:{},p=u[Kr];bt(p)&&lg(p,t)&&(l=!0),c={...i,mcpServers:{...u,[Kr]:cg(p,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let d=JSON.stringify(c,null,2)+`
|
|
376
|
+
`;if(n)return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await Q(e.path,d)}catch(u){return Gc(e,"write",u)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}a(dg,"mergeJsonConfig");function cg(e,t){let n=bt(e)&&bt(e.env)?e.env:{},r={...t.env};for(let[i,s]of Object.entries(n))!(i in r)&&typeof s=="string"&&(r[i]=s);return{command:t.command,args:[...t.args],env:r}}a(cg,"mergeEntry");function MT(e){return!("mcpServers"in e||!(Kr in e))}a(MT,"hasRootShape");function lg(e,t){if(!bt(e)||e.command!==t.command||!LT(e.args,t.args)||!bt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}a(lg,"serverEntriesEqual");function LT(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}a(LT,"arrayEquals");function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(bt,"isObject");function Gc(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Gc,"failed");Xe();import{parse as $T,stringify as FT}from"smol-toml";async function ug(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await ae(e.path)}catch(g){return Ss(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=$T(r);if(!en(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return Ss(e,"parse",g)}}let o=en(i.mcp_servers)?i.mcp_servers:{},c=o.maind;if(en(c)&&jT(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=en(c)&&en(c.env)?c.env:{},d={...t.env};for(let[g,y]of Object.entries(l))!(g in d)&&typeof y=="string"&&(d[g]=y);let u={command:t.command,args:[...t.args],env:d},p={...i,mcp_servers:{...o,maind:u}},h;try{h=FT(p),h.endsWith(`
|
|
364
377
|
`)||(h+=`
|
|
365
|
-
`)}catch(g){return
|
|
378
|
+
`)}catch(g){return Ss(e,"write",g)}let m=h.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await Q(e.path,h)}catch(g){return Ss(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}a(ug,"mergeTomlConfig");function jT(e,t){if(!en(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!en(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}a(jT,"tomlServerEntryEqual");function en(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(en,"isObject");function Ss(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Ss,"failed");import*as Ze from"node:path";var UT="__STACK__";var HT="__INTENT__";var Bc="https://mcp.maind.dev/mcp",GT=`?stack=${UT}&intent=${HT}`;function BT(e,t){let n=new URLSearchParams;t.stack&&t.stack.length>0&&n.set("stack",t.stack.join(",")),t.intent&&n.set("intent",t.intent),t.project&&n.set("project",t.project),t.verbosity&&n.set("verbosity",t.verbosity);let r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e}a(BT,"buildStackAwareEndpoint");var kH=BT(Bc,{stack:["nextjs","supabase"],intent:"mixed"}),qr=`## maind MCP integration \u2014 Mandatory consultation
|
|
366
379
|
|
|
367
380
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
368
381
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -431,10 +444,10 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
431
444
|
If no path is discoverable, provide a guided fallback:
|
|
432
445
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
433
446
|
|
|
434
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
447
|
+
Full tool set + provenance via \`get_conventions\`.`;function WT(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
435
448
|
|
|
436
449
|
- My stack: \`__STACK__\`
|
|
437
|
-
- MCP endpoint: \`${
|
|
450
|
+
- MCP endpoint: \`${e}\`
|
|
438
451
|
|
|
439
452
|
Please set this up strictly in order. Do not skip steps silently.
|
|
440
453
|
|
|
@@ -483,7 +496,7 @@ bridge creates and stores a device-bound key during first launch.
|
|
|
483
496
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
484
497
|
"env": {
|
|
485
498
|
"MAIND_CLIENT_FAMILY": "claude-code",
|
|
486
|
-
"MAIND_MCP_URL": "${
|
|
499
|
+
"MAIND_MCP_URL": "${e}"
|
|
487
500
|
}
|
|
488
501
|
}
|
|
489
502
|
}
|
|
@@ -496,7 +509,7 @@ bridge creates and stores a device-bound key during first launch.
|
|
|
496
509
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
497
510
|
"env": {
|
|
498
511
|
"MAIND_CLIENT_FAMILY": "claude-code",
|
|
499
|
-
"MAIND_MCP_URL": "${
|
|
512
|
+
"MAIND_MCP_URL": "${e}"
|
|
500
513
|
}
|
|
501
514
|
}
|
|
502
515
|
}
|
|
@@ -509,7 +522,7 @@ bridge creates and stores a device-bound key during first launch.
|
|
|
509
522
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
510
523
|
"env": {
|
|
511
524
|
"MAIND_CLIENT_FAMILY": "claude-desktop",
|
|
512
|
-
"MAIND_MCP_URL": "${
|
|
525
|
+
"MAIND_MCP_URL": "${e}"
|
|
513
526
|
}
|
|
514
527
|
}
|
|
515
528
|
}
|
|
@@ -521,7 +534,7 @@ command = "npx"
|
|
|
521
534
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
522
535
|
[mcp_servers.maind.env]
|
|
523
536
|
MAIND_CLIENT_FAMILY = "codex"
|
|
524
|
-
MAIND_MCP_URL = "${
|
|
537
|
+
MAIND_MCP_URL = "${e}"
|
|
525
538
|
|
|
526
539
|
# GitHub Copilot / VS Code workspace MCP (PROJECT_ROOT/.mcp.json)
|
|
527
540
|
{
|
|
@@ -531,7 +544,7 @@ MAIND_MCP_URL = "${t}"
|
|
|
531
544
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
532
545
|
"env": {
|
|
533
546
|
"MAIND_CLIENT_FAMILY": "copilot",
|
|
534
|
-
"MAIND_MCP_URL": "${
|
|
547
|
+
"MAIND_MCP_URL": "${e}"
|
|
535
548
|
}
|
|
536
549
|
}
|
|
537
550
|
}
|
|
@@ -545,7 +558,7 @@ MAIND_MCP_URL = "${t}"
|
|
|
545
558
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
546
559
|
"env": {
|
|
547
560
|
"MAIND_CLIENT_FAMILY": "cursor",
|
|
548
|
-
"MAIND_MCP_URL": "${
|
|
561
|
+
"MAIND_MCP_URL": "${e}"
|
|
549
562
|
}
|
|
550
563
|
}
|
|
551
564
|
}
|
|
@@ -559,7 +572,7 @@ MAIND_MCP_URL = "${t}"
|
|
|
559
572
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
560
573
|
"env": {
|
|
561
574
|
"MAIND_CLIENT_FAMILY": "windsurf",
|
|
562
|
-
"MAIND_MCP_URL": "${
|
|
575
|
+
"MAIND_MCP_URL": "${e}"
|
|
563
576
|
}
|
|
564
577
|
}
|
|
565
578
|
}
|
|
@@ -571,7 +584,7 @@ MAIND_MCP_URL = "${t}"
|
|
|
571
584
|
"command": "npx",
|
|
572
585
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
573
586
|
"env": {
|
|
574
|
-
"MAIND_MCP_URL": "${
|
|
587
|
+
"MAIND_MCP_URL": "${e}"
|
|
575
588
|
}
|
|
576
589
|
}
|
|
577
590
|
|
|
@@ -615,7 +628,7 @@ not share a session across those framed messages.
|
|
|
615
628
|
PowerShell 5.1-compatible example:
|
|
616
629
|
|
|
617
630
|
\`\`\`powershell
|
|
618
|
-
$env:MAIND_MCP_URL = "${
|
|
631
|
+
$env:MAIND_MCP_URL = "${e}"
|
|
619
632
|
$i1 = '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"setup-verify","version":"1.0"}}}'
|
|
620
633
|
$i2 = '{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}'
|
|
621
634
|
$i3 = '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_session_briefing","arguments":{"tools":["search_lessons"],"stack":["__STACK__"]}}}'
|
|
@@ -627,12 +640,12 @@ written config.
|
|
|
627
640
|
|
|
628
641
|
--- Preamble block ---
|
|
629
642
|
|
|
630
|
-
${
|
|
643
|
+
${qr}`}a(WT,"buildAiPromptBody");function Vr(e,t,n){let r=n?`
|
|
631
644
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
632
645
|
set -euo pipefail
|
|
633
646
|
|
|
634
|
-
CONFIG_FILE="${
|
|
635
|
-
MAIND_MCP_URL="${
|
|
647
|
+
CONFIG_FILE="${e}"
|
|
648
|
+
MAIND_MCP_URL="${t}"${r}
|
|
636
649
|
|
|
637
650
|
mkdir -p "$(dirname "$CONFIG_FILE")"
|
|
638
651
|
|
|
@@ -662,11 +675,11 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
662
675
|
config.mcpServers.maind = server;
|
|
663
676
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
664
677
|
console.log("WROTE " + file);
|
|
665
|
-
NODE`}a(
|
|
678
|
+
NODE`}a(Vr,"buildJsonConfigInstaller");function KT(e){return`#!/usr/bin/env bash
|
|
666
679
|
set -euo pipefail
|
|
667
680
|
|
|
668
681
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
669
|
-
MAIND_MCP_URL="${
|
|
682
|
+
MAIND_MCP_URL="${e}"
|
|
670
683
|
MAIND_CLIENT_FAMILY="codex"
|
|
671
684
|
|
|
672
685
|
mkdir -p "$(dirname "$CONFIG_FILE")"
|
|
@@ -715,46 +728,46 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
715
728
|
|
|
716
729
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
717
730
|
console.log("WROTE " + file);
|
|
718
|
-
NODE`}a(
|
|
731
|
+
NODE`}a(KT,"buildCodexTomlInstaller");function VT(e=Bc){let t=`${e}${GT}`;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:WT(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
|
|
719
732
|
"mcpServers": {
|
|
720
733
|
"maind": {
|
|
721
734
|
"command": "npx",
|
|
722
735
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
723
736
|
"env": {
|
|
724
737
|
"MAIND_CLIENT_FAMILY": "claude-code",
|
|
725
|
-
"MAIND_MCP_URL": "${
|
|
738
|
+
"MAIND_MCP_URL": "${t}"
|
|
726
739
|
}
|
|
727
740
|
}
|
|
728
741
|
}
|
|
729
|
-
}`,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
|
|
742
|
+
}`,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:Vr(".mcp.json",t,"claude-code")}]},{id:"claude-desktop",label:"Claude Desktop",description:"Browser-pairing desktop config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/Library/Application Support/Claude/claude_desktop_config.json",lang:"json",template:`{
|
|
730
743
|
"mcpServers": {
|
|
731
744
|
"maind": {
|
|
732
745
|
"command": "npx",
|
|
733
746
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
734
747
|
"env": {
|
|
735
748
|
"MAIND_CLIENT_FAMILY": "claude-desktop",
|
|
736
|
-
"MAIND_MCP_URL": "${
|
|
749
|
+
"MAIND_MCP_URL": "${t}"
|
|
737
750
|
}
|
|
738
751
|
}
|
|
739
752
|
}
|
|
740
|
-
}`,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
|
|
753
|
+
}`,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:Vr("$HOME/Library/Application Support/Claude/claude_desktop_config.json",t,"claude-desktop")}]},{id:"codex",label:"Codex CLI",description:"Browser-pairing Codex config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/.codex/config.toml",lang:"toml",template:`[mcp_servers.maind]
|
|
741
754
|
command = "npx"
|
|
742
755
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
743
756
|
|
|
744
757
|
[mcp_servers.maind.env]
|
|
745
758
|
MAIND_CLIENT_FAMILY = "codex"
|
|
746
|
-
MAIND_MCP_URL = "${
|
|
759
|
+
MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:KT(t)}]},{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:`{
|
|
747
760
|
"mcpServers": {
|
|
748
761
|
"maind": {
|
|
749
762
|
"command": "npx",
|
|
750
763
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
751
764
|
"env": {
|
|
752
765
|
"MAIND_CLIENT_FAMILY": "copilot",
|
|
753
|
-
"MAIND_MCP_URL": "${
|
|
766
|
+
"MAIND_MCP_URL": "${t}"
|
|
754
767
|
}
|
|
755
768
|
}
|
|
756
769
|
}
|
|
757
|
-
}`,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
|
|
770
|
+
}`,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:Vr(".mcp.json",t,"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
|
|
758
771
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
759
772
|
# CLAUDE.md (Claude Code)
|
|
760
773
|
# AGENTS.md (Codex, Windsurf, newer Cursor \u2014 cross-agent standard)
|
|
@@ -771,7 +784,7 @@ set -e
|
|
|
771
784
|
|
|
772
785
|
read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
|
|
773
786
|
|
|
774
|
-
${
|
|
787
|
+
${qr}
|
|
775
788
|
MAIND_PREAMBLE_EOF
|
|
776
789
|
|
|
777
790
|
mkdir -p .github
|
|
@@ -816,22 +829,22 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
816
829
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
817
830
|
"env": {
|
|
818
831
|
"MAIND_CLIENT_FAMILY": "cursor",
|
|
819
|
-
"MAIND_MCP_URL": "${
|
|
832
|
+
"MAIND_MCP_URL": "${t}"
|
|
820
833
|
}
|
|
821
834
|
}
|
|
822
835
|
}
|
|
823
|
-
}`,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
|
|
836
|
+
}`,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:Vr("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Windsurf",description:"Browser-pairing Windsurf config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/.codeium/windsurf/mcp_config.json",lang:"json",template:`{
|
|
824
837
|
"mcpServers": {
|
|
825
838
|
"maind": {
|
|
826
839
|
"command": "npx",
|
|
827
840
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
828
841
|
"env": {
|
|
829
842
|
"MAIND_CLIENT_FAMILY": "windsurf",
|
|
830
|
-
"MAIND_MCP_URL": "${
|
|
843
|
+
"MAIND_MCP_URL": "${t}"
|
|
831
844
|
}
|
|
832
845
|
}
|
|
833
846
|
}
|
|
834
|
-
}`,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
|
|
847
|
+
}`,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:Vr("$HOME/.codeium/windsurf/mcp_config.json",t,"windsurf")}]},{id:"langchain-ts",label:"LangChain / LangGraph (TS)",description:"Bridge-backed stdio MCP client. The bridge opens browser pairing, creates a fresh device-bound key, and forwards calls to the stack-aware maind endpoint. Replace `__STACK__` with your stack slugs.",filename:"agent.ts",lang:"ts",template:`import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
|
835
848
|
|
|
836
849
|
const mcp = new MultiServerMCPClient({
|
|
837
850
|
maind: {
|
|
@@ -839,7 +852,7 @@ const mcp = new MultiServerMCPClient({
|
|
|
839
852
|
command: "npx",
|
|
840
853
|
args: ["-y", "@maind-dev/mcp-bridge"],
|
|
841
854
|
env: {
|
|
842
|
-
MAIND_MCP_URL: "${
|
|
855
|
+
MAIND_MCP_URL: "${t}",
|
|
843
856
|
},
|
|
844
857
|
},
|
|
845
858
|
});
|
|
@@ -850,17 +863,17 @@ const tools = await mcp.getTools();
|
|
|
850
863
|
"command": "npx",
|
|
851
864
|
"args": ["-y", "@maind-dev/mcp-bridge"],
|
|
852
865
|
"env": {
|
|
853
|
-
"MAIND_MCP_URL": "${
|
|
866
|
+
"MAIND_MCP_URL": "${t}"
|
|
854
867
|
}
|
|
855
|
-
}`}]}a(
|
|
856
|
-
`:
|
|
857
|
-
`;return await
|
|
868
|
+
}`}]}a(VT,"buildSnippetTemplates");var xH=VT(Bc);Xe();var qT="## maind MCP integration";function zT(e){return[{key:"preamble:CLAUDE.md",path:Ze.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Ze.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Ze.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Ze.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Ze.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Ze.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}a(zT,"buildPreambleTargets");async function pg(e,t=!1){let n=zT(e),r=[];for(let i of n)r.push(await YT(i,t));return r}a(pg,"writePreambleFiles");async function YT(e,t){try{if(e.mayNeedParentDir&&!t&&await Hc(Ze.dirname(e.path)),await og(e.path,qT))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await ae(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${qr}
|
|
869
|
+
`:JT(r)+`${qr}
|
|
870
|
+
`;return await Q(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}a(YT,"writeOnePreambleFile");function JT(e){return e.endsWith(`
|
|
858
871
|
|
|
859
|
-
`)?
|
|
860
|
-
`)?
|
|
861
|
-
`:
|
|
872
|
+
`)?e:e.endsWith(`
|
|
873
|
+
`)?e+`
|
|
874
|
+
`:e+`
|
|
862
875
|
|
|
863
|
-
`}a(
|
|
876
|
+
`}a(JT,"ensureTrailingBlankLine");Xc();Yn();Xe();import*as bg from"node:readline";var nn="config:auto_working_paths",cA=`
|
|
864
877
|
Enable presence enrichment (auto working_paths)?
|
|
865
878
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
866
879
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -869,36 +882,36 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
869
882
|
absolute paths. Server-side these paths are account-private (org members never
|
|
870
883
|
see them) and revocable any time on the dashboard consent page or via
|
|
871
884
|
{"auto_working_paths": false} in the bridge config.
|
|
872
|
-
[y/N]: `;async function
|
|
873
|
-
`;if(
|
|
874
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=K();if(i!==null)return{apiKey:i,result:{target:
|
|
875
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw
|
|
876
|
-
`),2;let o;if(n.projectRoot!==null)o=n.projectRoot;else{let
|
|
877
|
-
`);for(let S of
|
|
878
|
-
`);return 2}o=k}}let c=new
|
|
885
|
+
[y/N]: `;async function wg(e){let t=e.configPath??Qe(),n={};try{let o=await ae(t);if(o!==null&&o.trim().length>0){let c=JSON.parse(o);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:nn,action:"skip",status:"skipped",detail:`already decided (${n.auto_working_paths?"enabled":"disabled"}) in ${t}`};let r;if(e.explicitFlag)r=!0;else if(e.isInteractive){if(e.dryRun)return{target:nn,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??lA)(e.out,cA)}else return{target:nn,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:nn,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},s=JSON.stringify(i,null,2)+`
|
|
886
|
+
`;if(e.dryRun)return{target:nn,action:"merge",status:"would-merge",detail:t};try{await Q(t,s,384)}catch(o){return{target:nn,action:"merge",status:"failed",detail:`write: ${o instanceof Error?o.message:String(o)}`}}return{target:nn,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}a(wg,"applyWorkingPathsConsent");async function lA(e,t){e.write(t);let n=bg.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}a(lA,"promptYesNoDefaultNo");se();async function vg(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),s={};try{s=await i.json()}catch{}return i.ok?s.status!=="exchanged"||typeof s.api_key!="string"||!s.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:s.api_key,plan:s.plan??"unknown"}:{ok:!1,reason:s.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}a(vg,"exchangeOneClickToken");async function Sg(e){let t="browser-pair";if(e.token!==null)try{let s=dA(e.token);return e.dryRun?{apiKey:s,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(Br(),Zt(s),{apiKey:s,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(s){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:kg(s)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let s=gs(e.bridgeVersion),o=await vg({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:s.device_id,label:Hh(),clientMeta:{...s}});if(o.ok)return Br(),Zt(o.apiKey),{apiKey:o.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${o.plan})`}};n=o.reason,xg(e).write(`[maind-mcp-bridge] one-click exchange failed (${o.reason}) \u2014 falling back to browser pairing.
|
|
887
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=K();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await Kn(e.bridgeVersion,xg(e));return s===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:s.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${s.plan})${r}`}}}catch(s){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:kg(s)}}}}a(Sg,"pairOrUseToken");function dA(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}a(dA,"validateTokenShape");function kg(e){return e instanceof Error?e.message:String(e)}a(kg,"errMessage");function xg(e){return e.out??process.stdout}a(xg,"out");Wn();var uA="install-completed",pA=3e3;async function Eg(e){if(!e.enabled||e.apiKey===null)return;let t=Bn(uA),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:mA(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:fA(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),pA);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(i)}}a(Eg,"postInstallTelemetry");function fA(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}a(fA,"countStatuses");function mA(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}a(mA,"parseNodeMajor");sn();var qA="https://mcp.maind.dev/mcp";async function by(e){let t=Date.now(),n;try{n=qh(e)}catch(b){if(b instanceof Pe)return process.stderr.write(`error: ${b.message}
|
|
888
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw b}if(n.help)return zh(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=_y.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
889
|
+
`),2;let o;if(n.projectRoot!==null)o=n.projectRoot;else{let b=await Zh(process.cwd());if(b.length===0)o=await Xh(process.cwd());else if(b.length===1)o=b[0];else{let k=await eg(b,i);if(k===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
|
|
890
|
+
`);for(let S of b)process.stderr.write(` candidate: ${S}
|
|
891
|
+
`);return 2}o=k}}let c=new _s,l=(process.env.MAIND_MCP_URL??"").trim()||qA;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
879
892
|
`),process.stdout.write(`maind install \u2014 project root: ${o}
|
|
880
893
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
881
894
|
|
|
882
|
-
`);let d=await
|
|
895
|
+
`);let d=await Sg({bridgeVersion:G,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(`
|
|
883
896
|
pairing failed: ${d.result.detail??"unknown"}
|
|
884
897
|
Skipping remaining steps.
|
|
885
|
-
`),c.print(process.stdout),2;let u=
|
|
898
|
+
`),c.print(process.stdout),2;let u=ks({projectRoot:o,homeDir:s,platform:process.platform,env:process.env}),p=vs(u);if(p=sg(p,n.client),n.skipCodex&&(p=p.filter(b=>b.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.
|
|
886
899
|
`:`error: no client targets selected (did you skip all of them?)
|
|
887
|
-
`),c.print(process.stdout),2;for(let
|
|
900
|
+
`),c.print(process.stdout),2;for(let b of p){let k=ig({mcpUrl:l,clientFamily:b.clientFamilyEnv}),S;b.kind==="json"?S=await dg(b,k,n.dryRun):S=await ug(b,k,n.dryRun),c.add(S)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let b=await pg({projectRoot:o,homeDir:s},n.dryRun);for(let k of b)c.add(k)}let h={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await yg(h));for(let b of await _g(h))c.add(b);c.add(await wg({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let m=uy();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 Eg({enabled:n.telemetry||n.full,installerVersion:G,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:d.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let g=c.exitCode(),y=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
888
901
|
DRY RUN finished in ${y}s. No files were modified. Re-run without --dry-run to apply.
|
|
889
902
|
`):process.stdout.write(`
|
|
890
903
|
Finished in ${y}s. Restart your MCP client so it picks up the new server entry.
|
|
891
|
-
`);let v=
|
|
904
|
+
`);let v=Me({entryPath:Le(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),w=v.fallbackReason===null?`${Vn(v)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${w}
|
|
892
905
|
`),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.
|
|
893
|
-
`),g}a(
|
|
894
|
-
`,1)[0]??"";return
|
|
895
|
-
${JSON.stringify(e)}`).digest("hex")}a(QT,"payloadKey");function Se(t,e,n){return{kind:"error",error:t,message:e,hint:n}}a(Se,"fail");var Xt="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Gg(t){let e=cc(t);if(e!==null&&lc(e))return Se("server_predates_attest_mode","the MAIND server predates attest mode (< 0.62.0): it rejected a review_verdict call without `findings`.","No fallback: the legacy two-call path only yields an advisory verdict. For that today use codebase_review_changes \u2192 review_changes \u2192 review_verdict.");if(e?.kind==="invalid_params"){let n=e.issues[0];return Se("attest_rejected",`the server rejected the attest payload${n?` at ${(n.path??[]).join(".")||"(root)"}: ${n.message??n.code??"invalid"}`:""}.`,"This is a bridge/server version mismatch, not a problem with your change. Update the bridge (`npx -y @maind-dev/mcp-bridge@latest`) and call again; if it persists, report it.")}return Se("cloud_unavailable",`review_verdict failed: ${As(e?.detail??t)||"no detail"}`,Xt)}a(Gg,"fromProtocolText");function eA(t,e,n){switch(t.kind){case"no_session":return Se("cloud_unavailable","no MCP session with the MAIND server \u2014 the client never completed its handshake through this bridge.",`Retry once the MAIND cloud tools respond. ${Xt}`);case"transport_error":return t.timedOut?Se("cloud_timeout",`review_verdict did not answer within ${Math.round(e/1e3)} s.`,n?"The call asked for a record, and the server may still have written one. Check before calling again: `maind verify --commit HEAD`.":"The call asked for no record, so nothing was written. Call again when the server responds."):Se("cloud_unavailable",`network error: ${t.message}`,Xt);case"http_error":return t.status===401?Se("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${As(t.body)}`,"If the key was revoked or rebound, the next forwarded MAIND call starts the re-authorization; otherwise run `npx -y @maind-dev/mcp-bridge --reauth`."):t.status===413?Se("payload_too_large","the attest payload exceeded the server's request limit (HTTP 413).","Symbols are never cut to fit \u2014 a shortened list would attest a review that did not happen. Split the change into smaller commits or pull requests."):Se("cloud_unavailable",`HTTP ${t.status}: ${As(t.body)}`,Xt);case"rpc_error":return Gg(`MCP error ${t.code}: ${t.message}`);case"result":{if(t.isError)return Gg(t.text);let r;try{r=JSON.parse(t.text)}catch{return Se("cloud_unavailable",`review_verdict returned non-JSON text: ${As(t.text)}`,Xt)}return typeof r!="object"||r===null?Se("cloud_unavailable","review_verdict returned no object",Xt):{kind:"verdict",body:r}}}}a(eA,"interpretOutcome");var tA="review_verdict \u2014 and with it this tool \u2014 is a Team-plan feature. codebase_review_changes still gives you the advisory review (https://maind.dev/pricing).",nA={dirty:"commit (or stash) your changes \u2014 a dirty worktree cannot be recomputed",base_kind_not_ref:"pass `since` \u2014 only a committed range is replayable",base_sha_missing:"pass `since` \u2014 only a committed range is replayable",stale_files:"the index was stale for changed files \u2014 run codebase_index, then call again",truncated:"more than 1000 changed symbols, or labels beyond the schema \u2014 split the change",hunk_coverage_not_full:"some changes could not be line-graded (binary or unusual diffs)",detector_coverage_not_full:"a repo-health detector could not run \u2014 see local.detectors",merge_base_missing:"no merge-base with `since` (shallow clone?) \u2014 fetch the full history",private_citation:"a finding cites a private convention \u2014 not verifiable by others"},Kg=a(t=>t.map(e=>nA[e]??e).join("; "),"adviceFor");function rA(t,e){switch(t){case"no_report":return"persist: false \u2014 verdict only, nothing recorded.";case"no_head":return"no HEAD commit \u2014 there is nothing a record could be anchored to.";case"no_project_key":return"no origin remote, so no project_key to file a record under \u2014 the verdict is computed but not recorded.";case"no_merge_base":return"no merge-base between HEAD and `since` (shallow clone?) \u2014 the verdict is computed but not recorded; fetch the full history.";case"no_base":return"uncommitted work is judged but never recorded. Commit and push, then call again with `since` = the branch's base (e.g. origin/master).";case"dirty_tree":return"the worktree has uncommitted or untracked changes \u2014 a record attests a commit, and a dirty tree cannot be recomputed. Commit (or stash) them, then call again.";case"not_grade_eligible":return`this run could not be attestation-grade (${(e??[]).join(", ")}), and only replayable runs are recorded. To fix: ${Kg(e??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(e??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,i]=e??[];return`the reviewed range starts at ${Bg(n)}, but this branch forks off ${i??"the default branch"} at ${Bg(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${i??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(e??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}a(rA,"skipText");function iA(t,e,n,r){if(t.persisted){if(e===!0)return`Recorded as attestation-grade run ${t.run_id} (format 3). Recompute it: \`maind verify ${t.run_id}\``+(r?` \u2014 a teammate: \`maind verify --commit ${r}\`.`:".");let c=Kg(n);return`Recorded as run ${t.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=t.reason??"",s=rA(i,t.detail),o=e===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return s!==null?`Not recorded: ${s}${o}`:`Not recorded (${i||"the server gave no reason"}).${o}`}a(iA,"recordHint");async function Vg(t,e,n){let r=n.repoRoot??de(),i=r,s=t,o=n.projectKey,c=typeof e.dir=="string"&&e.dir.length>0?e.dir:void 0;if(c!==void 0){let V=Gn(c,r);if(V===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(c)} could not be located \u2014 no repository was reviewed, nothing was sent.`,hint:"Pass a path that exists relative to the workspace (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};if(!GT(V.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};i=V.repoRoot,s=n.engineFor(i),o=n.projectKeyFor?.(i)??null}}let l=typeof e.since=="string"&&e.since.length>0?e.since:void 0,d=l!==void 0&&e.include_uncommitted===!0,u=e.persist!==!1,p=n.timeoutMs??9e4,h=n.recorded??VT,m=[],g=await qT(s,i,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await s.reviewChanges(ic(l,d)),v={repo_root:i,since:l??null,include_uncommitted:l===void 0?!0:d,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(zT(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:v,warnings:m};let b;try{b=await s.reviewDetectorScopes({baseRef:l})}catch(V){let nd=ge(Ve(`reviewDetectorScopes failed: ${Wc(V)}`));b={commit:nd,local:nd},m.push(`repo-health detectors unavailable (${Wc(V)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:w,dropped:k}=sc(y,b.commit);k>0&&m.push(`${k} symbol(s) exceed the server schema (name > ${zi} or qualified name > ${Yi} chars) and were left out \u2014 this run is not attestation-grade.`);let S=QT(o,w),R=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",D=XT({persistWanted:u,since:l,projectKey:o,result:y,payload:w,git:R?(n.persistFacts??ZT)(i,y.headSha):null,recordedRunId:h.get(S)??null}),F={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:w.changed_symbols.length,symbols_dropped:k,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,Hg),local_only:YT(b).slice(0,Hg)}},H=await n.callCloudTool("review_verdict",{attest:w,persist:D.persist,...o?{project_key:o}:{}},{timeoutMs:p}),U=eA(H,p,D.persist);if(U.kind==="error")return{ok:!1,error:U.error,message:U.message,hint:U.hint,base:v,local:F,warnings:m};let N=U.body;if(N.ok!==!0){let V=N.error==="requires_team"||N.error==="requires_enterprise";return{ok:!1,error:N.error??"unknown_error",message:N.message??"review_verdict returned no message",hint:V?tA:N.hint??Xt,base:v,local:F,warnings:m}}if(N.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:v,local:F,warnings:m};let j=N.attest,ue=N.run??null,ln=ue&&typeof ue.id=="string"?{persisted:!0,run_id:ue.id,commit_sha:ue.commit_sha??null,attestation_format:ue.attestation_format??null}:{persisted:!1,reason:D.skipped??N.run_note??"not_persisted",...D.detail?{detail:D.detail}:{}};ln.persisted&&h.set(S,ue.id);let ed=typeof j?.attestation_grade=="boolean"?j.attestation_grade:null,td=Array.isArray(j?.grade_blockers)?j.grade_blockers:[],ri=N.counts??{},ro=Array.isArray(N.findings)?N.findings:[],uw=`Verdict ${N.verdict??"?"}: ${ri.block??0} block, ${ri.warn??0} warn, ${ri.note??0} note`+(N.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:N.verdict??null,counts:ri,record:ln,attest:j?{attestation_grade:ed,grade_blockers:td,attestation_format:j.attestation_format??null,input_hash:j.input_hash??null,policy_hash:j.policy_hash??null,evaluated_convention_count:j.evaluated_convention_count??null,detector_coverage:j.detector_coverage??null}:null,hint:`${uw} ${iA(ln,ed,td,y.headSha)}`,findings:ro.slice(0,Bc).map(V=>({convention_id:V.convention_id,convention_version:V.convention_version,severity:V.severity,action:V.action,...V.downgrade_reason?{downgrade_reason:V.downgrade_reason}:{},summary:V.summary,matched_changed_symbols:(V.matched_changed_symbols??[]).slice(0,KT),matched_symbol_count:V.matched_symbols?.length??0})),...ro.length>Bc?{findings_not_shown:ro.length-Bc}:{},detector_findings:N.detector_findings??[],policy_source:N.policy_source??null,coverage_note:ac(y,j?.evaluated_convention_count,k),base:v,local:F,warnings:m}}a(Vg,"runAttestReview");var qg=(()=>{let t=Object.keys(Sr),e=t.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${t.length} built-in repo-health detectors (${e.join(", ")})`})();function Rs(t){return sA("sha256").update(t,"utf8").digest("hex")}a(Rs,"nodeKeyHash");var oA=["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:oA,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 "+qg+" \u2014 ADR-324 \u2014 and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full counts as a complete check. This two-step gives an ADVISORY verdict and writes no record: diff_stats carries no commit anchors (MAIND-581). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located. For a gate verdict \u2014 and, for a clean pushed commit, a replayable attestation record \u2014 use attest_review_changes instead: one call, and the bridge sends the payload itself.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"attest_review_changes",description:"Gate verdict for your change in ONE call, computed by the MAIND server (ADR-357) \u2014 and, for a clean pushed commit, recorded as a replayable attestation. The bridge refreshes the local index, enumerates the diff (merge-base of `since` \u2192 HEAD), runs the "+qg+", builds the attest payload exactly like `maind review --gate`, and sends it to review_verdict itself \u2014 you copy no symbols and no commit hashes. The server matches ALL changed symbols (up to 1000) against its full visible code_review convention set and answers pass|warn|block with cited findings. A RECORD is written only when anyone with the commit can recompute it (`maind verify <run_id>`): `since` given, a clean worktree, HEAD pushed, the range starting where the branch forks off the default branch (so `since` = e.g. 'origin/master'), and nothing that keeps the run from being attestation-grade. Otherwise you still get the verdict, and `record.reason` names the step that leads to a record. THIS TOOL UPLOADS, unlike the codebase_* tools: symbol names and qualified names, kinds, languages, change grades and changed-line counts; closed-enum risk flags; detector ids, rule ids, levels and evidence HASHES; file counts; commit hashes; this repo's project_key hash. Never paths, source, detector titles or reasons. Call this WHEN: (a) your work is committed and pushed and you are about to open or update a PR \u2014 pass `since` = the branch's base (e.g. 'origin/master'); (b) a reviewer or CI needs a verdict with provenance, not an advisory list; (c) you want to see how uncommitted work fares against the gate \u2014 omit `since` (judged, never recorded). To iterate on local edits, codebase_review_changes is cheaper and uploads nothing. review_verdict is a Team-plan feature. Read `verdict` and `record` first; `ok: false` always carries an `error` code and a `hint`.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref the change is based on (e.g. 'origin/master', a SHA). Reviewed range: merge-base(since, HEAD) \u2192 HEAD. A record is written only when this range starts where the branch forks off the default branch. Omit to judge your uncommitted work against HEAD (never recorded)."},include_uncommitted:{type:"boolean",description:"With `since`: also include uncommitted changes \u2014 judged, never recorded (a dirty worktree cannot be recomputed). Default false; ignored without `since`."},persist:{type:"boolean",description:"Record the run when it is replayable (default true). false = verdict only, nothing written."},dir:{type:"string",description:`A path inside the repository to review (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 e.g. "Asgard/Maind". The record is filed under THAT repository's origin remote. Omit for the workspace repo. A path that cannot be located answers dir_not_found \u2014 nothing is sent.`}}},annotations:{title:"Attested review verdict",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],Kc=new Map([["codebase_review_verdict","attest_review_changes"]]),Jg=new Set([...Gc.map(t=>t.name),...Kc.keys()]),Vc=new Set(["attest_review_changes",...[...Kc].filter(([,t])=>t==="attest_review_changes").map(([t])=>t)]);async function Xg(t,e,n,r){if(!Vc.has(e))throw new Error(`not a cloud-backed tool: ${e}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let i=await Vg(t,n,r),s=Kc.get(e);return s?{...i,renamed:{from:e,to:s,note:`${e} is ${s} since bridge 0.79.0 \u2014 call ${s}; the old name goes in a later minor.`}}:i}a(Xg,"dispatchCloudBackedTool");function X(t){return typeof t=="string"&&t.length>0?t:void 0}a(X,"str");function Zt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}a(Zt,"num");function zg(t){if(t===void 0)return{repoRoot:de(),scanDirs:void 0};let e=Gn(t);return e===null?null:{repoRoot:e.repoRoot,scanDirs:e.repoRelDir===""?void 0:[e.repoRelDir]}}a(zg,"anchorRepo");function Yg(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(Yg,"dirNotFound");async function Zg(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=X(n.for_path);if(i!==void 0){let u=Eg(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 $t(u.repoRoot,u.repoRelPath,{minFiles:r}),h=p.namespace,m=a(y=>y===null?null:`${h?.prefix??""}${y}`,"full"),g=h===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:h===null?null:{dir:h.dir,prefix:h.prefix,file_count:h.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,p=[];for(let k of s){let S=Gn(k);if(S===null){p.push(k);continue}let R=u.get(S.repoRoot)??new Set;R.add(S.repoRelDir),u.set(S.repoRoot,R)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let h=[],m=[],g=[],y=[];for(let[k,S]of u){let R=[...S],D=R.includes(""),F=await Lt(k,{dirs:D?void 0:R,minFiles:r});h.push({repo_root:k,dirs:D?null:R}),m.push(...F.findings),g.push(...F.facts.namespaces.map(H=>({repo_root:k,dir:H.dir,prefix:H.prefix,file_count:H.fileCount}))),y.push(...F.facts.skipped)}let v=m.filter(k=>k.status==="open"),b=m.filter(k=>k.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:v.length===0,open_count:v.length,preexisting_count:b.length,findings:v,preexisting:b.map(k=>`${k.namespace.prefix}${k.number}`),namespaces:g,skipped:y,scanned:h,...p.length>0?{unresolved_dirs:p}:{},hint:(v.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${v.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let o=de(),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:X(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=X(n.dir),i,s;if(r!==void 0){let u=Gn(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=de(),s=void 0;let o=Ut(i,{dirs:s,baseRef:X(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=zg(X(n.dir));if(r===null)return Yg("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=jt(r.repoRoot,{dirs:r.scanDirs,baseRef:X(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=zg(X(n.dir));if(r===null)return Yg("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=tc(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:X(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=X(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await t.searchGraph(r,{kind:X(n.kind),limit:Zt(n.limit)})).map(s=>({...s,nodeKeyHash:Rs(s.nodeKey)}))}case"codebase_trace":{let r=X(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:Zt(n.max_depth),limit:Zt(n.limit)})}case"codebase_snippet":{let r=X(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:Rs(r)}}case"codebase_map":return t.getArchitecture({topN:Zt(n.top_n)});case"codebase_changes":{let r=await t.changedSymbols({since:X(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Zt(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:Rs(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:X(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Zt(n.limit)}),i;if(n.include_history!==!1)try{i=Bo(await t.fileHistory({since:X(n.since),limit:1}))}catch{i=void 0}let s;try{s=await t.reviewDetectors({baseRef:X(n.since)})}catch(l){s=ge(Ve(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let o={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Rs(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:o,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:o},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await t.fileHistory({paths:r,since:X(n.since),limit:Zt(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(Zg,"dispatchLocalTool");var Is=class{constructor(e=Ag,n=null,r=de,i=null){this.makeEngine=e;this.aggregator=n;this.resolveRoot=r;this.ctx=i}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"&&Jg.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=Vc.has(i)?await Xg(this.getEngine(),i,s,this.ctx??void 0):await Zg(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=xg(o)?`${Sg} (${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=Mg(e,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Mn();var aA="/mcp-client-metrics-ingest",cA=4e3,lA="codebase_search_tokens_saved";async function Qg(t){if(!Number.isFinite(t.tokensSaved)||t.tokensSaved<=0)return!1;let e=`${Pr()}${aA}`,n=new AbortController,r=setTimeout(()=>n.abort(),cA);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:lA,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)}
|
|
896
|
-
`),!1}finally{clearTimeout(r)}}a(
|
|
897
|
-
`).filter(
|
|
898
|
-
`),process.exit(1)),
|
|
899
|
-
`),process.exit(1)),
|
|
900
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
901
|
-
`),process.exit(0));let
|
|
902
|
-
`),n=await
|
|
903
|
-
`))}a(
|
|
906
|
+
`),g}a(by,"runInstall");sn();sn();import{readFileSync as zA}from"node:fs";import{join as wy}from"node:path";function Fs(e){return e?Math.ceil(e.length/4):0}a(Fs,"estimateTokens");var vy=1e6,js=class{static{a(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function ky(e){try{let t=zA(e,"utf8");return t.length>vy?t.slice(0,vy):t}catch{return""}}a(ky,"readFileCapped");function YA(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}a(YA,"distinctFilePaths");function xy(e,t,n,r){try{let i=Fs(n);if(e==="codebase_search"){let s=YA(t);if(s.length===0)return 0;let o=0;for(let c of s)o+=Fs(ky(wy(r,c)));return Math.max(0,o-i)}if(e==="codebase_snippet"){let s=t?.filePath;if(typeof s!="string"||s.length===0)return 0;let o=Fs(ky(wy(r,s)));return Math.max(0,o-i)}return 0}catch{return 0}}a(xy,"measureLocalToolSaved");Yt();sn();import{createHash as gR}from"node:crypto";Yt();import{execFileSync as QA}from"node:child_process";import{createHash as eR}from"node:crypto";sn();ll();import{realpathSync as Iy}from"node:fs";function tR(e,t){try{return Iy(e)===Iy(t)}catch{return e===t}}a(tR,"samePath");var dl=30,nR=10,Ny=20,rR=new Map;function ul(e){return e instanceof Error?e.message:String(e)}a(ul,"msg");function Hs(e){let t=e.split(`
|
|
907
|
+
`,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}a(Hs,"firstLine");var Cy=a(e=>e?e.slice(0,12):"?","short");async function iR(e,t,n,r){let i=await e.status(),s=!i.indexed||i.fileCount===0,o=await Ry(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:ul(c)}}},n);return o.locked?o.value.ok?s?(r.push(`no local index found \u2014 built it now (${o.value.stats.filesParsed} file(s), ${Math.round(o.value.stats.durationMs/1e3)} s).`),{action:"built",files_parsed:o.value.stats.filesParsed,missing:!1}):{action:"refreshed",files_parsed:o.value.stats.filesParsed,missing:!1}:(s||r.push(`index refresh failed \u2014 continuing with the existing index: ${o.value.error}`),{action:"kept",note:"refresh_failed",missing:s}):(s||r.push("another process holds the index lock (the Stop hook's refresh?) \u2014 reviewing with the existing index; stale files degrade to co_located and keep the run from being attestation-grade."),{action:"kept",note:"lock_busy",missing:s})}a(iR,"refreshIndex");function sR(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}a(sR,"isEmptyRange");function oR(e){let t=a(r=>`${r.detector_id}\0${r.rule_id}\0${r.title}`,"key"),n=new Set(e.commit.local.map(t));return e.local.local.filter(r=>!n.has(t(r)))}a(oR,"localOnly");function aR(e){let t=[],n=e.diff_stats;return e.base_sha||t.push("base_sha_missing"),n.stale_file_count!==0&&t.push("stale_files"),n.truncated!==!1&&t.push("truncated"),n.hunk_coverage!=="full"&&t.push("hunk_coverage_not_full"),n.detector_coverage!=="full"&&t.push("detector_coverage_not_full"),t}a(aR,"localGradeBlockers");function cR(e){if(!e.persistWanted)return{persist:!1,skipped:"no_report"};if(e.since===void 0)return{persist:!1,skipped:"no_base"};if(e.result.dirty)return{persist:!1,skipped:"dirty_tree"};let t=Rc(!1,e.projectKey,e.result);if(!t.persist)return t;let n=aR(e.payload);return n.length>0?{persist:!1,skipped:"not_grade_eligible",detail:n}:e.git===null||e.git.defaultBranch===null||e.git.forkPoint===null?{persist:!1,skipped:"fork_point_unknown",detail:[e.git?.defaultBranch?`origin/${e.git.defaultBranch}`:"no default branch"]}:e.git.forkPoint!==e.result.mergeBaseSha?{persist:!1,skipped:"base_not_fork_point",detail:[e.result.mergeBaseSha??"?",e.git.forkPoint,`origin/${e.git.defaultBranch}`]}:e.git.pushed?e.recordedRunId!==null?{persist:!1,skipped:"already_recorded",detail:[e.recordedRunId]}:{persist:!0,skipped:null}:{persist:!1,skipped:"head_not_pushed"}}a(cR,"bridgePersistDecision");function Oy(e,t){try{return QA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}a(Oy,"git");function lR(e,t){let n=Rr(e),r=n&&Oy(e,["merge-base",t,`origin/${n}`])||null,i=Oy(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}a(lR,"gitPersistFacts");function dR(e,t){return eR("sha256").update(`${e??""}
|
|
908
|
+
${JSON.stringify(t)}`).digest("hex")}a(dR,"payloadKey");function Te(e,t,n){return{kind:"error",error:e,message:t,hint:n}}a(Te,"fail");var on="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Dy(e){let t=Nc(e);if(t!==null&&Cc(t))return Te("server_predates_attest_mode","the MAIND server predates attest mode (< 0.62.0): it rejected a review_verdict call without `findings`.","No fallback: the legacy two-call path only yields an advisory verdict. For that today use codebase_review_changes \u2192 review_changes \u2192 review_verdict.");if(t?.kind==="invalid_params"){let n=t.issues[0];return Te("attest_rejected",`the server rejected the attest payload${n?` at ${(n.path??[]).join(".")||"(root)"}: ${n.message??n.code??"invalid"}`:""}.`,"This is a bridge/server version mismatch, not a problem with your change. Update the bridge (`npx -y @maind-dev/mcp-bridge@latest`) and call again; if it persists, report it.")}return Te("cloud_unavailable",`review_verdict failed: ${Hs(t?.detail??e)||"no detail"}`,on)}a(Dy,"fromProtocolText");function uR(e,t,n){switch(e.kind){case"no_session":return Te("cloud_unavailable","no MCP session with the MAIND server \u2014 the client never completed its handshake through this bridge.",`Retry once the MAIND cloud tools respond. ${on}`);case"transport_error":return e.timedOut?Te("cloud_timeout",`review_verdict did not answer within ${Math.round(t/1e3)} s.`,n?"The call asked for a record, and the server may still have written one. Check before calling again: `maind verify --commit HEAD`.":"The call asked for no record, so nothing was written. Call again when the server responds."):Te("cloud_unavailable",`network error: ${e.message}`,on);case"http_error":return e.status===401?Te("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Hs(e.body)}`,"If the key was revoked or rebound, the next forwarded MAIND call starts the re-authorization; otherwise run `npx -y @maind-dev/mcp-bridge --reauth`."):e.status===413?Te("payload_too_large","the attest payload exceeded the server's request limit (HTTP 413).","Symbols are never cut to fit \u2014 a shortened list would attest a review that did not happen. Split the change into smaller commits or pull requests."):Te("cloud_unavailable",`HTTP ${e.status}: ${Hs(e.body)}`,on);case"rpc_error":return Dy(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Dy(e.text);let r;try{r=JSON.parse(e.text)}catch{return Te("cloud_unavailable",`review_verdict returned non-JSON text: ${Hs(e.text)}`,on)}return typeof r!="object"||r===null?Te("cloud_unavailable","review_verdict returned no object",on):{kind:"verdict",body:r}}}}a(uR,"interpretOutcome");var pR="review_verdict \u2014 and with it this tool \u2014 is a Team-plan feature. codebase_review_changes still gives you the advisory review (https://maind.dev/pricing).",fR={dirty:"commit (or stash) your changes \u2014 a dirty worktree cannot be recomputed",base_kind_not_ref:"pass `since` \u2014 only a committed range is replayable",base_sha_missing:"pass `since` \u2014 only a committed range is replayable",stale_files:"the index was stale for changed files \u2014 run codebase_index, then call again",truncated:"more than 1000 changed symbols, or labels beyond the schema \u2014 split the change",hunk_coverage_not_full:"some changes could not be line-graded (binary or unusual diffs)",detector_coverage_not_full:"a repo-health detector could not run \u2014 see local.detectors",merge_base_missing:"no merge-base with `since` (shallow clone?) \u2014 fetch the full history",private_citation:"a finding cites a private convention \u2014 not verifiable by others"},Py=a(e=>e.map(t=>fR[t]??t).join("; "),"adviceFor");function mR(e,t){switch(e){case"no_report":return"persist: false \u2014 verdict only, nothing recorded.";case"no_head":return"no HEAD commit \u2014 there is nothing a record could be anchored to.";case"no_project_key":return"no origin remote, so no project_key to file a record under \u2014 the verdict is computed but not recorded.";case"no_merge_base":return"no merge-base between HEAD and `since` (shallow clone?) \u2014 the verdict is computed but not recorded; fetch the full history.";case"no_base":return"uncommitted work is judged but never recorded. Commit and push, then call again with `since` = the branch's base (e.g. origin/master).";case"dirty_tree":return"the worktree has uncommitted or untracked changes \u2014 a record attests a commit, and a dirty tree cannot be recomputed. Commit (or stash) them, then call again.";case"not_grade_eligible":return`this run could not be attestation-grade (${(t??[]).join(", ")}), and only replayable runs are recorded. To fix: ${Py(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,i]=t??[];return`the reviewed range starts at ${Cy(n)}, but this branch forks off ${i??"the default branch"} at ${Cy(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${i??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}a(mR,"skipText");function hR(e,t,n,r){if(e.persisted){if(t===!0)return`Recorded as attestation-grade run ${e.run_id} (format 3). Recompute it: \`maind verify ${e.run_id}\``+(r?` \u2014 a teammate: \`maind verify --commit ${r}\`.`:".");let c=Py(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",s=mR(i,e.detail),o=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return s!==null?`Not recorded: ${s}${o}`:`Not recorded (${i||"the server gave no reason"}).${o}`}a(hR,"recordHint");async function My(e,t,n){let r=n.repoRoot??pe(),i=r,s=e,o=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let Y=er(c,r);if(Y===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(c)} could not be located \u2014 no repository was reviewed, nothing was sent.`,hint:"Pass a path that exists relative to the workspace (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};if(!tR(Y.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};i=Y.repoRoot,s=n.engineFor(i),o=n.projectKeyFor?.(i)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,d=l!==void 0&&t.include_uncommitted===!0,u=t.persist!==!1,p=n.timeoutMs??9e4,h=n.recorded??rR,m=[],g=await iR(s,i,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await s.reviewChanges(Tc(l,d)),v={repo_root:i,since:l??null,include_uncommitted:l===void 0?!0:d,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(sR(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:v,warnings:m};let w;try{w=await s.reviewDetectorScopes({baseRef:l})}catch(Y){let Kd=_e(qe(`reviewDetectorScopes failed: ${ul(Y)}`));w={commit:Kd,local:Kd},m.push(`repo-health detectors unavailable (${ul(Y)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:b,dropped:k}=Ac(y,w.commit);k>0&&m.push(`${k} symbol(s) exceed the server schema (name > ${ls} or qualified name > ${ds} chars) and were left out \u2014 this run is not attestation-grade.`);let S=dR(o,b),R=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",D=cR({persistWanted:u,since:l,projectKey:o,result:y,payload:b,git:R?(n.persistFacts??lR)(i,y.headSha):null,recordedRunId:h.get(S)??null}),F={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:b.changed_symbols.length,symbols_dropped:k,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:w.commit.coverage,findings:w.commit.local.slice(0,Ny),local_only:oR(w).slice(0,Ny)}},H=await n.callCloudTool("review_verdict",{attest:b,persist:D.persist,...o?{project_key:o}:{}},{timeoutMs:p}),U=uR(H,p,D.persist);if(U.kind==="error")return{ok:!1,error:U.error,message:U.message,hint:U.hint,base:v,local:F,warnings:m};let N=U.body;if(N.ok!==!0){let Y=N.error==="requires_team"||N.error==="requires_enterprise";return{ok:!1,error:N.error??"unknown_error",message:N.message??"review_verdict returned no message",hint:Y?pR:N.hint??on,base:v,local:F,warnings:m}}if(N.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:v,local:F,warnings:m};let j=N.attest,me=N.run??null,bn=me&&typeof me.id=="string"?{persisted:!0,run_id:me.id,commit_sha:me.commit_sha??null,attestation_format:me.attestation_format??null}:{persisted:!1,reason:D.skipped??N.run_note??"not_persisted",...D.detail?{detail:D.detail}:{}};bn.persisted&&h.set(S,me.id);let Bd=typeof j?.attestation_grade=="boolean"?j.attestation_grade:null,Wd=Array.isArray(j?.grade_blockers)?j.grade_blockers:[],_i=N.counts??{},Eo=Array.isArray(N.findings)?N.findings:[],kv=`Verdict ${N.verdict??"?"}: ${_i.block??0} block, ${_i.warn??0} warn, ${_i.note??0} note`+(N.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:N.verdict??null,counts:_i,record:bn,attest:j?{attestation_grade:Bd,grade_blockers:Wd,attestation_format:j.attestation_format??null,input_hash:j.input_hash??null,policy_hash:j.policy_hash??null,evaluated_convention_count:j.evaluated_convention_count??null,detector_coverage:j.detector_coverage??null}:null,hint:`${kv} ${hR(bn,Bd,Wd,y.headSha)}`,findings:Eo.slice(0,dl).map(Y=>({convention_id:Y.convention_id,convention_version:Y.convention_version,severity:Y.severity,action:Y.action,...Y.downgrade_reason?{downgrade_reason:Y.downgrade_reason}:{},summary:Y.summary,matched_changed_symbols:(Y.matched_changed_symbols??[]).slice(0,nR),matched_symbol_count:Y.matched_symbols?.length??0})),...Eo.length>dl?{findings_not_shown:Eo.length-dl}:{},detector_findings:N.detector_findings??[],policy_source:N.policy_source??null,coverage_note:Ic(y,j?.evaluated_convention_count,k),base:v,local:F,warnings:m}}a(My,"runAttestReview");var Ly=(()=>{let e=Object.keys(Dr),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Gs(e){return gR("sha256").update(e,"utf8").digest("hex")}a(Gs,"nodeKeyHash");var yR=["module","class","interface","function","method","type_alias","enum","variable"],pl=[{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:yR,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 "+Ly+" \u2014 ADR-324 \u2014 and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full counts as a complete check. This two-step gives an ADVISORY verdict and writes no record: diff_stats carries no commit anchors (MAIND-581). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located. For a gate verdict \u2014 and, for a clean pushed commit, a replayable attestation record \u2014 use attest_review_changes instead: one call, and the bridge sends the payload itself.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"attest_review_changes",description:"Gate verdict for your change in ONE call, computed by the MAIND server (ADR-357) \u2014 and, for a clean pushed commit, recorded as a replayable attestation. The bridge refreshes the local index, enumerates the diff (merge-base of `since` \u2192 HEAD), runs the "+Ly+", builds the attest payload exactly like `maind review --gate`, and sends it to review_verdict itself \u2014 you copy no symbols and no commit hashes. The server matches ALL changed symbols (up to 1000) against its full visible code_review convention set and answers pass|warn|block with cited findings. A RECORD is written only when anyone with the commit can recompute it (`maind verify <run_id>`): `since` given, a clean worktree, HEAD pushed, the range starting where the branch forks off the default branch (so `since` = e.g. 'origin/master'), and nothing that keeps the run from being attestation-grade. Otherwise you still get the verdict, and `record.reason` names the step that leads to a record. THIS TOOL UPLOADS, unlike the codebase_* tools: symbol names and qualified names, kinds, languages, change grades and changed-line counts; closed-enum risk flags; detector ids, rule ids, levels and evidence HASHES; file counts; commit hashes; this repo's project_key hash. Never paths, source, detector titles or reasons. Call this WHEN: (a) your work is committed and pushed and you are about to open or update a PR \u2014 pass `since` = the branch's base (e.g. 'origin/master'); (b) a reviewer or CI needs a verdict with provenance, not an advisory list; (c) you want to see how uncommitted work fares against the gate \u2014 omit `since` (judged, never recorded). To iterate on local edits, codebase_review_changes is cheaper and uploads nothing. review_verdict is a Team-plan feature. Read `verdict` and `record` first; `ok: false` always carries an `error` code and a `hint`.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref the change is based on (e.g. 'origin/master', a SHA). Reviewed range: merge-base(since, HEAD) \u2192 HEAD. A record is written only when this range starts where the branch forks off the default branch. Omit to judge your uncommitted work against HEAD (never recorded)."},include_uncommitted:{type:"boolean",description:"With `since`: also include uncommitted changes \u2014 judged, never recorded (a dirty worktree cannot be recomputed). Default false; ignored without `since`."},persist:{type:"boolean",description:"Record the run when it is replayable (default true). false = verdict only, nothing written."},dir:{type:"string",description:`A path inside the repository to review (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 e.g. "Asgard/Maind". The record is filed under THAT repository's origin remote. Omit for the workspace repo. A path that cannot be located answers dir_not_found \u2014 nothing is sent.`}}},annotations:{title:"Attested review verdict",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],fl=new Map([["codebase_review_verdict","attest_review_changes"]]),jy=new Set([...pl.map(e=>e.name),...fl.keys()]),ml=new Set(["attest_review_changes",...[...fl].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function Uy(e,t,n,r){if(!ml.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let i=await My(e,n,r),s=fl.get(t);return s?{...i,renamed:{from:t,to:s,note:`${t} is ${s} since bridge 0.79.0 \u2014 call ${s}; the old name goes in a later minor.`}}:i}a(Uy,"dispatchCloudBackedTool");function ee(e){return typeof e=="string"&&e.length>0?e:void 0}a(ee,"str");function an(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}a(an,"num");function $y(e){if(e===void 0)return{repoRoot:pe(),scanDirs:void 0};let t=er(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}a($y,"anchorRepo");function Fy(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}a(Fy,"dirNotFound");async function Hy(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(o=>typeof o=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(o=>o.status==="open").length,s=r.findings.filter(o=>o.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=ee(n.for_path);if(i!==void 0){let u=my(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 Wt(u.repoRoot,u.repoRelPath,{minFiles:r}),h=p.namespace,m=a(y=>y===null?null:`${h?.prefix??""}${y}`,"full"),g=h===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:h===null?null:{dir:h.dir,prefix:h.prefix,file_count:h.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,p=[];for(let k of s){let S=er(k);if(S===null){p.push(k);continue}let R=u.get(S.repoRoot)??new Set;R.add(S.repoRelDir),u.set(S.repoRoot,R)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let h=[],m=[],g=[],y=[];for(let[k,S]of u){let R=[...S],D=R.includes(""),F=await Bt(k,{dirs:D?void 0:R,minFiles:r});h.push({repo_root:k,dirs:D?null:R}),m.push(...F.findings),g.push(...F.facts.namespaces.map(H=>({repo_root:k,dir:H.dir,prefix:H.prefix,file_count:H.fileCount}))),y.push(...F.facts.skipped)}let v=m.filter(k=>k.status==="open"),w=m.filter(k=>k.status==="info"),b=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:v.length===0,open_count:v.length,preexisting_count:w.length,findings:v,preexisting:w.map(k=>`${k.namespace.prefix}${k.number}`),namespaces:g,skipped:y,scanned:h,...p.length>0?{unresolved_dirs:p}:{},hint:(v.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${v.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+b}}let o=pe(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:o,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:ee(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=ee(n.dir),i,s;if(r!==void 0){let u=er(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=pe(),s=void 0;let o=qt(i,{dirs:s,baseRef:ee(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=$y(ee(n.dir));if(r===null)return Fy("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Vt(r.repoRoot,{dirs:r.scanDirs,baseRef:ee(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=$y(ee(n.dir));if(r===null)return Fy("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=xc(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:ee(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=ee(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:ee(n.kind),limit:an(n.limit)})).map(s=>({...s,nodeKeyHash:Gs(s.nodeKey)}))}case"codebase_trace":{let r=ee(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:an(n.max_depth),limit:an(n.limit)})}case"codebase_snippet":{let r=ee(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:Gs(r)}}case"codebase_map":return e.getArchitecture({topN:an(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:ee(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:an(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:Gs(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:ee(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:an(n.limit)}),i;if(n.include_history!==!1)try{i=da(await e.fileHistory({since:ee(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:ee(n.since)})}catch(l){s=_e(qe(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let o={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Gs(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:o,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:o},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await e.fileHistory({paths:r,since:ee(n.since),limit:an(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(o=>({sha:o.sha,author_name:o.authorName,author_email:o.authorEmail,date_iso:o.dateIso,subject:o.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(o=>({name:o.name,email:o.email,commits:o.commits,last_date_iso:o.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}a(Hy,"dispatchLocalTool");var Bs=class{constructor(t=gy,n=null,r=pe,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{a(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return pl}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&jy.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let o=ml.has(i)?await Uy(this.getEngine(),i,s,this.ctx??void 0):await Hy(this.getEngine(),i,s),c=JSON.stringify(o,null,2);return this.recordSavings(i,o,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(o){let c=o instanceof Error?o.message:String(o),l=py(o)?`${fy} (${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=xy(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};Wn();var _R="/mcp-client-metrics-ingest",bR=4e3,wR="codebase_search_tokens_saved";async function Gy(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Wr()}${_R}`,n=new AbortController,r=setTimeout(()=>n.abort(),bR);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:wR,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)}
|
|
909
|
+
`),!1}finally{clearTimeout(r)}}a(Gy,"postSavingsMetric");yl();Ks();qs();or();import{join as rN}from"node:path";var iN="<synthetic>";function D_(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:rN(Ul,Hl(e.cwd),`${e.transcript_stem}.jsonl`)}a(D_,"transcriptPathFromSideChannel");var no=class{constructor(t){this.deps=t}static{a(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??jl)(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!==iN&&(this.model=s.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as sN}from"node:child_process";var oN=8,aN=32;function cN(e){return e.split(`
|
|
910
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,aN)}a(cN,"parsePorcelain");function lN(e,t=oN){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(s.length===0||n.includes(s))&&(n.push(s),n.length>=t))break}return n}a(lN,"condenseToDirs");async function P_(e=dN){let t=await e();if(t===null)return null;let n=lN(cN(t));return n.length>0?n:null}a(P_,"deriveWorkingPaths");async function dN(){return await new Promise(e=>{sN("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}a(dN,"defaultGitStatus");var qD=1,zD=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function YD(e){return zD.includes(e)}a(YD,"isHookSubcommand");var JD=6e4;async function XD(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==K()&&Zt(e),e;let t=K();if(t!==null)return t;let n=await Kn(G);return n===null&&(Qt("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:G}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
911
|
+
`),process.exit(1)),Qt("paired",null,{version:G}),n.apiKey}a(XD,"ensureApiKey");async function ZD(e){let t=await Kn(G);return t===null&&(Qt("auth_failed",`${e}; re-authorization did not complete`,{version:G}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
912
|
+
`),process.exit(1)),Qt("paired",null,{version:G}),t.apiKey}a(ZD,"reauth");async function QD(){let e=process.argv.slice(2).find(b=>!b.startsWith("-"));if(e==="install"){let b=process.argv.indexOf("install"),k=process.argv.slice(b+1),S=await by(k);process.exit(S)}if(e==="doctor"){let{runDoctor:b}=await Promise.resolve().then(()=>(zl(),H_));process.exit(await b(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:b}=await Promise.resolve().then(()=>(Zb(),Xb));process.exit(await b())}if(e==="guard"){let b=process.argv.indexOf("guard"),{runGuard:k}=await Promise.resolve().then(()=>(sw(),iw));process.exit(await k(process.argv.slice(b+1)))}if(e==="guard-inject"){let{runGuardInject:b}=await Promise.resolve().then(()=>(mw(),fw));process.exit(await b())}if(e==="guard-gate"){let{runGuardGate:b}=await Promise.resolve().then(()=>(kw(),vw));process.exit(await b())}if(e==="guard-stop"){let{runGuardStop:b}=await Promise.resolve().then(()=>(Ew(),Sw));process.exit(await b())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:b}=await Promise.resolve().then(()=>(Td(),yw));process.exit(await b())}if(e==="guard-capture"){let{runGuardCapture:b}=await Promise.resolve().then(()=>(Iw(),Rw));process.exit(await b())}if(e==="gateway"){let b=process.argv.indexOf("gateway"),{runGateway:k}=await Promise.resolve().then(()=>(fv(),pv));process.exit(await k(process.argv.slice(b+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:b}=await Promise.resolve().then(()=>(Ud(),jd));process.exit(await b())}if(e==="guard-cross-check"){let{runGuardCrossCheck:b}=await Promise.resolve().then(()=>(Ud(),jd));process.exit(await b())}if(e==="on-index-refresh"){let{runOnIndexRefresh:b}=await Promise.resolve().then(()=>(Gd(),Hd));process.exit(await b())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:b}=await Promise.resolve().then(()=>(Gd(),Hd));process.exit(await b())}if(e!==void 0&&YD(e)){let b=await Promise.resolve().then(()=>(wd(),jb)),k={"on-session-start":b.runOnSessionStart,"on-tool-use":b.runOnToolUse,"on-file-write":b.runOnFileWrite,"on-file-edit":b.runOnFileEdit,"on-repo-health":b.runOnRepoHealth,"on-write-health":b.runOnWriteHealth,"sync-config":b.runSyncConfig,flush:b.runFlush,status:b.runHookStatus}[e];process.exit(await k())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(G+`
|
|
913
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(eP(),process.exit(0)),process.argv.includes("--reauth")&&(Br(),await Kn(G,process.stdout)===null&&process.exit(1),Qt("paired",null,{version:G}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
914
|
+
`),process.exit(0));let t=X(),n=await XD(),r=q(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new js:null,o=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Bs(void 0,s,void 0,{callCloudTool:a((b,k,S)=>o===null?Promise.resolve({kind:"no_session"}):o.callCloudTool(b,k,S),"callCloudTool"),projectKey:r,engineFor:a(b=>{let k=c.get(b);return k===void 0&&(k=yy(b),c.set(b,k)),k},"engineFor"),projectKeyFor:Vh}),d=`bridge-${VD()}`,u=a(async()=>{if(!s)return;let b=s.takePending();b.tokens<=0||await Gy({apiKey:n,deviceId:t,sessionId:d,tokensSaved:b.tokens,bridgeVersion:G})},"flushSavings"),p=s?setInterval(()=>{u()},JD):null;p?.unref();let h=new Vs({projectKey:r}),m=new no({resolvePath:a(()=>D_(h.sideChannel()),"resolvePath"),fallbackModel:a(()=>h.sideChannel()?.model??null,"fallbackModel")}),g=new Ws({projectKey:r,identity:h,sessionMeta:a(()=>m.read(),"sessionMeta"),postToolCall:a((b,k)=>o===null?Promise.reject(new Error("presence: no active forwarder")):o.postPresenceToolCall(b,k),"postToolCall"),deriveWorkingPaths:a(()=>P_(),"deriveWorkingPaths"),snapshot:r!==null?Qy({projectKey:r}):void 0}),y=g.isEnabled?setInterval(()=>{g.pollActivity()},Ky):null;if(y?.unref(),g.isEnabled){let b=a(k=>{g.end().finally(()=>process.exit(k))},"endAndExit");process.on("SIGTERM",()=>b(143)),process.on("SIGINT",()=>b(130))}let v=0,w=Mc();try{for(;;){let b=o?.carryOver()??null,k=new ms({apiKey:n,deviceId:t,bridgeVersion:G,projectKey:r,localRouter:l,presence:g,onConnectionOutcome:a((S,R)=>Qt(S,R,{version:G}),"onConnectionOutcome"),carry:b});o=k;try{await k.run(w);return}catch(S){if(S instanceof Gr&&v<qD){v+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${S.message}; re-authorizing\u2026
|
|
915
|
+
`),n=await ZD(S.reason);continue}throw S}}}finally{p&&clearInterval(p),y&&clearInterval(y),await g.end(),await u()}}a(QD,"main");function eP(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge doctor # offline self-diagnosis with fix commands (--json)"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>"," guard difficulty <on|off> | guard capture <on|off> in-loop triggers (ADR-360)",' guard skip --session <id> --reason "\u2026" [--kind consult|difficulty|capture] logged override'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop,"," guard-cross-observe, guard-cross-check, guard-difficulty, guard-outcome, guard-capture)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
|
|
916
|
+
`))}a(eP,"printHelp");QD().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
904
917
|
`),process.exit(1)});
|