@maind-dev/mcp-bridge 0.112.0 → 0.112.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -136,7 +136,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
136
136
  `,Mn="schema_version",Go="last_index_commit",xs="last_indexed_at",Wo="edges_dirty",mm="resolve_config_fp",Gc="embed_recipe_version",Wc="embed_model",Vc="embed_dim",hm="last_synced_at",ES="last_synced_commit"});function gm(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 TS(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of gm(e.name))t.add(o);for(let o of gm(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function AS(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let o of gm(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var ym=k(()=>{"use strict";s(gm,"splitIdentifier");s(TS,"buildSearchText");s(AS,"toFtsMatchQuery")});import{readFileSync as CS}from"node:fs";import{posix as RS}from"node:path";function IS(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 Hr(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function NS(e){return e==="added"?0:e==="modified"?1:2}function v1(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let o=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(o+=l-c+1)}let i=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return o>0||i?{...e,change:"modified",changedLineCount:o,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var Ss,_m=k(()=>{"use strict";an();uv();Dp();pv();gv();Mp();xv();De();Pv();Wp();tf();hs();lm();bs();SS();Vo();ym();Ss=class{static{s(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(Mn),o=await this.store.countFiles()>0;(t.full||o&&r!==Pn)&&await this.wipe();let i=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(i.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let b=Up(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(b===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");a=b}else a=Cv(this.repoRoot);let c=new Set(a.map(b=>b.path)),l=new Map(i.map(b=>[b.path,b])),u=i.length>0&&!t.full,d={filesScanned:a.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u},p=!1,f=s(async()=>{p||(p=!0,await this.store.setMeta(Wo,"1"))},"markEdgesDirty");for(let b of i)c.has(b.path)||(await f(),await this.store.deleteFile(b.path),d.filesDeleted++);let m=0;for(let b of a){m++;let w=Iv(this.repoRoot,b.path);if(!w){d.filesSkipped++;continue}let v=l.get(b.path);if(v&&v.mtimeMs===w.mtimeMs&&v.size===w.size){d.filesSkipped++;continue}let S=this.readRepoFile(b.path);if(S===null){d.filesSkipped++;continue}let x=Tc(S);if(v&&v.contentHash===x){await this.store.upsertFile({...v,mtimeMs:w.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let T=await this.parser.parse(b.path,S,b.language),I=new Map;for(let C of T.nodes)I.set(C.nodeKey,TS(C));let j={path:b.path,language:b.language,contentHash:x,mtimeMs:w.mtimeMs,size:w.size,indexedAt:n};await f(),await this.store.replaceFileNodes(j,T.nodes,I,{contains:T.edges,refs:T.refs,imports:T.imports,exports:T.exports}),d.filesParsed++,t.onProgress?.({path:b.path,done:m,total:a.length})}let g=fv(this.repoRoot),y=await this.store.getMeta(mm)!==g.fingerprint;if(p||y||await this.store.getMeta(Wo)==="1"){let b=wv(await this.store.getNameIndex()),w=new jo(g.config,b.files),v=vv(await this.store.getAllFacts(),b,w);await this.store.replaceCrossFileEdges(v),await this.store.setMeta(mm,g.fingerprint),await this.store.setMeta(Wo,"0")}if(this.embedder&&t.embed){let b=await this.store.getNodesByKinds([...Op]),w=await this.store.getEmbeddingContentHashes(),v=[];for(let x of b){let T=lv(x),I=Tc(`${this.embedder.recipeVersion}\0${T}`);w.get(x.nodeKey)!==I&&v.push({nodeKey:x.nodeKey,text:T,hash:I})}let S=64;for(let x=0;x<v.length;x+=S){let T=v.slice(x,x+S),I=await this.embedder.embedDocuments(T.map(C=>C.text));await this.store.upsertEmbeddings(T.map((C,M)=>({nodeKey:C.nodeKey,dim:this.embedder.dim,vec:I[M],contentHash:C.hash})));let j=Math.min(x+S,v.length);t.onProgress?.({path:"embedding symbols",done:j,total:v.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Gc,this.embedder.recipeVersion),await this.store.setMeta(Wc,this.embedder.model),await this.store.setMeta(Vc,String(this.embedder.dim))}await this.store.setMeta(Mn,Pn),await this.store.setMeta(xs,String(n));let _=ls(this.repoRoot);return _&&await this.store.setMeta(Go,_),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let i of n)r[i.language]=i.count;let o=await this.store.getMeta(xs);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:o?Number(o):null,lastIndexCommit:await this.store.getMeta(Go),schemaVersion:await this.store.getMeta(Mn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Hr(n.limit,20,100),o=await this.store.searchFts(t,n.kind??null,r),i=[];for(let a of o){let c=await this.store.getNode(a.nodeKey);c&&i.push({...IS(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Hr(n.limit,20,100),o=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:dv(o,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of a){let u=await this.store.getNode(l.nodeKey);u&&c.push({...IS(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=Hr(n.maxDepth,3,5),i=Hr(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let p=0;p<o&&d.length>0;p++){let f=[];for(let m of d){let g=await this.store.neighbors(m,r,a,i);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=i)return c;let b=r==="out"?y.dstKey:y.srcKey;u.has(b)||(u.add(b),f.push(b))}}d=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=CS(RS.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),o={};for(let a of n)o[a.kind]=a.count;let i={};for(let a of r)i[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:o,languageDistribution:i,topModules:await this.store.topModulesByFanIn(Hr(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Up(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Hr(t.limit,64,200),o=[],i=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&i++,o.push(...c)}return o.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:i,symbols:o.slice(0,r),truncated:o.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Ec(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(ls(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Hv(this.repoRoot,n,t)}async checkDivergence(t={}){return ps(this.repoRoot,t)}async checkNumberCollisions(t={}){return Dr(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Pr(this.repoRoot,t,n)}async checkSpecDrift(t={}){return $r(this.repoRoot,t)}async reviewDetectors(t={}){return am(this.repoRoot,t)}async reviewDetectorScopes(t={}){return cm(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Ec(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Dv(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",a=xS({paths:n,hunks:o,readUntracked:s(f=>this.readRepoFileHead(f,Ov),"readUntracked")}),c=Av(n.keys()),l=Hr(t.limit,64,t.attest?On:200),u=[],d=0,p=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;d++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),_=g!==null&&y!==null&&Tc(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let b=n.get(f.path)??"modified",w=o.get(f.path);for(let v of m)u.push(v1(v,b,w,_))}return u.sort((f,m)=>NS(f.change)-NS(m.change)||(f.filePath<m.filePath?-1:f.filePath>m.filePath?1:0)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:p,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:ls(this.repoRoot),dirty:Bp(this.repoRoot),baseSha:t.since?Ac(this.repoRoot,t.since):null,mergeBaseSha:t.since?Hp(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 CS(RS.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};s(IS,"toHit");s(Hr,"clampLimit");s(NS,"changeRank");s(v1,"classifyReviewSymbol")});var OS=k(()=>{"use strict";De()});var x1,Uee,DS=k(()=>{"use strict";De();x1=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],Uee=new RegExp(x1.join("|"),"g")});import{existsSync as bm,readdirSync as S1,readFileSync as E1}from"node:fs";import{spawnSync as T1}from"node:child_process";import{dirname as A1,join as qc,posix as km}from"node:path";function MS(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 ${wm} 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 ${wm} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,f=r!==null&&r.ok===!1?r.detail:void 0,g={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let o=new Set(r.versions),i=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!o.has(p)).sort(ln);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!i.has(p)).sort(ln),l=new Map,u=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}else u.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(u.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${u.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${u.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:u}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(ln),m=e.remote.versions.filter(g=>!i.has(g)).sort(ln);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let d=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function $S(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function jS(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(`
137
137
  `).filter(Boolean).slice(-1)[0]}}function PS(e,t,n){let r=e(t,C1,n);return r.ok===!1?jS(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
138
138
  `).map(o=>o.trim()).filter(Boolean)}}function FS(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 R1(e){let t=N(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=A1(t);return n===e?null:n}function I1(e,t,n){let r=km.dirname(t),i=[{path:qc(e,r,"config.toml"),source:"worktree"}],a=R1(e);a&&i.push({path:qc(a,r,"config.toml"),source:"main_worktree"});for(let c of i)if(bm(c.path))try{let l=FS(E1(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 N1(e,t){let n=new Map,r=N(e,["worktree","list","--porcelain"]);if(r===null)return n;let o=N(e,["rev-parse","--show-toplevel"])?.trim();for(let i of r.split(`
139
- `)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===o||!bm(a))continue;let c=qc(a,t);if(bm(c))try{for(let l of S1(c)){let u=Ho(l);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function vm(e,t={}){let n=t.runPsql??LS,r=t.timeoutMs??15e3,o=[],i=Nr(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}};let a=[],c=[],l=[];for(let p of i){let f=I1(e,p.dir,o),m=f.source==="missing"?null:PS(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?PS(n,t.remoteDbUrl,r):null,y=MS({dir:p.dir,projectRoot:qc(e,km.dirname(km.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:N1(e,p.dir),remote:g});a.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let u=$S(l),d={open:0,warn:1,info:2};return a.sort((p,f)=>d[p.status]-d[f.status]||p.id.localeCompare(f.id)),{ok:u==="in_sync",verdict:u,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}}}var wm,LS,C1,HS=k(()=>{"use strict";De();ds();wm=54322;s(MS,"evaluateLedgerProject");s($S,"deriveLedgerVerdict");LS=s((e,t,n)=>{let r=T1("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"),C1="select version from supabase_migrations.schema_migrations order by version";s(jS,"classifyLedgerError");s(PS,"readLedger");s(FS,"parseDbPort");s(R1,"mainWorktreeRoot");s(I1,"resolveConfig");s(N1,"gatherSiblingVersions");s(vm,"checkMigrationLedgerDrift")});function ft(e){return typeof e=="string"?e:String(e??"")}function Es(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function xm(e){return{nodeKey:ft(e.node_key),kind:ft(e.kind),name:ft(e.name),qualifiedName:ft(e.qualified_name),filePath:ft(e.file_path),startLine:Es(e.start_line),endLine:Es(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function KS(e){return{path:ft(e.path),language:ft(e.language),contentHash:ft(e.content_hash),mtimeMs:Es(e.mtime_ms),size:Es(e.size),indexedAt:Es(e.indexed_at)}}function Sm(e){let t=new Map,n=s(o=>{let i=t.get(o);return i===void 0&&(i=e.prepare(o),t.set(o,i)),i},"stmt"),r=s(o=>{let i=n($n.meta).get(o);return i===void 0?null:ft(i.value)},"metaValue");return{meta(){let o=r(Mn),i=r(xs);return{schemaVersion:o,schemaCurrent:o===Pn,edgesDirty:r(Wo)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n($n.file).get(o);return i===void 0?null:KS(i)},files(o){let i=new Map;for(let a of new Set(o)){let c=n($n.file).get(a);c!==void 0&&i.set(a,KS(c))}return i},symbolsInFile(o,i=O1){return n($n.symbolsInFile).all(o,i).map(xm)},symbolsNamed(o,i=D1){let a=new Map;for(let c of new Set(o)){let l=n($n.symbolsNamed).all(c,i);l.length>0&&a.set(c,l.map(xm))}return a},callersOfFile(o,i=P1){return n($n.callersOfFile).all(o,o,i).map(c=>({calleeKey:ft(c.callee_key),kind:ft(c.edge_kind),caller:xm(c)}))},importersOf(o,i=M1){let a=n($n.importersOf).all(Kt(o),i),c=[];for(let l of a){let u=ft(l.src_key),d=u.endsWith(BS)?u.slice(0,-BS.length):u;d!==o&&!c.includes(d)&&c.push(d)}return c},close(){e.close()}}}function Ts(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var US,$n,O1,D1,P1,M1,BS,Em=k(()=>{"use strict";Ir();Vo();US="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",$n={meta:"SELECT key, value FROM meta WHERE key = ?",file:"SELECT path, language, content_hash, mtime_ms, size, indexed_at FROM files WHERE path = ?",symbolsInFile:`SELECT ${US} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${US} FROM nodes WHERE name = ? AND kind <> 'module' ORDER BY file_path, start_line LIMIT ?`,callersOfFile:"SELECT e.dst_key AS callee_key, e.kind AS edge_kind, c.node_key, c.kind, c.name, c.qualified_name, c.file_path, c.start_line, c.end_line, c.signature FROM nodes n JOIN edges e ON e.dst_key = n.node_key AND e.kind IN ('calls', 'extends', 'implements') JOIN nodes c ON c.node_key = e.src_key WHERE n.file_path = ? AND c.file_path <> ? LIMIT ?",importersOf:"SELECT src_key FROM edges WHERE dst_key = ? AND kind = 'imports' LIMIT ?"},O1=400,D1=8,P1=600,M1=200,BS="#<module>";s(ft,"str");s(Es,"num");s(xm,"toSymbol");s(KS,"toFileRow");s(Sm,"createIndexReader");s(Ts,"isFileCurrent")});var Tm,Am=k(()=>{"use strict";Tm="0.2.0"});function Cm(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:On,attest:!0}}function Rm(e,t){let n=0,r=[];for(let i of e.symbols){let a=i.qualifiedName?i.qualifiedName:void 0;if(i.name.length===0||i.name.length>zc||a!==void 0&&a.length>Jc){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=WS?{kind:i.kind}:{},...i.language&&i.language.length<=VS?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),qS)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Tm},dropped:n}}function Im(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 Nm(e,t,n){let r=t,o=[];r===0?o.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):o.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&o.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&o.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let i=e.changedFiles-e.indexedFiles;return i>0&&o.push(`${i} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&o.push(`Symbol list truncated at ${On} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&o.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),o.join(" ")}function qo(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===GS&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===GS?{kind:"invalid_params",code:n,detail:r,issues:$1(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function $1(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 Om(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 zc,Jc,WS,VS,qS,GS,L1,zS=k(()=>{"use strict";an();Am();zc=200,Jc=512,WS=64,VS=32,qS=1e4;s(Cm,"attestReviewOptions");s(Rm,"buildAttestPayload");s(Im,"attestPersistDecision");s(Nm,"attestCoverageNote");GS=-32602;s(qo,"classifyMcpErrorText");s($1,"parseIssues");s(Om,"isLegacyAttestRejection");L1=`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)}`});import{execFileSync as j1}from"node:child_process";import{existsSync as F1,readFileSync as H1,readdirSync as U1}from"node:fs";import{basename as B1,join as JS}from"node:path";function Yc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ZS(e,t){let n=new Set,r=new Set,o=0;for(let i of e){if(i.split("/").includes("node_modules"))continue;let a=B1(i);for(let[u,d]of G1)a===u&&r.add(d);if(W1.test(i)&&(n.add("supabase"),n.add("postgres")),a!=="package.json"||o>=XS)continue;o+=1;let c=t(i);if(!Yc(c))continue;r.add("javascript");let l={...Yc(c.dependencies)?c.dependencies:{},...Yc(c.devDependencies)?c.devDependencies:{},...Yc(c.peerDependencies)?c.peerDependencies:{}};Object.prototype.hasOwnProperty.call(l,"typescript")&&r.add("typescript");for(let[u,d]of K1)Object.prototype.hasOwnProperty.call(l,u)&&n.add(d)}return{platforms:[...n].sort(),languages:[...r].sort()}}function Ur(e){return[...e.platforms,...e.languages]}function YS(e,t){try{return j1("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3,maxBuffer:64*1024*1024})}catch{return null}}function fn(e){let t=YS(e,["rev-parse","--show-toplevel"])?.trim()||null,n=e,r,o=t===null?null:YS(t,["ls-files","-z"]);if(t!==null&&o!==null)n=t,r=o.split("\0").filter(i=>i.length>0);else{try{r=U1(e)}catch{return{platforms:[],languages:[]}}F1(JS(e,"supabase","migrations"))&&r.push("supabase/migrations/")}return ZS(r,i=>{try{return JSON.parse(H1(JS(n,i),"utf8"))}catch{return null}})}var XS,K1,G1,W1,QS=k(()=>{"use strict";XS=200,K1=[["next","nextjs"],["react","react"],["react-dom","react"],["react-native","react-native"],["expo","expo"],["@supabase/supabase-js","supabase"],["@supabase/ssr","supabase"],["supabase","supabase"],["tailwindcss","tailwind"],["stripe","stripe"],["@stripe/stripe-js","stripe"],["pg","postgres"],["postgres","postgres"],["@modelcontextprotocol/sdk","mcp"]],G1=[["tsconfig.json","typescript"],["pyproject.toml","python"],["requirements.txt","python"],["go.mod","go"],["Cargo.toml","rust"]],W1=/(^|\/)supabase\/(config\.toml$|migrations\/)/;s(Yc,"isRecord");s(ZS,"inferRepoStack");s(Ur,"repoStackSlugs");s(YS,"git");s(fn,"detectRepoStack")});var He=k(()=>{"use strict";vb();_m();Wp();pm();De();$c();Df();Sf();Cf();If();tf();OS();DS();Jp();hs();Fc();tm();bs();ds();jc();HS();gf();lm();hs();bs();Fc();jc();kc();Dp();Vo();Em();vc();Am();zS();QS()});import{homedir as V1}from"node:os";import{join as q1}from"node:path";function Zc(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=As(r.id),i=As(r.key),a=As(r.title),c=As(r.status);if(!o||!i||!a||!c)continue;let l=r.here===!1?!1:void 0,u=As(r.where);if(t.push({id:o,key:i,title:a,status:c,...l===!1?{here:l}:{},...u?{where:u}:{}}),t.length>=z1)break}return t}function Dm(e){if(e.length===0)return null;let t=e.map(r=>`${r.key} "${r.title}"${r.status==="warn"?" (blocked)":""}`+(r.here===!1?` (in ${r.where?`${r.where}/`:"a repository below this one"})`:"")).join(", "),n=e.length===1;return`Assigned to your user and not taken yet: ${t}. Their own agents may take ${n?"it":"these"} (take_work_object). Mention ${n?"it":"them"} to your user and offer to take ${n?"it":"one"} \u2014 do not start unasked.`}function eE(e=V1()){return q1(e,".maind","assigned-told")}function tE(e,t){if(!e||typeof e!="object")return e;let n=e;return Array.isArray(n.assigned_to_you)?{...n,assigned_to_you:n.assigned_to_you.map(r=>{if(!r||typeof r!="object")return r;let o=r;if(o.here!==!1||typeof o.project_key!="string")return r;let i=t(o.project_key);return i?{...o,where:i}:r})}:e}function nE(e){return e==="claude-code"}var z1,As,Xc,Cs=k(()=>{"use strict";z1=5,As=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Zc,"parseAssignedList");s(Dm,"assignedNoticeText");s(eE,"assignedToldDir");Xc=class{static{s(this,"AssignedInbox")}current=[];told=new Set;update(t){if(!t||typeof t!="object")return;let n=t;n.ok===!0&&(this.current=Zc(n.assigned_to_you))}takeNote(){let t=this.current.filter(n=>!this.told.has(n.id));for(let n of t)this.told.add(n.id);return Dm(t)}};s(tE,"labelNestedItems");s(nE,"clientHasHooks")});function sE(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,o=typeof n.method=="string"?n.method:void 0;if(o!==void 0){let i={kind:r!==void 0?"request":"notification",method:o,id:r};if(o==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(i.toolName=c)}}return i}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function zo(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 $m(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Lm(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function jm(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Fm=k(()=>{"use strict";s(sE,"parseFrame");s(zo,"denyResult");s($m,"toolEvent");s(Lm,"policyEvent");s(jm,"shaEvent")});import{execFileSync as lE}from"node:child_process";function uE(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=iH}function sH(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let o=[];for(let i of nH){let a=r[i];typeof a=="string"&&aE.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of rH){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&aE.test(l)&&o.push({field:`${i}.${a}`,sha:l})}return o}function aH(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,cE);for(let o=cE;o>=oH;o--){let i=r.slice(0,o),a=t(i);if(a!==null&&a.startsWith(i))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:o}}return{field:"",sha:e,verdict:"unknown"}}function Jo(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 dE(){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 el(e=process.cwd()){try{let n=lE("git",["rev-parse","--show-toplevel"],{cwd:e,env:dE(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function cH(e){return t=>{try{let r=lE("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:dE(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function tl(e,t){if(t===null)return[];let n=sH(e);if(n.length===0)return[];let r=cH(t),o=[];for(let{field:i,sha:a}of n){let c=aH(a,r);c.verdict!=="proven"&&o.push({...c,field:i})}return o}var nH,rH,aE,oH,cE,iH,Hm=k(()=>{"use strict";nH=["commit_sha","base_sha","head_sha"],rH=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],aE=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,oH=7,cE=12,iH=10;s(uE,"isDenyGrade");s(sH,"extractShaArgs");s(aH,"classifySha");s(Jo,"shaFindingText");s(dE,"cleanGitEnv");s(el,"resolveRepoRootForSha");s(cH,"gitShaResolver");s(tl,"inspectLineForShas")});import{execFileSync as lH}from"node:child_process";import{createHash as uH}from"node:crypto";import{mkdirSync as dH,readFileSync as pH,renameSync as fH,writeFileSync as mH}from"node:fs";import{dirname as fE,join as mE}from"node:path";function At(e=process.cwd()){try{let t=lH("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 jn(e){return uH("sha256").update(e).digest("hex").slice(0,16)}function nl(e){return mE(e,hH)}function hE(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function gE(e,t,n,r=new Date().toISOString()){try{if(!hE(n))return;let o={version:Bm,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=nl(e);dH(fE(i),{recursive:!0}),cs(fE(i));let a=`${i}.${process.pid}.tmp`;mH(a,JSON.stringify(o,null,2),"utf8"),fH(a,i)}catch{}}function rl(e,t){try{let n=pH(nl(e),"utf8"),r=JSON.parse(n);return r.version!==Bm||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!hE(r.result)?null:{version:Bm,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function yE(e,t,n=new Date){let r=gH(t.cached_at,n),o=t.result.instructions??"",i={...t.result,instructions:`${r}
139
+ `)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===o||!bm(a))continue;let c=qc(a,t);if(bm(c))try{for(let l of S1(c)){let u=Ho(l);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function vm(e,t={}){let n=t.runPsql??LS,r=t.timeoutMs??15e3,o=[],i=Nr(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}};let a=[],c=[],l=[];for(let p of i){let f=I1(e,p.dir,o),m=f.source==="missing"?null:PS(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?PS(n,t.remoteDbUrl,r):null,y=MS({dir:p.dir,projectRoot:qc(e,km.dirname(km.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:N1(e,p.dir),remote:g});a.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let u=$S(l),d={open:0,warn:1,info:2};return a.sort((p,f)=>d[p.status]-d[f.status]||p.id.localeCompare(f.id)),{ok:u==="in_sync",verdict:u,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}}}var wm,LS,C1,HS=k(()=>{"use strict";De();ds();wm=54322;s(MS,"evaluateLedgerProject");s($S,"deriveLedgerVerdict");LS=s((e,t,n)=>{let r=T1("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"),C1="select version from supabase_migrations.schema_migrations order by version";s(jS,"classifyLedgerError");s(PS,"readLedger");s(FS,"parseDbPort");s(R1,"mainWorktreeRoot");s(I1,"resolveConfig");s(N1,"gatherSiblingVersions");s(vm,"checkMigrationLedgerDrift")});function ft(e){return typeof e=="string"?e:String(e??"")}function Es(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function xm(e){return{nodeKey:ft(e.node_key),kind:ft(e.kind),name:ft(e.name),qualifiedName:ft(e.qualified_name),filePath:ft(e.file_path),startLine:Es(e.start_line),endLine:Es(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function KS(e){return{path:ft(e.path),language:ft(e.language),contentHash:ft(e.content_hash),mtimeMs:Es(e.mtime_ms),size:Es(e.size),indexedAt:Es(e.indexed_at)}}function Sm(e){let t=new Map,n=s(o=>{let i=t.get(o);return i===void 0&&(i=e.prepare(o),t.set(o,i)),i},"stmt"),r=s(o=>{let i=n($n.meta).get(o);return i===void 0?null:ft(i.value)},"metaValue");return{meta(){let o=r(Mn),i=r(xs);return{schemaVersion:o,schemaCurrent:o===Pn,edgesDirty:r(Wo)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n($n.file).get(o);return i===void 0?null:KS(i)},files(o){let i=new Map;for(let a of new Set(o)){let c=n($n.file).get(a);c!==void 0&&i.set(a,KS(c))}return i},symbolsInFile(o,i=O1){return n($n.symbolsInFile).all(o,i).map(xm)},symbolsNamed(o,i=D1){let a=new Map;for(let c of new Set(o)){let l=n($n.symbolsNamed).all(c,i);l.length>0&&a.set(c,l.map(xm))}return a},callersOfFile(o,i=P1){return n($n.callersOfFile).all(o,o,i).map(c=>({calleeKey:ft(c.callee_key),kind:ft(c.edge_kind),caller:xm(c)}))},importersOf(o,i=M1){let a=n($n.importersOf).all(Kt(o),i),c=[];for(let l of a){let u=ft(l.src_key),d=u.endsWith(BS)?u.slice(0,-BS.length):u;d!==o&&!c.includes(d)&&c.push(d)}return c},close(){e.close()}}}function Ts(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var US,$n,O1,D1,P1,M1,BS,Em=k(()=>{"use strict";Ir();Vo();US="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",$n={meta:"SELECT key, value FROM meta WHERE key = ?",file:"SELECT path, language, content_hash, mtime_ms, size, indexed_at FROM files WHERE path = ?",symbolsInFile:`SELECT ${US} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${US} FROM nodes WHERE name = ? AND kind <> 'module' ORDER BY file_path, start_line LIMIT ?`,callersOfFile:"SELECT e.dst_key AS callee_key, e.kind AS edge_kind, c.node_key, c.kind, c.name, c.qualified_name, c.file_path, c.start_line, c.end_line, c.signature FROM nodes n JOIN edges e ON e.dst_key = n.node_key AND e.kind IN ('calls', 'extends', 'implements') JOIN nodes c ON c.node_key = e.src_key WHERE n.file_path = ? AND c.file_path <> ? LIMIT ?",importersOf:"SELECT src_key FROM edges WHERE dst_key = ? AND kind = 'imports' LIMIT ?"},O1=400,D1=8,P1=600,M1=200,BS="#<module>";s(ft,"str");s(Es,"num");s(xm,"toSymbol");s(KS,"toFileRow");s(Sm,"createIndexReader");s(Ts,"isFileCurrent")});var Tm,Am=k(()=>{"use strict";Tm="0.2.0"});function Cm(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:On,attest:!0}}function Rm(e,t){let n=0,r=[];for(let i of e.symbols){let a=i.qualifiedName?i.qualifiedName:void 0;if(i.name.length===0||i.name.length>zc||a!==void 0&&a.length>Jc){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=WS?{kind:i.kind}:{},...i.language&&i.language.length<=VS?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),qS)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Tm},dropped:n}}function Im(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 Nm(e,t,n){let r=t,o=[];r===0?o.push("No code_review conventions apply to this repository \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):o.push(`Matched by the server (attest mode) against the repository's code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&o.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&o.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let i=e.changedFiles-e.indexedFiles;return i>0&&o.push(`${i} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&o.push(`Symbol list truncated at ${On} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&o.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),o.join(" ")}function qo(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===GS&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===GS?{kind:"invalid_params",code:n,detail:r,issues:$1(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function $1(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 Om(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 zc,Jc,WS,VS,qS,GS,L1,zS=k(()=>{"use strict";an();Am();zc=200,Jc=512,WS=64,VS=32,qS=1e4;s(Cm,"attestReviewOptions");s(Rm,"buildAttestPayload");s(Im,"attestPersistDecision");s(Nm,"attestCoverageNote");GS=-32602;s(qo,"classifyMcpErrorText");s($1,"parseIssues");s(Om,"isLegacyAttestRejection");L1=`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)}`});import{execFileSync as j1}from"node:child_process";import{existsSync as F1,readFileSync as H1,readdirSync as U1}from"node:fs";import{basename as B1,join as JS}from"node:path";function Yc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ZS(e,t){let n=new Set,r=new Set,o=0;for(let i of e){if(i.split("/").includes("node_modules"))continue;let a=B1(i);for(let[u,d]of G1)a===u&&r.add(d);if(W1.test(i)&&(n.add("supabase"),n.add("postgres")),a!=="package.json"||o>=XS)continue;o+=1;let c=t(i);if(!Yc(c))continue;r.add("javascript");let l={...Yc(c.dependencies)?c.dependencies:{},...Yc(c.devDependencies)?c.devDependencies:{},...Yc(c.peerDependencies)?c.peerDependencies:{}};Object.prototype.hasOwnProperty.call(l,"typescript")&&r.add("typescript");for(let[u,d]of K1)Object.prototype.hasOwnProperty.call(l,u)&&n.add(d)}return{platforms:[...n].sort(),languages:[...r].sort()}}function Ur(e){return[...e.platforms,...e.languages]}function YS(e,t){try{return j1("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3,maxBuffer:64*1024*1024})}catch{return null}}function fn(e){let t=YS(e,["rev-parse","--show-toplevel"])?.trim()||null,n=e,r,o=t===null?null:YS(t,["ls-files","-z"]);if(t!==null&&o!==null)n=t,r=o.split("\0").filter(i=>i.length>0);else{try{r=U1(e)}catch{return{platforms:[],languages:[]}}F1(JS(e,"supabase","migrations"))&&r.push("supabase/migrations/")}return ZS(r,i=>{try{return JSON.parse(H1(JS(n,i),"utf8"))}catch{return null}})}var XS,K1,G1,W1,QS=k(()=>{"use strict";XS=200,K1=[["next","nextjs"],["react","react"],["react-dom","react"],["react-native","react-native"],["expo","expo"],["@supabase/supabase-js","supabase"],["@supabase/ssr","supabase"],["supabase","supabase"],["tailwindcss","tailwind"],["stripe","stripe"],["@stripe/stripe-js","stripe"],["pg","postgres"],["postgres","postgres"],["@modelcontextprotocol/sdk","mcp"]],G1=[["tsconfig.json","typescript"],["pyproject.toml","python"],["requirements.txt","python"],["go.mod","go"],["Cargo.toml","rust"]],W1=/(^|\/)supabase\/(config\.toml$|migrations\/)/;s(Yc,"isRecord");s(ZS,"inferRepoStack");s(Ur,"repoStackSlugs");s(YS,"git");s(fn,"detectRepoStack")});var He=k(()=>{"use strict";vb();_m();Wp();pm();De();$c();Df();Sf();Cf();If();tf();OS();DS();Jp();hs();Fc();tm();bs();ds();jc();HS();gf();lm();hs();bs();Fc();jc();kc();Dp();Vo();Em();vc();Am();zS();QS()});import{homedir as V1}from"node:os";import{join as q1}from"node:path";function Zc(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=As(r.id),i=As(r.key),a=As(r.title),c=As(r.status);if(!o||!i||!a||!c)continue;let l=r.here===!1?!1:void 0,u=As(r.where);if(t.push({id:o,key:i,title:a,status:c,...l===!1?{here:l}:{},...u?{where:u}:{}}),t.length>=z1)break}return t}function Dm(e){if(e.length===0)return null;let t=e.map(r=>`${r.key} "${r.title}"${r.status==="warn"?" (blocked)":""}`+(r.here===!1?` (in ${r.where?`${r.where}/`:"a repository below this one"})`:"")).join(", "),n=e.length===1;return`Assigned to your user and not taken yet: ${t}. Their own agents may take ${n?"it":"these"} (take_work_object). Mention ${n?"it":"them"} to your user and offer to take ${n?"it":"one"} \u2014 do not start unasked.`}function eE(e=V1()){return q1(e,".maind","assigned-told")}function tE(e,t){if(!e||typeof e!="object")return e;let n=e;return Array.isArray(n.assigned_to_you)?{...n,assigned_to_you:n.assigned_to_you.map(r=>{if(!r||typeof r!="object")return r;let o=r;if(o.here!==!1||typeof o.project_key!="string")return r;let i=t(o.project_key);return i?{...o,where:i}:r})}:e}function nE(e){return e==="claude-code"}var z1,As,Xc,Cs=k(()=>{"use strict";z1=5,As=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(Zc,"parseAssignedList");s(Dm,"assignedNoticeText");s(eE,"assignedToldDir");Xc=class{static{s(this,"AssignedInbox")}current=[];told=new Set;update(t){if(!t||typeof t!="object")return;let n=t;n.ok===!0&&(this.current=Zc(n.assigned_to_you))}takeNote(){let t=this.current.filter(n=>!this.told.has(n.id));for(let n of t)this.told.add(n.id);return Dm(t)}};s(tE,"labelNestedItems");s(nE,"clientHasHooks")});function sE(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,o=typeof n.method=="string"?n.method:void 0;if(o!==void 0){let i={kind:r!==void 0?"request":"notification",method:o,id:r};if(o==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(i.toolName=c)}}return i}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function zo(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 $m(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Lm(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function jm(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Fm=k(()=>{"use strict";s(sE,"parseFrame");s(zo,"denyResult");s($m,"toolEvent");s(Lm,"policyEvent");s(jm,"shaEvent")});import{execFileSync as lE}from"node:child_process";function uE(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=iH}function sH(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let o=[];for(let i of nH){let a=r[i];typeof a=="string"&&aE.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of rH){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&aE.test(l)&&o.push({field:`${i}.${a}`,sha:l})}return o}function aH(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,cE);for(let o=cE;o>=oH;o--){let i=r.slice(0,o),a=t(i);if(a!==null&&a.startsWith(i))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:o}}return{field:"",sha:e,verdict:"unknown"}}function Jo(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 dE(){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 el(e=process.cwd()){try{let n=lE("git",["rev-parse","--show-toplevel"],{cwd:e,env:dE(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function cH(e){return t=>{try{let r=lE("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:dE(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function tl(e,t){if(t===null)return[];let n=sH(e);if(n.length===0)return[];let r=cH(t),o=[];for(let{field:i,sha:a}of n){let c=aH(a,r);c.verdict!=="proven"&&o.push({...c,field:i})}return o}var nH,rH,aE,oH,cE,iH,Hm=k(()=>{"use strict";nH=["commit_sha","base_sha","head_sha"],rH=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],aE=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,oH=7,cE=12,iH=10;s(uE,"isDenyGrade");s(sH,"extractShaArgs");s(aH,"classifySha");s(Jo,"shaFindingText");s(dE,"cleanGitEnv");s(el,"resolveRepoRootForSha");s(cH,"gitShaResolver");s(tl,"inspectLineForShas")});import{execFileSync as lH}from"node:child_process";import{createHash as uH}from"node:crypto";import{mkdirSync as dH,readFileSync as pH,renameSync as fH,writeFileSync as mH}from"node:fs";import{dirname as fE,join as mE}from"node:path";function At(e=process.cwd()){try{let t=lH("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 jn(e){return uH("sha256").update(e).digest("hex").slice(0,16)}function nl(e){return mE(e,hH)}function hE(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function gE(e,t,n,r=new Date().toISOString()){try{if(!hE(n))return;let o={version:Bm,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=nl(e);dH(fE(i),{recursive:!0}),cs(fE(i));let a=`${i}.${process.pid}.tmp`;mH(a,JSON.stringify(o,null,2),"utf8"),fH(a,i)}catch{}}function rl(e,t){try{let n=pH(nl(e),"utf8"),r=JSON.parse(n);return r.version!==Bm||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!hE(r.result)?null:{version:Bm,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function yE(e,t,n=new Date){let r=gH(t.cached_at,n),o=t.result.instructions??"",i={...t.result,instructions:`${r}
140
140
 
141
141
  ${o}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function gH(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${yH(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function yH(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,o=Math.floor(r/6e4);if(o<1)return"just now";if(o<60)return`${o} minute${o===1?"":"s"} ago`;let i=Math.floor(o/60);if(i<24)return`${i} hour${i===1?"":"s"} ago`;let a=Math.floor(i/24);return`${a} day${a===1?"":"s"} ago`}var Bm,hH,qt=k(()=>{"use strict";He();Bm=1,hH=mE(".maind","conventions-cache.json");s(At,"resolveRepoRoot");s(jn,"keyFingerprint");s(nl,"cachePath");s(hE,"hasInstructions");s(gE,"writeConventionsCache");s(rl,"readConventionsCache");s(yE,"buildCachedInitializeResponse");s(gH,"fallbackMarker");s(yH,"relativeAge")});import{existsSync as al,mkdirSync as IH,readFileSync as kE,writeFileSync as qm,chmodSync as wE}from"node:fs";import{homedir as NH,hostname as OH,platform as Vm,release as DH}from"node:os";import{randomUUID as PH}from"node:crypto";import{join as Br}from"node:path";function Ct(){let e=NH(),t=process.env;if(Vm()==="darwin")return Br(e,"Library","Application Support","maind");if(Vm()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Br(e,"AppData","Roaming");return Br(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Br(e,".config");return Br(n,"maind")}function vE(e){al(e)||IH(e,{recursive:!0,mode:448})}function me(){let e=Ct();vE(e);let t=Br(e,MH);if(al(t)){let r=kE(t,"utf8").trim();if(jH(r))return r}let n=PH();qm(t,n+`
142
142
  `,{encoding:"utf8",mode:384});try{wE(t,384)}catch{}return n}function jH(e){return LH.test(e)}function zm(){return Br(Ct(),$H)}function Kr(e){let t=Ct();vE(t);let n=zm();qm(n,e+`
@@ -148,7 +148,7 @@ ${o}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function gH(e,t){ret
148
148
  `),null}async function BH(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}function KH(e){return new Promise(t=>setTimeout(t,e))}function GH(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: ${SE(e.verification_uri,56)} \u2502`,` \u2502 Code: ${SE(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(`
149
149
  `)+`
150
150
  `)}function SE(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}async function WH(e){let t,n;switch(UH()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,o)=>{try{let i=HH(t,n,{stdio:"ignore",detached:!0});i.on("error",o),i.unref(),r()}catch(i){o(i)}})}var Jm=k(()=>{"use strict";he();Zo();s(Qo,"runDeviceFlow");s(BH,"pollOnce");s(KH,"sleep");s(GH,"printAuthInstructions");s(SE,"pad");s(WH,"openExternalBrowser")});import{mkdirSync as VH,readFileSync as qH,renameSync as zH,writeFileSync as JH}from"node:fs";import{join as YH}from"node:path";function EE(e=Ct()){return YH(e,ZH)}function eU(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,QH)}function Gr(e,t,n){try{let r=n.dir??Ct();VH(r,{recursive:!0,mode:448});let o={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:eU(t),bridge_version:n.version},i=EE(r),a=`${i}.${process.pid}.tmp`;JH(a,JSON.stringify(o)+`
151
- `,{encoding:"utf8",mode:384}),zH(a,i)}catch{}}function TE(e=Ct()){try{let t=JSON.parse(qH(EE(e),"utf8"));return t.v!==1||typeof t.at!="string"||!XH.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 XH,ZH,QH,Ym=k(()=>{"use strict";he();XH=["ok","paired","auth_failed","not_paired"],ZH="connection-state.json",QH=200;s(EE,"connectionStatePath");s(eU,"redactDetail");s(Gr,"writeConnectionState");s(TE,"readConnectionState")});var G,ze=k(()=>{"use strict";G="0.112.0"});import{execFileSync as AE}from"node:child_process";import{createHash as tU}from"node:crypto";function Xm(e){return tU("sha256").update(e).digest("hex")}function Zm(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 Fn(e){let t=Zm(e);return t?Xm(t):null}function te(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&nU.test(e))return e;let t;try{t=AE("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Fn(t):null}function Je(e){let t;try{t=AE("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Fn(t):null}var nU,pe=k(()=>{"use strict";s(Xm,"sha256Hex");s(Zm,"normalizeRemoteUrl");s(Fn,"projectKeyFromRemote");nU=/^[a-f0-9]{64}$/;s(te,"computeProjectKey");s(Je,"projectKeyForRepo")});import rU from"node:path";import{fileURLToPath as oU}from"node:url";function iU(e,t=rU.sep){return e.split(t).includes("_npx")}function ve(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",RE,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):iU(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 fe(){try{let e=oU(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ye(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${CE(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:CE(n)).join(" ")}function zt(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(RE)}function ll(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function CE(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var RE,Rt=k(()=>{"use strict";RE="@maind-dev/mcp-bridge";s(iU,"isEphemeralEntry");s(ve,"resolveBridgeLaunch");s(fe,"currentBridgeEntry");s(Ye,"launchToShellCommand");s(zt,"isNpxForm");s(ll,"isLegacyHookForm");s(CE,"shellQuote")});import{readFileSync as sU}from"node:fs";import*as H from"node:path";function OE(e){let t=e.launch??ve({entryPath:fe(),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 PE(e){return fl(e,"Claude")}function cU(e){return H.join(PE(e),DE)}function fl(e,t){switch(e.platform){case"darwin":return H.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(n,t)}default:{let n=e.xdgConfigHome??H.join(e.homeDir,".config");return H.join(n,t)}}}function lU(e){return H.join(fl(e,"Code"),"User")}function dl(e,t,n=[]){return{kind:"foreign-entries",dir:fl(e,t),ours:["User",...n]}}function IE(e){return e.localAppData??H.join(e.homeDir,"AppData","Local")}function dU(e){let t=[{kind:"foreign-entries",dir:PE(e),ours:[DE]}];return e.platform==="darwin"?t.push({kind:"dir",path:H.join("/Applications","Claude.app")},{kind:"dir",path:H.join(e.homeDir,"Applications","Claude.app")}):e.platform==="win32"&&t.push({kind:"dir",path:H.join(IE(e),"AnthropicClaude")},{kind:"dir",path:H.join(IE(e),"Packages",uU)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function mn(e){return{evidence:[dl(e,"Cursor"),{kind:"foreign-entries",dir:H.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function ME(e){if(e.platform==="win32"){let t=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(t,"devin")}return H.join(e.xdgConfigHome??H.join(e.homeDir,".config"),"devin")}function pU(e){return H.join(ME(e),"mcp_config.json")}function $E(e){return H.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function pl(e){let t=[dl(e,"Devin",["mcp_config.json"]),{kind:"dir",path:H.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:ME(e),ours:["mcp_config.json"]}),t.push(dl(e,"Windsurf"),{kind:"foreign-entries",dir:H.dirname($E(e)),ours:["mcp_config.json"]}),{evidence:t,skipDetail:"Devin Desktop (formerly Windsurf) not found (no Devin or Windsurf app data, nothing of theirs in ~/.devin, Devin's config dir or ~/.codeium/windsurf)"}}function yU(e){return e===null?null:gU.exec(e)?.[1]??null}function jE(e,t){let n=LE.map(r=>H.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push(H.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of hU)for(let o of["/Applications",H.join(e.homeDir,"Applications")])n.push(H.join(o,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function FE(e){return e.clineDataDir?e.clineDataDir:H.join(e.clineDir??H.join(e.homeDir,".cline"),"data")}function _U(e){return e.clineMcpSettingsPath??H.join(FE(e),"settings","cline_mcp_settings.json")}function Qm(e){return{evidence:[{kind:"foreign-entries",dir:FE(e),ours:["settings"]},...fU.map(t=>({kind:"dir",path:H.join(fl(e,t),"User","globalStorage",NE)})),...jE(e,NE)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function ml(e){return e.continueGlobalDir??H.join(e.homeDir,".continue")}function bU(e){return H.join(ml(e),"mcpServers","maind.json")}function eh(e){return{evidence:[{kind:"foreign-entries",dir:ml(e),ours:["mcpServers","rules"]},...jE(e,mU)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function Hn(e){return e.codexHome??H.join(e.homeDir,".codex")}function Wr(e){return H.join(Hn(e),"config.toml")}function ei(e){let t=Hn(e),n=H.join(e.homeDir,".codex"),r=[{kind:"foreign-entries",dir:t,ours:["config.toml"]}];return t!==n&&r.push({kind:"foreign-entries",dir:n,ours:["config.toml"]}),{evidence:r,skipDetail:t===n?"Codex not found (nothing of Codex's in ~/.codex)":"Codex not found (nothing of Codex's in $CODEX_HOME or ~/.codex)"}}function Ds(e){return{evidence:[dl(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function kU(e){return H.join(lU(e),"mcp.json")}function Ps(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:H.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:H.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:cU(e),kind:"json",presence:dU(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:H.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:mn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:pU(e),kind:"json",presence:pl(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:$E(e),kind:"json",presence:pl(e),refreshOnly:{skipDetail:"no maind entry here to keep current \u2014 Devin Desktop's own file is the windsurf row"}},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:kU(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:Ds(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:_U(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:Qm(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:bU(e),kind:"json",presence:eh(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Wr(e),kind:"toml",presence:ei(e)}]}function HE(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function UE(e){return e.jsonShape??aU}function BE(e){let{homeDir:t,platform:n,env:r}=e,o=H.join(t,"Documents");if(n==="win32"){let l=["OneDrive","OneDriveConsumer","OneDriveCommercial"].map(u=>r[u]?.trim()).filter(u=>typeof u=="string"&&u.length>0&&H.win32.isAbsolute(u)).map(u=>H.join(u,"Documents"));return[...new Set([o,...l])]}if(n==="darwin")return[o];let i=r.XDG_CONFIG_HOME?.trim()||H.join(t,".config"),a=e.readText?.(H.join(i,"user-dirs.dirs"))??null,c=a===null?null:KE(a,t);return c!==null&&c!==o?[c,o]:[o]}function KE(e,t){for(let n of e.split(/\r?\n/)){let r=/^\s*XDG_DOCUMENTS_DIR\s*=\s*"?([^"]*)"?\s*$/.exec(n);if(!r)continue;let o=r[1].replace(/^\$HOME(?=\/|$)/,t).replace(/^\$\{HOME\}(?=\/|$)/,t);return H.isAbsolute(o)&&o.length>1?H.normalize(o):null}return null}function hn(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:ul(e.env.XDG_CONFIG_HOME),appData:ul(e.env.APPDATA),localAppData:ul(e.env.LOCALAPPDATA),clineDir:Os(e.env.CLINE_DIR),clineDataDir:Os(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:Os(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:Os(e.env.CONTINUE_GLOBAL_DIR),codexHome:Os(e.env.CODEX_HOME),bundleAppRoot:yU(e.bridgeEntry??null),documentsDirs:BE({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return sU(t,"utf8")}catch{return null}},"readText")})}}function ul(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Os(e){let t=ul(e);return t!==null&&H.isAbsolute(t)?t:null}var aU,DE,uU,LE,fU,NE,mU,hU,gU,th,Xe=k(()=>{"use strict";Rt();aU={serversKey:"mcpServers"};s(OE,"buildMaindServerEntry");DE="claude_desktop_config.json";s(PE,"claudeDesktopAppDataDir");s(cU,"claudeDesktopConfigPath");s(fl,"editorAppDataDir");s(lU,"vsCodeUserDir");s(dl,"editorRan");s(IE,"localAppDataDir");uU="Claude_pzs8sxrjxfjjc";s(dU,"claudeDesktopPresence");s(mn,"cursorPresence");s(ME,"devinConfigDir");s(pU,"devinMcpConfigPath");s($E,"windsurfLegacyMcpConfigPath");s(pl,"devinDesktopPresence");LE=[{appData:"Code",dataFolder:".vscode"},{appData:"Code - Insiders",dataFolder:".vscode-insiders"},{appData:"Cursor",dataFolder:".cursor"},{appData:"VSCodium",dataFolder:".vscode-oss"},{appData:"Windsurf",dataFolder:".windsurf"},{appData:"Devin",dataFolder:".devin"},{appData:"AgentComposer",dataFolder:".agentcomposer"}],fU=LE.map(e=>e.appData),NE="saoudrizwan.claude-dev",mU="continue.continue",hU=["AgentComposer"],gU=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(yU,"bundleAppRootOf");s(jE,"agentExtensionEvidence");s(FE,"clineDataDir");s(_U,"clineMcpSettingsPath");s(Qm,"clinePresence");s(ml,"continueGlobalDir");s(bU,"continueMcpConfigPath");s(eh,"continuePresence");s(Hn,"codexHomeDir");s(Wr,"codexConfigPath");s(ei,"codexPresence");s(Ds,"vsCodePresence");s(kU,"vsCodeUserMcpPath");s(Ps,"getClientTargets");s(HE,"filterTargetsByFamily");s(UE,"jsonShapeOf");th=[...new Set(Ps({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(BE,"documentsDirCandidates");s(KE,"parseXdgDocumentsDir");s(hn,"makeDefaultContext");s(ul,"nonEmpty");s(Os,"absoluteOrNull")});function nh(){return th.map(e=>{let t=Object.keys(hl).filter(n=>hl[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function GE(e){let t={projectRoot:null,full:!1,team:!1,noRules:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,agentActivity:!1,hooksOnly:!1,help:!1,notices:[]};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--team":t.team=!0;break;case"--no-rules":t.noRules=!0;break;case"--no-preamble":t.noPreamble||t.notices.push(wU),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"--agent-activity":t.agentActivity=!0;break;case"--hooks-only":t.hooksOnly=!0;break;case"--project-root":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--project-root requires a path argument");t.projectRoot=o,n++;break}case"--token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--token requires a token argument");t.token=o,n++;break}case"--one-click-token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--one-click-token requires a token argument");t.oneClickToken=o,n++;break}case"--one-click-exchange-url":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=o,n++;break}case"--client":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt(`--client requires a family argument (${nh()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(hl,i)?hl[i]:i;if(!th.includes(a))throw new mt(`--client "${o}" is not a known client family. Known: ${nh()}`);t.client=a,n++;break}default:throw new mt(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}if(t.full&&(t.nonInteractive=!0),t.hooksOnly){let n=[t.noHook&&"--no-hook",t.projectRoot!==null&&"--project-root",t.team&&"--team",t.token!==null&&"--token",t.oneClickToken!==null&&"--one-click-token",t.oneClickExchangeUrl!==null&&"--one-click-exchange-url",t.client!==null&&"--client",t.skipCodex&&"--skip-codex",t.telemetry&&"--telemetry",t.autoWorkingPaths&&"--auto-working-paths",t.agentActivity&&"--agent-activity"].filter(r=>typeof r=="string");if(n.length>0)throw new mt(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function WE(){process.stdout.write(vU())}function vU(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Pairs this device with MAIND and merges the MCP-server entry into every","supported AI-client config it finds (user level). Then it sets up the","channels that bring the MAIND hint and your project conventions into each","session \u2014 each with its own consent, only for clients that are installed:","hooks for Claude Code (~/.claude/settings.json), Cursor (~/.cursor/hooks.json)","and Codex (config.toml), user-level rule files for GitHub Copilot, Cline and","Continue. It writes nothing into your repository unless you pass --team.","Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (consents to the hooks and rule files)"," --team Also write into the repository, deliberately: the conventions"," block in AGENTS.md (kept current by the bridge) and the project"," .mcp.json \u2014 for teams whose colleagues should get the rules with"," the repository; recommended for teams that work mostly in Cursor"," --no-hook Never write hooks (Claude Code, Cursor, Codex; overrides --full)"," --no-rules Never write the user-level rule files (Copilot, Cline, Continue)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${nh()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --skip-codex Skip Codex (its config.toml and hook) even where Codex is installed",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only the user-level channels: the hooks (Claude Code; Cursor and"," Codex where installed) and the rule files (Copilot, Cline,"," Continue where installed) \u2014 no pairing, no MCP configs; adds"," what an existing install is missing; with --full, without prompts"," --agent-activity Opt-in: Claude Code sessions bound to one work object report their"," agent activity (plan, action counts, questions, answers) to it \u2014"," never paths or commands; not implied by --full"," --telemetry Opt-in: post anonymous install_completed event"," --no-preamble No effect since 0.100.0 (accepted for old scripts)"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --team # also AGENTS.md + .mcp.json in the repo"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","Blocks earlier versions wrote into a repository (CLAUDE.md, AGENTS.md, \u2026) stay","until you remove them: maind-mcp-bridge doctor --migrate-repo-blocks lists them.","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
151
+ `,{encoding:"utf8",mode:384}),zH(a,i)}catch{}}function TE(e=Ct()){try{let t=JSON.parse(qH(EE(e),"utf8"));return t.v!==1||typeof t.at!="string"||!XH.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 XH,ZH,QH,Ym=k(()=>{"use strict";he();XH=["ok","paired","auth_failed","not_paired"],ZH="connection-state.json",QH=200;s(EE,"connectionStatePath");s(eU,"redactDetail");s(Gr,"writeConnectionState");s(TE,"readConnectionState")});var G,ze=k(()=>{"use strict";G="0.112.1"});import{execFileSync as AE}from"node:child_process";import{createHash as tU}from"node:crypto";function Xm(e){return tU("sha256").update(e).digest("hex")}function Zm(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 Fn(e){let t=Zm(e);return t?Xm(t):null}function te(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&nU.test(e))return e;let t;try{t=AE("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Fn(t):null}function Je(e){let t;try{t=AE("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Fn(t):null}var nU,pe=k(()=>{"use strict";s(Xm,"sha256Hex");s(Zm,"normalizeRemoteUrl");s(Fn,"projectKeyFromRemote");nU=/^[a-f0-9]{64}$/;s(te,"computeProjectKey");s(Je,"projectKeyForRepo")});import rU from"node:path";import{fileURLToPath as oU}from"node:url";function iU(e,t=rU.sep){return e.split(t).includes("_npx")}function ve(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",RE,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):iU(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 fe(){try{let e=oU(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ye(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${CE(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:CE(n)).join(" ")}function zt(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(RE)}function ll(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function CE(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var RE,Rt=k(()=>{"use strict";RE="@maind-dev/mcp-bridge";s(iU,"isEphemeralEntry");s(ve,"resolveBridgeLaunch");s(fe,"currentBridgeEntry");s(Ye,"launchToShellCommand");s(zt,"isNpxForm");s(ll,"isLegacyHookForm");s(CE,"shellQuote")});import{readFileSync as sU}from"node:fs";import*as H from"node:path";function OE(e){let t=e.launch??ve({entryPath:fe(),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 PE(e){return fl(e,"Claude")}function cU(e){return H.join(PE(e),DE)}function fl(e,t){switch(e.platform){case"darwin":return H.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(n,t)}default:{let n=e.xdgConfigHome??H.join(e.homeDir,".config");return H.join(n,t)}}}function lU(e){return H.join(fl(e,"Code"),"User")}function dl(e,t,n=[]){return{kind:"foreign-entries",dir:fl(e,t),ours:["User",...n]}}function IE(e){return e.localAppData??H.join(e.homeDir,"AppData","Local")}function dU(e){let t=[{kind:"foreign-entries",dir:PE(e),ours:[DE]}];return e.platform==="darwin"?t.push({kind:"dir",path:H.join("/Applications","Claude.app")},{kind:"dir",path:H.join(e.homeDir,"Applications","Claude.app")}):e.platform==="win32"&&t.push({kind:"dir",path:H.join(IE(e),"AnthropicClaude")},{kind:"dir",path:H.join(IE(e),"Packages",uU)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function mn(e){return{evidence:[dl(e,"Cursor"),{kind:"foreign-entries",dir:H.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function ME(e){if(e.platform==="win32"){let t=e.appData??H.join(e.homeDir,"AppData","Roaming");return H.join(t,"devin")}return H.join(e.xdgConfigHome??H.join(e.homeDir,".config"),"devin")}function pU(e){return H.join(ME(e),"mcp_config.json")}function $E(e){return H.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function pl(e){let t=[dl(e,"Devin",["mcp_config.json"]),{kind:"dir",path:H.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:ME(e),ours:["mcp_config.json"]}),t.push(dl(e,"Windsurf"),{kind:"foreign-entries",dir:H.dirname($E(e)),ours:["mcp_config.json"]}),{evidence:t,skipDetail:"Devin Desktop (formerly Windsurf) not found (no Devin or Windsurf app data, nothing of theirs in ~/.devin, Devin's config dir or ~/.codeium/windsurf)"}}function yU(e){return e===null?null:gU.exec(e)?.[1]??null}function jE(e,t){let n=LE.map(r=>H.join(e.homeDir,r.dataFolder,"extensions"));if(e.bundleAppRoot&&n.push(H.join(e.bundleAppRoot,"extensions")),e.platform==="darwin")for(let r of hU)for(let o of["/Applications",H.join(e.homeDir,"Applications")])n.push(H.join(o,`${r}.app`,"Contents","Resources","app","extensions"));return[...new Set(n)].map(r=>({kind:"extension",dir:r,id:t}))}function FE(e){return e.clineDataDir?e.clineDataDir:H.join(e.clineDir??H.join(e.homeDir,".cline"),"data")}function _U(e){return e.clineMcpSettingsPath??H.join(FE(e),"settings","cline_mcp_settings.json")}function Qm(e){return{evidence:[{kind:"foreign-entries",dir:FE(e),ours:["settings"]},...fU.map(t=>({kind:"dir",path:H.join(fl(e,t),"User","globalStorage",NE)})),...jE(e,NE)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function ml(e){return e.continueGlobalDir??H.join(e.homeDir,".continue")}function bU(e){return H.join(ml(e),"mcpServers","maind.json")}function eh(e){return{evidence:[{kind:"foreign-entries",dir:ml(e),ours:["mcpServers","rules"]},...jE(e,mU)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function Hn(e){return e.codexHome??H.join(e.homeDir,".codex")}function Wr(e){return H.join(Hn(e),"config.toml")}function ei(e){let t=Hn(e),n=H.join(e.homeDir,".codex"),r=[{kind:"foreign-entries",dir:t,ours:["config.toml"]}];return t!==n&&r.push({kind:"foreign-entries",dir:n,ours:["config.toml"]}),{evidence:r,skipDetail:t===n?"Codex not found (nothing of Codex's in ~/.codex)":"Codex not found (nothing of Codex's in $CODEX_HOME or ~/.codex)"}}function Ds(e){return{evidence:[dl(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function kU(e){return H.join(lU(e),"mcp.json")}function Ps(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:H.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:H.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:cU(e),kind:"json",presence:dU(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:H.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:mn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:pU(e),kind:"json",presence:pl(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:$E(e),kind:"json",presence:pl(e),refreshOnly:{skipDetail:"no maind entry here to keep current \u2014 Devin Desktop's own file is the windsurf row"}},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:kU(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:Ds(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:_U(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:Qm(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:bU(e),kind:"json",presence:eh(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Wr(e),kind:"toml",presence:ei(e)}]}function HE(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function UE(e){return e.jsonShape??aU}function BE(e){let{homeDir:t,platform:n,env:r}=e,o=H.join(t,"Documents");if(n==="win32"){let l=["OneDrive","OneDriveConsumer","OneDriveCommercial"].map(u=>r[u]?.trim()).filter(u=>typeof u=="string"&&u.length>0&&H.win32.isAbsolute(u)).map(u=>H.join(u,"Documents"));return[...new Set([o,...l])]}if(n==="darwin")return[o];let i=r.XDG_CONFIG_HOME?.trim()||H.join(t,".config"),a=e.readText?.(H.join(i,"user-dirs.dirs"))??null,c=a===null?null:KE(a,t);return c!==null&&c!==o?[c,o]:[o]}function KE(e,t){for(let n of e.split(/\r?\n/)){let r=/^\s*XDG_DOCUMENTS_DIR\s*=\s*"?([^"]*)"?\s*$/.exec(n);if(!r)continue;let o=r[1].replace(/^\$HOME(?=\/|$)/,t).replace(/^\$\{HOME\}(?=\/|$)/,t);return H.isAbsolute(o)&&o.length>1?H.normalize(o):null}return null}function hn(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:ul(e.env.XDG_CONFIG_HOME),appData:ul(e.env.APPDATA),localAppData:ul(e.env.LOCALAPPDATA),clineDir:Os(e.env.CLINE_DIR),clineDataDir:Os(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:Os(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:Os(e.env.CONTINUE_GLOBAL_DIR),codexHome:Os(e.env.CODEX_HOME),bundleAppRoot:yU(e.bridgeEntry??null),documentsDirs:BE({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return sU(t,"utf8")}catch{return null}},"readText")})}}function ul(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Os(e){let t=ul(e);return t!==null&&H.isAbsolute(t)?t:null}var aU,DE,uU,LE,fU,NE,mU,hU,gU,th,Xe=k(()=>{"use strict";Rt();aU={serversKey:"mcpServers"};s(OE,"buildMaindServerEntry");DE="claude_desktop_config.json";s(PE,"claudeDesktopAppDataDir");s(cU,"claudeDesktopConfigPath");s(fl,"editorAppDataDir");s(lU,"vsCodeUserDir");s(dl,"editorRan");s(IE,"localAppDataDir");uU="Claude_pzs8sxrjxfjjc";s(dU,"claudeDesktopPresence");s(mn,"cursorPresence");s(ME,"devinConfigDir");s(pU,"devinMcpConfigPath");s($E,"windsurfLegacyMcpConfigPath");s(pl,"devinDesktopPresence");LE=[{appData:"Code",dataFolder:".vscode"},{appData:"Code - Insiders",dataFolder:".vscode-insiders"},{appData:"Cursor",dataFolder:".cursor"},{appData:"VSCodium",dataFolder:".vscode-oss"},{appData:"Windsurf",dataFolder:".windsurf"},{appData:"Devin",dataFolder:".devin"},{appData:"AgentComposer",dataFolder:".agentcomposer"}],fU=LE.map(e=>e.appData),NE="saoudrizwan.claude-dev",mU="continue.continue",hU=["AgentComposer"],gU=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(yU,"bundleAppRootOf");s(jE,"agentExtensionEvidence");s(FE,"clineDataDir");s(_U,"clineMcpSettingsPath");s(Qm,"clinePresence");s(ml,"continueGlobalDir");s(bU,"continueMcpConfigPath");s(eh,"continuePresence");s(Hn,"codexHomeDir");s(Wr,"codexConfigPath");s(ei,"codexPresence");s(Ds,"vsCodePresence");s(kU,"vsCodeUserMcpPath");s(Ps,"getClientTargets");s(HE,"filterTargetsByFamily");s(UE,"jsonShapeOf");th=[...new Set(Ps({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(BE,"documentsDirCandidates");s(KE,"parseXdgDocumentsDir");s(hn,"makeDefaultContext");s(ul,"nonEmpty");s(Os,"absoluteOrNull")});function nh(){return th.map(e=>{let t=Object.keys(hl).filter(n=>hl[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function GE(e){let t={projectRoot:null,full:!1,team:!1,noRules:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,agentActivity:!1,hooksOnly:!1,help:!1,notices:[]};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--team":t.team=!0;break;case"--no-rules":t.noRules=!0;break;case"--no-preamble":t.noPreamble||t.notices.push(wU),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"--agent-activity":t.agentActivity=!0;break;case"--hooks-only":t.hooksOnly=!0;break;case"--project-root":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--project-root requires a path argument");t.projectRoot=o,n++;break}case"--token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--token requires a token argument");t.token=o,n++;break}case"--one-click-token":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--one-click-token requires a token argument");t.oneClickToken=o,n++;break}case"--one-click-exchange-url":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=o,n++;break}case"--client":{let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new mt(`--client requires a family argument (${nh()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(hl,i)?hl[i]:i;if(!th.includes(a))throw new mt(`--client "${o}" is not a known client family. Known: ${nh()}`);t.client=a,n++;break}default:throw new mt(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}if(t.full&&(t.nonInteractive=!0),t.hooksOnly){let n=[t.noHook&&"--no-hook",t.projectRoot!==null&&"--project-root",t.team&&"--team",t.token!==null&&"--token",t.oneClickToken!==null&&"--one-click-token",t.oneClickExchangeUrl!==null&&"--one-click-exchange-url",t.client!==null&&"--client",t.skipCodex&&"--skip-codex",t.telemetry&&"--telemetry",t.autoWorkingPaths&&"--auto-working-paths",t.agentActivity&&"--agent-activity"].filter(r=>typeof r=="string");if(n.length>0)throw new mt(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function WE(){process.stdout.write(vU())}function vU(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Pairs this device with MAIND and merges the MCP-server entry into every","supported AI-client config it finds (user level). Then it sets up the","channels that bring the MAIND hint and your project conventions into each","session \u2014 each with its own consent, only for clients that are installed:","hooks for Claude Code (~/.claude/settings.json), Cursor (~/.cursor/hooks.json)","and Codex (config.toml), user-level rule files for GitHub Copilot, Cline and","Continue. It writes nothing into your repository unless you pass --team.","Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (consents to the hooks and rule files)"," --team Also write into the repository, deliberately: the conventions"," block in AGENTS.md (kept current by the bridge) and the project"," .mcp.json \u2014 for teams whose colleagues should get the rules with"," the repository; recommended for teams that work mostly in Cursor"," --no-hook Never write hooks (Claude Code, Cursor, Codex; overrides --full)"," --no-rules Never write the user-level rule files (Copilot, Cline, Continue)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${nh()}`," (windsurf = Devin Desktop, formerly Windsurf)"," --skip-codex Skip Codex (its config.toml and hook) even where Codex is installed",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only the user-level channels: the hooks (Claude Code; Cursor and"," Codex where installed) and the rule files (Copilot, Cline,"," Continue where installed) \u2014 no pairing, no MCP configs; adds"," what an existing install is missing; with --full, without prompts"," --agent-activity Opt-in: Claude Code sessions bound to one work object report their"," agent activity (plan, action counts, questions, answers) to it \u2014"," never paths or commands; not implied by --full"," --telemetry Opt-in: post anonymous install_completed event"," --no-preamble No effect since 0.100.0 (accepted for old scripts)"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --team # also AGENTS.md + .mcp.json in the repo"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","Blocks earlier versions wrote into a repository (CLAUDE.md, AGENTS.md, \u2026) stay","until you remove them: maind-mcp-bridge doctor --migrate-repo-blocks lists them.","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
152
152
  `)}var hl,wU,mt,VE=k(()=>{"use strict";Xe();hl={devin:"windsurf"};s(nh,"familyChoices");wU="note: --no-preamble has no effect since bridge 0.100.0 \u2014 install writes no preamble files into the repository any more (ADR-364).";s(GE,"parseInstallFlags");mt=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};s(WE,"printInstallHelp");s(vU,"installHelpText")});var Ms,qE=k(()=>{"use strict";Ms=class{static{s(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let o of this.results)o.status==="created"||o.status==="merged"||o.status==="skipped"||o.status==="would-create"||o.status==="would-merge"||o.status==="would-pair"?t++:o.status==="needs-user-decision"?n++:o.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
153
153
  `;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(u=>u.target.length)),r=Math.max(t[1].length,...this.results.map(u=>u.action.length)),o=Math.max(t[2].length,...this.results.map(u=>u.status.length)),i=Math.max(t[3].length,...this.results.map(u=>(u.detail??"").length)),a=s((u,d)=>u+" ".repeat(Math.max(0,d-u.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(o)} | ${"-".repeat(i)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],o)} | ${a(t[3],i)} |`),l.push(c);for(let u of this.results)l.push(`| ${a(u.target,n)} | ${a(u.action,r)} | ${a(u.status,o)} | ${a(u.detail??"",i)} |`);return l.join(`
154
154
  `)+`
@@ -1110,7 +1110,7 @@ ${a}`:`${o} Two exits:
1110
1110
  `).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let o=null;try{o=JSON.parse(r)}catch{continue}await Y_(o)||(n=!0,t.push(r))}try{let r=`${vo()}.${process.pid}.tmp`;await QD(r,t.length>0?t.join(`
1111
1111
  `)+`
1112
1112
  `:"",{mode:384}),await ZD(r,vo())}catch{}}var YD,iP=k(()=>{"use strict";he();xn();ze();YD=256;s(nP,"aggregateWindow");s(vo,"attestSpoolPath");s(Y_,"postAttestation");s(rP,"spoolAttestation");s(U6,"capSpool");s(oP,"flushAttestSpool")});function Ga(e=process.env,t=re()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Vd(e=process.env,t=re()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function sP(e,t=we()){let n={};try{let o=await K(t);if(o!==null&&o.trim().length>0){let i=JSON.parse(o);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await B(t,JSON.stringify(r,null,2)+`
1113
- `,384)}async function aP(e,t=we()){await sP({gateway_mode:e},t)}async function cP(e,t=we()){await sP({gateway_attest:e},t)}function lP(e=process.env,t=re()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var X_=k(()=>{"use strict";xe();ce();s(Ga,"resolveGatewayMode");s(Vd,"resolveGatewayAttest");s(sP,"writeGatewayConfigPatch");s(aP,"writeGatewayMode");s(cP,"writeGatewayAttest");s(lP,"resolveShaProofMode")});function dP(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let o=r,i=o.gateway_gate;if(typeof i!="object"||i===null)continue;let a=i;if(a.enabled!==!0)continue;let c=typeof o.id=="string"&&o.id.length>0&&o.id.length<=64?o.id:null,l=typeof o.version=="number"&&Number.isInteger(o.version)&&o.version>=1?o.version:null;if(c===null||l===null)continue;let u=typeof o.severity=="string"&&B6.has(o.severity)?o.severity:"recommended",d=typeof o.summary=="string"?o.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:u,summary:d})}}return n}function K6(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function pP(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)K6(i,e,t)&&(o===null||uP[i.severity]>uP[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function fP(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 B6,uP,Z_=k(()=>{"use strict";B6=new Set(["required","recommended","info"]);s(dP,"extractGatewayRules");uP={required:2,recommended:1,info:0};s(K6,"ruleMatches");s(pP,"decideToolCall");s(fP,"policyDenyText")});import{mkdirSync as G6,readFileSync as W6,renameSync as V6,writeFileSync as q6}from"node:fs";import{homedir as z6}from"node:os";import{dirname as J6,join as Y6}from"node:path";function mP(){return Y6(z6(),".maind","gateway","policy-cache.json")}function qd(e,t,n=new Date().toISOString()){try{let r={version:Q_,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=mP();G6(J6(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;q6(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),V6(i,o)}catch{}}function zd(e){try{let t=W6(mP(),"utf8"),n=JSON.parse(t);return n.version!==Q_||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Q_,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Q_,eb=k(()=>{"use strict";Q_=1;s(mP,"policyCachePath");s(qd,"writePolicyCache");s(zd,"readPolicyCache")});function Wa(e=process.env){let t=e.MAIND_MCP_URL??ga,n=Y();return{mcpUrl:t,keyFp:n?jn(n):"anon"}}async function Jd(e=6e3){let t=Y();if(t===null)return null;let n=null;try{n=te()}catch{n=null}let r=await $t("get_conventions",{},{apiKey:t,deviceId:me(),projectKey:n,bridgeVersion:G,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return dP(o)}var tb=k(()=>{"use strict";qt();he();xn();pe();ze();Z_();s(Wa,"policyIdentity");s(Jd,"fetchGatewayRules")});function Va(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 X6(e){if(Va(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 Z6(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Va(e)?{action:"skip",reason:"already-wrapped"}:X6(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function hP(e,t,n){let r=String(e.command),o=Array.isArray(e.args)?e.args.map(String):[],i=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=i||t.env?{...i??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...o]};return a&&(c.env=a),c}function gP(e){if(!Va(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 yP(e){return Object.entries(e).map(([t,n])=>{let r=Z6(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var _P=k(()=>{"use strict";s(Va,"isGatewayWrapped");s(X6,"isMaindProxyEntry");s(Z6,"classifyServer");s(hP,"wrapServerEntry");s(gP,"unwrapServerEntry");s(yP,"planRewrites")});var SP={};ee(SP,{runGatewayInstall:()=>o9,runGatewayUninstall:()=>i9});import{existsSync as Q6,readFileSync as e9}from"node:fs";import{homedir as t9}from"node:os";import{join as bP}from"node:path";import{createInterface as n9}from"node:readline";function kP(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 wP(){return[{label:"Claude Code (project .mcp.json)",path:bP(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:bP(t9(),".claude.json")}]}async function vP(e){let t=n9({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 xP(e){let t=r9(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,o=r.mcpServers;return typeof o!="object"||o===null||Array.isArray(o)?null:{raw:r,servers:o}}catch{return null}}function r9(e){try{return Q6(e)?e9(e,"utf8"):null}catch{return null}}async function o9(e){let t=kP(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1113
+ `,384)}async function aP(e,t=we()){await sP({gateway_mode:e},t)}async function cP(e,t=we()){await sP({gateway_attest:e},t)}function lP(e=process.env,t=re()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var X_=k(()=>{"use strict";xe();ce();s(Ga,"resolveGatewayMode");s(Vd,"resolveGatewayAttest");s(sP,"writeGatewayConfigPatch");s(aP,"writeGatewayMode");s(cP,"writeGatewayAttest");s(lP,"resolveShaProofMode")});function dP(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let o=r,i=o.gateway_gate;if(typeof i!="object"||i===null)continue;let a=i;if(a.enabled!==!0)continue;let c=typeof o.id=="string"&&o.id.length>0&&o.id.length<=64?o.id:null,l=typeof o.version=="number"&&Number.isInteger(o.version)&&o.version>=1?o.version:null;if(c===null||l===null)continue;let u=typeof o.severity=="string"&&B6.has(o.severity)?o.severity:"recommended",d=typeof o.summary=="string"?o.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:u,summary:d})}}return n}function K6(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function pP(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)K6(i,e,t)&&(o===null||uP[i.severity]>uP[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function fP(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 B6,uP,Z_=k(()=>{"use strict";B6=new Set(["required","recommended","info"]);s(dP,"extractGatewayRules");uP={required:2,recommended:1,info:0};s(K6,"ruleMatches");s(pP,"decideToolCall");s(fP,"policyDenyText")});import{mkdirSync as G6,readFileSync as W6,renameSync as V6,writeFileSync as q6}from"node:fs";import{homedir as z6}from"node:os";import{dirname as J6,join as Y6}from"node:path";function mP(){return Y6(z6(),".maind","gateway","policy-cache.json")}function qd(e,t,n=new Date().toISOString()){try{let r={version:Q_,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=mP();G6(J6(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;q6(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),V6(i,o)}catch{}}function zd(e){try{let t=W6(mP(),"utf8"),n=JSON.parse(t);return n.version!==Q_||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Q_,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Q_,eb=k(()=>{"use strict";Q_=1;s(mP,"policyCachePath");s(qd,"writePolicyCache");s(zd,"readPolicyCache")});function Wa(e=process.env){let t=e.MAIND_MCP_URL??ga,n=Y();return{mcpUrl:t,keyFp:n?jn(n):"anon"}}async function Jd(e=6e3){let t=Y();if(t===null)return null;let n=null;try{n=te()}catch{n=null}let r=await $t("get_conventions",{},{apiKey:t,deviceId:me(),projectKey:n,bridgeVersion:G,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return dP(o)}var tb=k(()=>{"use strict";qt();he();xn();pe();ze();Z_();s(Wa,"policyIdentity");s(Jd,"fetchGatewayRules")});function Va(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 X6(e){if(Va(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 Z6(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Va(e)?{action:"skip",reason:"already-wrapped"}:X6(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function hP(e,t,n){let r=String(e.command),o=Array.isArray(e.args)?e.args.map(String):[],i=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=i||t.env?{...i??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...o]};return a&&(c.env=a),c}function gP(e){if(!Va(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 yP(e){return Object.entries(e).map(([t,n])=>{let r=Z6(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var _P=k(()=>{"use strict";s(Va,"isGatewayWrapped");s(X6,"isMaindProxyEntry");s(Z6,"classifyServer");s(hP,"wrapServerEntry");s(gP,"unwrapServerEntry");s(yP,"planRewrites")});var SP={};ee(SP,{runGatewayInstall:()=>o3,runGatewayUninstall:()=>i3});import{existsSync as Q6,readFileSync as e3}from"node:fs";import{homedir as t3}from"node:os";import{join as bP}from"node:path";import{createInterface as n3}from"node:readline";function kP(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 wP(){return[{label:"Claude Code (project .mcp.json)",path:bP(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:bP(t3(),".claude.json")}]}async function vP(e){let t=n3({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 xP(e){let t=r3(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,o=r.mcpServers;return typeof o!="object"||o===null||Array.isArray(o)?null:{raw:r,servers:o}}catch{return null}}function r3(e){try{return Q6(e)?e3(e,"utf8"):null}catch{return null}}async function o3(e){let t=kP(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1114
1114
  `),2;let n=ve({entryPath:fe(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let o of wP()){let i=xP(o.path);if(i===null){process.stderr.write(` skipped ${o.label} \u2014 no mcpServers object
1115
1115
  `);continue}let a=yP(i.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${o.label} \xB7 ${c.key} \u2014 ${c.reason}
1116
1116
  `);continue}if(!(t.yes||await vP(`Wrap MCP server '${c.key}' in ${o.label} with the maind gateway?
@@ -1122,7 +1122,7 @@ ${a}`:`${o} Two exits:
1122
1122
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
1123
1123
  `:`
1124
1124
  Nothing to wrap.
1125
- `),0}async function i9(e){let t=kP(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1125
+ `),0}async function i3(e){let t=kP(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1126
1126
  `),2;let n=0;for(let r of wP()){let o=xP(r.path);if(o===null)continue;let i=!1;for(let[a,c]of Object.entries(o.servers)){if(!Va(c)||!(t.yes||await vP(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let u=gP(c);if(u===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
1127
1127
  `);continue}o.servers[a]=u,i=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
1128
1128
  `)}!t.dryRun&&i&&await B(r.path,JSON.stringify(o.raw,null,2)+`
@@ -1130,26 +1130,26 @@ Nothing to wrap.
1130
1130
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
1131
1131
  `:`
1132
1132
  Nothing wrapped \u2014 nothing to restore.
1133
- `),0}var EP=k(()=>{"use strict";ce();Rt();_P();s(kP,"parseFlags");s(wP,"targets");s(vP,"confirm");s(xP,"loadConfig");s(r9,"readFileSafeSync");s(o9,"runGatewayInstall");s(i9,"runGatewayUninstall")});var TP={};ee(TP,{runGatewayAttest:()=>a9,runGatewayMode:()=>s9,runGatewayPolicy:()=>u9});async function s9(e){let t=e[0];if(t===void 0){let n=Ga(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1133
+ `),0}var EP=k(()=>{"use strict";ce();Rt();_P();s(kP,"parseFlags");s(wP,"targets");s(vP,"confirm");s(xP,"loadConfig");s(r3,"readFileSafeSync");s(o3,"runGatewayInstall");s(i3,"runGatewayUninstall")});var TP={};ee(TP,{runGatewayAttest:()=>a3,runGatewayMode:()=>s3,runGatewayPolicy:()=>u3});async function s3(e){let t=e[0];if(t===void 0){let n=Ga(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1134
1134
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
1135
1135
  `),2):(await aP(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
1136
1136
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
1137
1137
  `:`Convention policy is off; only explicit --deny-tool flags apply.
1138
- `)),0)}async function a9(e){let t=e[0];if(t===void 0){let n=Vd(),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)":""}.
1138
+ `)),0)}async function a3(e){let t=e[0];if(t===void 0){let n=Vd(),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)":""}.
1139
1139
  `+(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.
1140
1140
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
1141
1141
  `),2):(await cP(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.
1142
1142
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
1143
- `),0)}function c9(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1143
+ `),0)}function c3(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1144
1144
  `;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),o=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${o})
1145
- `}return t}function l9(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let o=Math.floor(r/60);return o<24?`${o} h ago`:`${Math.floor(o/24)} d ago`}async function u9(e){let t=e.includes("--refresh"),n=Ga(),r=Wa();if(t){let i=await Jd();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1145
+ `}return t}function l3(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let o=Math.floor(r/60);return o<24?`${o} h ago`:`${Math.floor(o/24)} d ago`}async function u3(e){let t=e.includes("--refresh"),n=Ga(),r=Wa();if(t){let i=await Jd();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1146
1146
  `):(qd(r,i),process.stdout.write(`maind: policy refreshed (${i.length} rule(s)).
1147
1147
  `))}let o=zd(r);return process.stdout.write(`maind: gateway mode '${n}'
1148
1148
  `),o===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
1149
- `),0):(process.stdout.write(`maind: policy from cache (${l9(o)}, ${r.mcpUrl}):
1150
- `),process.stdout.write(c9(o.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
1151
- `),0)}var AP=k(()=>{"use strict";X_();eb();tb();s(s9,"runGatewayMode");s(a9,"runGatewayAttest");s(c9,"renderRules");s(l9,"cacheAge");s(u9,"runGatewayPolicy")});var OP={};ee(OP,{gatewayEventsFile:()=>IP,parseGatewayArgs:()=>NP,runGateway:()=>_9});import{spawn as d9}from"node:child_process";import{appendFile as p9,mkdir as f9}from"node:fs/promises";import{homedir as CP}from"node:os";import{basename as m9,join as RP}from"node:path";import{createInterface as h9}from"node:readline";function IP(){return RP(CP(),".maind","gateway","events.jsonl")}async function y9(e){try{let t=IP();await f9(RP(CP(),".maind","gateway"),{recursive:!0}),await p9(t,JSON.stringify(e)+`
1152
- `,{mode:384})}catch{}}function NP(e){let t=new Set,n=null,r=0;for(;r<e.length;){let o=e[r];if(o==="--deny-tool"){let i=e[r+1];if(!i)return null;t.add(i),r+=2;continue}if(o==="--label"){let i=e[r+1];if(!i)return null;n=i,r+=2;continue}if(o==="--"){let i=e[r+1];return i?{denyTools:t,label:n,command:i,args:e.slice(r+2)}:null}return null}return null}async function _9(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:x,runGatewayUninstall:T}=await Promise.resolve().then(()=>(EP(),SP));return e[0]==="install"?x(e.slice(1)):T(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:x,runGatewayMode:T,runGatewayPolicy:I}=await Promise.resolve().then(()=>(AP(),TP));return e[0]==="mode"?T(e.slice(1)):e[0]==="attest"?x(e.slice(1)):I(e.slice(1))}let t=NP(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1149
+ `),0):(process.stdout.write(`maind: policy from cache (${l3(o)}, ${r.mcpUrl}):
1150
+ `),process.stdout.write(c3(o.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
1151
+ `),0)}var AP=k(()=>{"use strict";X_();eb();tb();s(s3,"runGatewayMode");s(a3,"runGatewayAttest");s(c3,"renderRules");s(l3,"cacheAge");s(u3,"runGatewayPolicy")});var OP={};ee(OP,{gatewayEventsFile:()=>IP,parseGatewayArgs:()=>NP,runGateway:()=>_3});import{spawn as d3}from"node:child_process";import{appendFile as p3,mkdir as f3}from"node:fs/promises";import{homedir as CP}from"node:os";import{basename as m3,join as RP}from"node:path";import{createInterface as h3}from"node:readline";function IP(){return RP(CP(),".maind","gateway","events.jsonl")}async function y3(e){try{let t=IP();await f3(RP(CP(),".maind","gateway"),{recursive:!0}),await p3(t,JSON.stringify(e)+`
1152
+ `,{mode:384})}catch{}}function NP(e){let t=new Set,n=null,r=0;for(;r<e.length;){let o=e[r];if(o==="--deny-tool"){let i=e[r+1];if(!i)return null;t.add(i),r+=2;continue}if(o==="--label"){let i=e[r+1];if(!i)return null;n=i,r+=2;continue}if(o==="--"){let i=e[r+1];return i?{denyTools:t,label:n,command:i,args:e.slice(r+2)}:null}return null}return null}async function _3(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:x,runGatewayUninstall:T}=await Promise.resolve().then(()=>(EP(),SP));return e[0]==="install"?x(e.slice(1)):T(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:x,runGatewayMode:T,runGatewayPolicy:I}=await Promise.resolve().then(()=>(AP(),TP));return e[0]==="mode"?T(e.slice(1)):e[0]==="attest"?x(e.slice(1)):I(e.slice(1))}let t=NP(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1153
1153
  maind-mcp-bridge gateway install [--yes] [--dry-run]
1154
1154
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1155
1155
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -1159,13 +1159,13 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
1159
1159
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
1160
1160
  install/uninstall rewrite Claude Code MCP configs (consent per server).
1161
1161
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
1162
- `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??m9(o),c=Ga(),l=lP(),u=l==="off"?null:el(),d=c==="off"?[]:zd(Wa())?.rules??[];c!=="off"&&Jd().then(x=>{x!==null&&(d=x,qd(Wa(),x))}).catch(()=>{});let p=[],f=Vd()&&Y()!==null&&c!=="off",m=null;try{m=te()}catch{m=null}let g=Promise.resolve(),y=s(x=>{g=g.then(()=>y9(x)),f&&p.push(x)},"record"),_=s(async()=>{if(!f)return;let x=nP(p.splice(0),c,a,m);x!==null&&(await Y_(x)||await rP(x))},"attestAndReset");f&&oP().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let w=d9(o,i,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",x=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(x)}
1163
- `),process.exitCode=1});let v=h9({input:process.stdin,terminal:!1});v.on("line",x=>{let T=sE(x);if(T.kind==="request"&&T.method==="tools/call"&&T.toolName){if(n.has(T.toolName)&&T.id!==void 0){process.stdout.write(zo(T.id,T.toolName)+`
1162
+ `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??m3(o),c=Ga(),l=lP(),u=l==="off"?null:el(),d=c==="off"?[]:zd(Wa())?.rules??[];c!=="off"&&Jd().then(x=>{x!==null&&(d=x,qd(Wa(),x))}).catch(()=>{});let p=[],f=Vd()&&Y()!==null&&c!=="off",m=null;try{m=te()}catch{m=null}let g=Promise.resolve(),y=s(x=>{g=g.then(()=>y3(x)),f&&p.push(x)},"record"),_=s(async()=>{if(!f)return;let x=nP(p.splice(0),c,a,m);x!==null&&(await Y_(x)||await rP(x))},"attestAndReset");f&&oP().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let w=d3(o,i,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",x=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(x)}
1163
+ `),process.exitCode=1});let v=h3({input:process.stdin,terminal:!1});v.on("line",x=>{let T=sE(x);if(T.kind==="request"&&T.method==="tools/call"&&T.toolName){if(n.has(T.toolName)&&T.id!==void 0){process.stdout.write(zo(T.id,T.toolName)+`
1164
1164
  `),y($m("deny",a,T.toolName,Date.now()));return}let I=pP(T.toolName,a,d,c);if(I.kind==="deny"&&T.id!==void 0){process.stdout.write(zo(T.id,T.toolName,fP(T.toolName,I.rule))+`
1165
1165
  `),y(Lm("policy_deny",a,T.toolName,Date.now(),I.rule.conventionId,I.rule.conventionVersion));return}(I.kind==="warn"||I.kind==="deny")&&y(Lm("policy_warn",a,T.toolName,Date.now(),I.rule.conventionId,I.rule.conventionVersion));let j=tl(x,u);if(j.length>0){let C=j.find(R=>R.verdict==="fabricated");if(C!==void 0&&l==="enforce"&&c==="enforce"&&T.id!==void 0&&C!==void 0&&T.id!==void 0){process.stdout.write(zo(T.id,T.toolName,Jo(C,!0))+`
1166
1166
  `),y(jm("sha_deny",a,T.toolName,Date.now()));return}let E=C??j[0];process.stderr.write(`[maind gateway] ${Jo(E,!1)}
1167
1167
  `),y(jm("sha_warn",a,T.toolName,Date.now()))}y($m("tool_call",a,T.toolName,Date.now()))}w.stdin.write(x+`
1168
- `)}),v.on("close",()=>{w.stdin.end()});let S=await new Promise(x=>{w.on("exit",(T,I)=>{x(T??(I?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(x=>setTimeout(x,g9).unref())]),await _(),S}var g9,DP=k(()=>{"use strict";Fm();iP();X_();Z_();Hm();eb();tb();he();pe();s(IP,"gatewayEventsFile");g9=5e3;s(y9,"logEvent");s(NP,"parseGatewayArgs");s(_9,"runGateway")});var MP={};ee(MP,{ACTIVITY_WHAT_IS_SENT:()=>nb,runActivity:()=>k9,statusText:()=>PP});async function k9(e,t={}){let n=t.out??(c=>process.stdout.write(c)),r=t.err??(c=>process.stderr.write(c)),o=e[0];if(o===void 0||o==="status")return n(PP(t)),0;if(o!=="on"&&o!=="off")return r(`usage: maind-mcp-bridge activity [on|off|status]
1168
+ `)}),v.on("close",()=>{w.stdin.end()});let S=await new Promise(x=>{w.on("exit",(T,I)=>{x(T??(I?1:0))})});return clearInterval(b),await Promise.race([g,new Promise(x=>setTimeout(x,g3).unref())]),await _(),S}var g3,DP=k(()=>{"use strict";Fm();iP();X_();Z_();Hm();eb();tb();he();pe();s(IP,"gatewayEventsFile");g3=5e3;s(y3,"logEvent");s(NP,"parseGatewayArgs");s(_3,"runGateway")});var MP={};ee(MP,{ACTIVITY_WHAT_IS_SENT:()=>nb,runActivity:()=>k3,statusText:()=>PP});async function k3(e,t={}){let n=t.out??(c=>process.stdout.write(c)),r=t.err??(c=>process.stderr.write(c)),o=e[0];if(o===void 0||o==="status")return n(PP(t)),0;if(o!=="on"&&o!=="off")return r(`usage: maind-mcp-bridge activity [on|off|status]
1169
1169
  `),2;try{await(t.write??(c=>LO(c)))(o==="on")}catch(c){return r(`maind: could not write the bridge config: ${c instanceof Error?c.message:String(c)}
1170
1170
  `),1}let i=t.env??process.env,a=i[Fi]!==void 0&&i[Fi].trim().length>0?`maind: note \u2014 ${Fi} is set in this environment and wins over the config file.
1171
1171
  `:"";return n(o==="on"?"maind: agent activity reporting ON. "+nb+`
@@ -1173,15 +1173,15 @@ maind: sessions that are already running pick it up when their bridge restarts (
1173
1173
  `+a:`maind: agent activity reporting OFF. Running sessions stop reporting when their bridge restarts.
1174
1174
  `+a),0}function PP(e={}){let t=(e.setting??(()=>Od(e.env??process.env)))(),n=[],r=t.source==="env"?` (from ${Fi} env)`:t.source==="default"?" (default)":"";n.push(`maind: agent activity reporting is ${t.enabled?"ON":"OFF"}${r}.`),t.enabled||n.push(`maind: enable with 'maind-mcp-bridge activity on' \u2014 ${nb}`);let o=null;try{o=(e.projectKey??te)()}catch{o=null}if(o===null)return n.push("maind: not inside a git repository with an origin remote \u2014 there is no target to resolve here."),n.join(`
1175
1175
  `)+`
1176
- `;let i=[];try{i=(e.snapshots??(u=>Pt(u)))(o)}catch{i=[]}let a=(e.now??Date.now)(),c=i.filter(u=>{let d=Date.parse(u.written_at);return u.announce_error===void 0&&Number.isFinite(d)&&a-d<=b9});if(c.length===0)return n.push("maind: no live bridge session found for this repository. A target resolves once a session announces itself bound to a work object \u2014 a branch bound with `maind object bind`, or a take (take_work_object)."),n.join(`
1176
+ `;let i=[];try{i=(e.snapshots??(u=>Pt(u)))(o)}catch{i=[]}let a=(e.now??Date.now)(),c=i.filter(u=>{let d=Date.parse(u.written_at);return u.announce_error===void 0&&Number.isFinite(d)&&a-d<=b3});if(c.length===0)return n.push("maind: no live bridge session found for this repository. A target resolves once a session announces itself bound to a work object \u2014 a branch bound with `maind object bind`, or a take (take_work_object)."),n.join(`
1177
1177
  `)+`
1178
1178
  `;let l=t.enabled?"reports to":"would report to";n.push(`maind: live bridge sessions in this repository: ${c.length}`);for(let u of c){let d=` session ${u.own_session_id.slice(0,8)}\u2026${u.branch?` on ${u.branch}`:""}:`;if(u.bound_objects===void 0){n.push(`${d} target unknown \u2014 this snapshot was written by a bridge older than 0.104.0`);continue}let p=_i({branchObjectId:u.branch_object_id??null,boundObjects:u.bound_objects});n.push(`${d} ${p.objectId!==null?`${l} ${ca(p)}`:`nothing to report to \u2014 ${ca(p)}`}`)}return n.join(`
1179
1179
  `)+`
1180
- `}var b9,nb,$P=k(()=>{"use strict";so();pe();A_();oo();b9=120*6e4,nb="A Claude Code session bound to exactly one work object then reports what its agent does to that object's activity panel: the todo list as the plan, actions as category counts (read, edit, run, test, search, git, web, other), its questions to you and its answers. Never paths, commands, file contents or tool output; the agent's own words only when your organization sets agent_activity_text = on.";s(k9,"runActivity");s(PP,"statusText")});var lb={};ee(lb,{MAX_ENTRIES:()=>rb,TTL_MS:()=>sb,crossSessionDir:()=>ab,decideCrossSession:()=>FP,parseSessionDb:()=>jP,pruneDb:()=>cb,runGuardCrossCheck:()=>R9,runGuardCrossObserve:()=>C9,staleReason:()=>ob});import{mkdir as w9,readFile as v9,readdir as x9,stat as LP,unlink as S9,writeFile as E9}from"node:fs/promises";import{homedir as T9}from"node:os";import{join as ib}from"node:path";function ab(){return ib(T9(),".maind","cross-session")}function jP(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[i,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[i]={m:c.m,t:c.t})}let o={};if(typeof n.warned=="object"&&n.warned!==null)for(let[i,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(o[i]=a);return{files:r,warned:o}}function cb(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=sb);return n.length>rb&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-rb)),{files:Object.fromEntries(n),warned:e.warned}}function FP(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function ob(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 HP(e){let t=ab();return await w9(t,{recursive:!0}),ib(t,`${e}.json`)}async function UP(e,t){try{let n=await v9(await HP(e),"utf8");return cb(jP(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function BP(e,t){try{await E9(await HP(e),JSON.stringify(t),{mode:384})}catch{}}async function A9(e){try{let t=ab();for(let n of await x9(t)){if(!n.endsWith(".json"))continue;let r=ib(t,n),o=await LP(r).catch(()=>null);o&&e-o.mtimeMs>sb&&await S9(r).catch(()=>{})}}catch{}}async function KP(e){try{return(await LP(e)).mtimeMs}catch{return}}async function C9(e,t=Date.now()){try{if(_e().mode==="off")return 0;let r=e??await de();if(Ce(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=og(r);if(!o||!i)return 0;let a=await KP(i);if(a===void 0)return 0;let c=await UP(o,t);return c.files[i]={m:a,t},delete c.warned[i],await BP(o,cb(c,t)),await A9(t),0}catch{return 0}}async function R9(e,t=Date.now()){try{let n=_e();if(n.mode==="off")return 0;let r=e??await de();if(Ce(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=og(r);if(!o||!i)return 0;let a=await UP(o,t),c=FP(a.files[i]?.m,await KP(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Xt(ob(i,c))+`
1180
+ `}var b3,nb,$P=k(()=>{"use strict";so();pe();A_();oo();b3=120*6e4,nb="A Claude Code session bound to exactly one work object then reports what its agent does to that object's activity panel: the todo list as the plan, actions as category counts (read, edit, run, test, search, git, web, other), its questions to you and its answers. Never paths, commands, file contents or tool output; the agent's own words only when your organization sets agent_activity_text = on.";s(k3,"runActivity");s(PP,"statusText")});var lb={};ee(lb,{MAX_ENTRIES:()=>rb,TTL_MS:()=>sb,crossSessionDir:()=>ab,decideCrossSession:()=>FP,parseSessionDb:()=>jP,pruneDb:()=>cb,runGuardCrossCheck:()=>R3,runGuardCrossObserve:()=>C3,staleReason:()=>ob});import{mkdir as w3,readFile as v3,readdir as x3,stat as LP,unlink as S3,writeFile as E3}from"node:fs/promises";import{homedir as T3}from"node:os";import{join as ib}from"node:path";function ab(){return ib(T3(),".maind","cross-session")}function jP(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[i,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[i]={m:c.m,t:c.t})}let o={};if(typeof n.warned=="object"&&n.warned!==null)for(let[i,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(o[i]=a);return{files:r,warned:o}}function cb(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=sb);return n.length>rb&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-rb)),{files:Object.fromEntries(n),warned:e.warned}}function FP(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function ob(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 HP(e){let t=ab();return await w3(t,{recursive:!0}),ib(t,`${e}.json`)}async function UP(e,t){try{let n=await v3(await HP(e),"utf8");return cb(jP(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function BP(e,t){try{await E3(await HP(e),JSON.stringify(t),{mode:384})}catch{}}async function A3(e){try{let t=ab();for(let n of await x3(t)){if(!n.endsWith(".json"))continue;let r=ib(t,n),o=await LP(r).catch(()=>null);o&&e-o.mtimeMs>sb&&await S3(r).catch(()=>{})}}catch{}}async function KP(e){try{return(await LP(e)).mtimeMs}catch{return}}async function C3(e,t=Date.now()){try{if(_e().mode==="off")return 0;let r=e??await de();if(Ce(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=og(r);if(!o||!i)return 0;let a=await KP(i);if(a===void 0)return 0;let c=await UP(o,t);return c.files[i]={m:a,t},delete c.warned[i],await BP(o,cb(c,t)),await A3(t),0}catch{return 0}}async function R3(e,t=Date.now()){try{let n=_e();if(n.mode==="off")return 0;let r=e??await de();if(Ce(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=og(r);if(!o||!i)return 0;let a=await UP(o,t),c=FP(a.files[i]?.m,await KP(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Xt(ob(i,c))+`
1181
1181
  `),await ne({event:"cross_session_deny",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i}),0):(a.warned[i]===c.current||(process.stdout.write(bn(ob(i,c))+`
1182
- `),a.warned[i]=c.current,await BP(o,a),await ne({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var sb,rb,ub=k(()=>{"use strict";je();Ie();pi();Mt();Zt();sb=48*3600*1e3,rb=500;s(ab,"crossSessionDir");s(jP,"parseSessionDb");s(cb,"pruneDb");s(FP,"decideCrossSession");s(ob,"staleReason");s(HP,"dbPath");s(UP,"loadDb");s(BP,"saveDb");s(A9,"sweepStaleSessionFiles");s(KP,"fileMtime");s(C9,"runGuardCrossObserve");s(R9,"runGuardCrossCheck")});var JP={};ee(JP,{decideDocDutyReminder:()=>WP,decideLocally:()=>pb,localDocFacts:()=>VP,readServerDocState:()=>zP,reminderStateDir:()=>qP,runDocDutyReminder:()=>j9});import{execFileSync as I9}from"node:child_process";import{existsSync as N9,mkdirSync as O9,readFileSync as GP,writeFileSync as D9}from"node:fs";import{homedir as P9}from"node:os";import{join as db}from"node:path";function pb(e){return e.standsDown?{remind:!1,why:"host"}:e.stopHookActive?{remind:!1,why:"stop_hook_active"}:e.object?e.alreadyReminded?{remind:!1,why:"already_reminded"}:e.hasWork?e.locallySatisfied?{remind:!1,why:"locally_satisfied"}:null:{remind:!1,why:"no_work"}:{remind:!1,why:"no_object"}}function WP(e){let t=pb(e);if(t)return t;let n=e.object.key;if(e.server?.docDuty==="off")return{remind:!1,why:"duty_off"};if(e.server&&!e.server.docMissing)return{remind:!1,why:"documented_elsewhere"};let r=e.server?.docDuty==="require";return{remind:!0,reason:`[maind] Documentation duty for ${n} is still open: this work has no document that names ${n} and no recorded exception. Before you finish, either add or update a Markdown document (ADR, note, session note) that names ${n}, or \u2014 if none is needed \u2014 put a trailer in a commit: "Doc-Decision: none - <reason>" (or "Doc-Decision: elsewhere - <owner/repo#pr>").`+(r?" This organization requires it: `maind feature promote` refuses to merge without it.":"")+` This reminder comes once per session for ${n}.`}}function qa(e,t){try{return I9("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:8*1024*1024})}catch{return null}}function M9(e){let t=qa(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),n=t?[t.replace(/^refs\/remotes\//,"")]:["origin/main","origin/master"];for(let r of n){let o=qa(e,["merge-base",r,"HEAD"])?.trim();if(o)return o}return null}function VP(e,t){let n=M9(e),r=n?(qa(e,["-c","core.quotepath=off","diff","--name-only",`${n}`,"HEAD"])??"").split(`
1182
+ `),a.warned[i]=c.current,await BP(o,a),await ne({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var sb,rb,ub=k(()=>{"use strict";je();Ie();pi();Mt();Zt();sb=48*3600*1e3,rb=500;s(ab,"crossSessionDir");s(jP,"parseSessionDb");s(cb,"pruneDb");s(FP,"decideCrossSession");s(ob,"staleReason");s(HP,"dbPath");s(UP,"loadDb");s(BP,"saveDb");s(A3,"sweepStaleSessionFiles");s(KP,"fileMtime");s(C3,"runGuardCrossObserve");s(R3,"runGuardCrossCheck")});var JP={};ee(JP,{decideDocDutyReminder:()=>WP,decideLocally:()=>pb,localDocFacts:()=>VP,readServerDocState:()=>zP,reminderStateDir:()=>qP,runDocDutyReminder:()=>j3});import{execFileSync as I3}from"node:child_process";import{existsSync as N3,mkdirSync as O3,readFileSync as GP,writeFileSync as D3}from"node:fs";import{homedir as P3}from"node:os";import{join as db}from"node:path";function pb(e){return e.standsDown?{remind:!1,why:"host"}:e.stopHookActive?{remind:!1,why:"stop_hook_active"}:e.object?e.alreadyReminded?{remind:!1,why:"already_reminded"}:e.hasWork?e.locallySatisfied?{remind:!1,why:"locally_satisfied"}:null:{remind:!1,why:"no_work"}:{remind:!1,why:"no_object"}}function WP(e){let t=pb(e);if(t)return t;let n=e.object.key;if(e.server?.docDuty==="off")return{remind:!1,why:"duty_off"};if(e.server&&!e.server.docMissing)return{remind:!1,why:"documented_elsewhere"};let r=e.server?.docDuty==="require";return{remind:!0,reason:`[maind] Documentation duty for ${n} is still open: this work has no document that names ${n} and no recorded exception. Before you finish, either add or update a Markdown document (ADR, note, session note) that names ${n}, or \u2014 if none is needed \u2014 put a trailer in a commit: "Doc-Decision: none - <reason>" (or "Doc-Decision: elsewhere - <owner/repo#pr>").`+(r?" This organization requires it: `maind feature promote` refuses to merge without it.":"")+` This reminder comes once per session for ${n}.`}}function qa(e,t){try{return I3("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:8*1024*1024})}catch{return null}}function M3(e){let t=qa(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),n=t?[t.replace(/^refs\/remotes\//,"")]:["origin/main","origin/master"];for(let r of n){let o=qa(e,["merge-base",r,"HEAD"])?.trim();if(o)return o}return null}function VP(e,t){let n=M3(e),r=n?(qa(e,["-c","core.quotepath=off","diff","--name-only",`${n}`,"HEAD"])??"").split(`
1183
1183
  `):[],i=(qa(e,["-c","core.quotepath=off","status","--porcelain","--untracked-files=all"])??"").split(`
1184
- `).filter(d=>d.length>3).map(d=>d.slice(3).replace(/^.* -> /,"").replace(/^"|"$/g,"")),a=[...new Set([...r,...i].map(d=>d.trim()).filter(Boolean))],c=a.length>0;if(!c)return{hasWork:c,locallySatisfied:!1};if(es(a.filter(Lo),d=>{try{return GP(db(e,d),"utf8")}catch{return null}},t).length>0)return{hasWork:c,locallySatisfied:!0};let u=n?(qa(e,["log","--reverse","--format=%B%x00",`${n}..HEAD`])??"").split("\0"):[];return{hasWork:c,locallySatisfied:ts(u).kind==="ok"}}function qP(){return db(P9(),".maind","doc-duty")}function $9(e){return e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}function L9(e){try{let t=JSON.parse(GP(e,"utf8"));return Array.isArray(t.reminded)?t.reminded.filter(n=>typeof n=="string"):[]}catch{return[]}}function zP(e,t){if(!e)return null;try{let n=JSON.parse(e),o=(Array.isArray(n.resolved)?n.resolved:[]).find(a=>a?.key===t);if(!o)return null;let i=o.doc_duty;return i!=="off"&&i!=="remind"&&i!=="require"?null:{docDuty:i,docMissing:o.doc_missing===!0}}catch{return null}}async function j9(){try{let e=await de(),t=typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():null,n=typeof e.cwd=="string"&&e.cwd.trim()?e.cwd:process.cwd(),r=Ce(e),o=e.stop_hook_active===!0;if(r||o||t===null)return 0;let i=te();if(i===null)return 0;let a=vn(Pt(i),{hostPids:ct(),cwd:n})?.snap;if(!a||a.announce_error)return 0;let c=_i({branchObjectId:a.branch_object_id??null,boundObjects:a.bound_objects??null});if(c.objectId===null||!c.key)return 0;let l={id:c.objectId,key:c.key},u=qP(),d=db(u,`${$9(t)}.json`),p=N9(d)?L9(d):[],f=VP(n,l.key);if(pb({standsDown:r,stopHookActive:o,object:l,alreadyReminded:p.includes(l.id),...f}))return 0;let g=Y(),y=g?await $t("get_my_work_objects",{project_key:i,session_id:a.own_session_id,keys:[l.key]},{apiKey:g,deviceId:me(),projectKey:i,bridgeVersion:G,timeoutMs:3e3}):null,_=WP({standsDown:r,stopHookActive:o,object:l,alreadyReminded:!1,...f,server:zP(y,l.key)});return _.remind&&(O9(u,{recursive:!0}),D9(d,JSON.stringify({reminded:[...p,l.id]})),process.stdout.write(JSON.stringify({decision:"block",reason:_.reason}))),0}catch{return 0}}var YP=k(()=>{"use strict";an();oo();he();xn();so();pe();ze();ua();je();Ie();en();s(pb,"decideLocally");s(WP,"decideDocDutyReminder");s(qa,"git");s(M9,"mergeBase");s(VP,"localDocFacts");s(qP,"reminderStateDir");s($9,"safeName");s(L9,"readReminded");s(zP,"readServerDocState");s(j9,"runDocDutyReminder")});import{randomUUID as F9}from"node:crypto";He();Cs();import{createInterface as _H}from"node:readline";var J1=[["claude-code","claude-code"],["claude-cli","claude-code"],["claude-desktop","claude-desktop"],["claude.app","claude-desktop"],["openai-codex","codex"],["codex-cli","codex"],["codex","codex"],["github-copilot","copilot"],["vscode-copilot","copilot"],["copilot","copilot"],["cursor","cursor"],["windsurf","windsurf"],["codeium","windsurf"],["cline","cline"],["continue","continue"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function Y1(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of J1)if(t.includes(n))return r;return null}s(Y1,"mapClientInfoNameToFamily");function rE(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Pm(t)||t.method!=="initialize")return null;let n=t.params;if(!Pm(n))return null;let r=n.clientInfo;if(!Pm(r))return null;let o=r.name,i=Y1(typeof o=="string"?o:null);if(i===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:c}}s(rE,"tryExtractInitializeClient");function Pm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Pm,"isRecord");import{fileURLToPath as X1}from"node:url";var Mm="maind-bridge-",Z1=8,oE=8e3;function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ln,"isRecord");function Q1(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Ln(t)||t.method!=="initialize"||!Ln(t.params))return!1;let n=t.params.capabilities;return Ln(n)&&Ln(n.roots)}catch{return!1}}s(Q1,"clientDeclaresRoots");function eH(e){if(!e.includes("notifications/initialized"))return!1;try{let t=JSON.parse(e);return t.method==="notifications/initialized"&&t.id===void 0}catch{return!1}}s(eH,"isInitializedNotification");function tH(e){if(!Ln(e)||!Ln(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Ln(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=X1(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=Z1)break}return n}s(tH,"rootPathsFrom");var Qc=class{constructor(t,n=!1){this.writeLine=t;this.initialized=n}static{s(this,"ClientRequestChannel")}initialized;closed=!1;waiters=[];pending=new Map;seq=0;observe(t){if(t.includes(Mm)){let n;try{n=JSON.parse(t)}catch{n=null}if(Ln(n)&&typeof n.id=="string"&&n.id.startsWith(Mm)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&eH(t)){this.initialized=!0;for(let n of this.waiters.splice(0))n(!0)}return!1}close(){if(!this.closed){this.closed=!0;for(let t of this.waiters.splice(0))t(!1);for(let t of[...this.pending.values()])t.settle(null)}}async request(t,n=oE){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(c=>{let l=s(d=>{clearTimeout(u),this.waiters=this.waiters.filter(p=>p!==l),c(d)},"done"),u=setTimeout(()=>l(!1),n);this.waiters.push(l)})||this.closed))return null;let o=`${Mm}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,i=new Promise(a=>{let c=s(u=>{clearTimeout(l),this.pending.delete(o),a(u)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(o,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:o,method:t})),i}};async function iE(e,t,n=oE){return Q1(e)?tH(await t.request("roots/list",n)):null}s(iE,"listClientRoots");Fm();Hm();function Um(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let i=JSON.parse(t);return Array.isArray(i)?i:[i]}catch{return[]}let n=[],r=[],o=s(()=>{if(r.length===0)return;let i=r.join(`
1184
+ `).filter(d=>d.length>3).map(d=>d.slice(3).replace(/^.* -> /,"").replace(/^"|"$/g,"")),a=[...new Set([...r,...i].map(d=>d.trim()).filter(Boolean))],c=a.length>0;if(!c)return{hasWork:c,locallySatisfied:!1};if(es(a.filter(Lo),d=>{try{return GP(db(e,d),"utf8")}catch{return null}},t).length>0)return{hasWork:c,locallySatisfied:!0};let u=n?(qa(e,["log","--reverse","--format=%B%x00",`${n}..HEAD`])??"").split("\0"):[];return{hasWork:c,locallySatisfied:ts(u).kind==="ok"}}function qP(){return db(P3(),".maind","doc-duty")}function $3(e){return e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}function L3(e){try{let t=JSON.parse(GP(e,"utf8"));return Array.isArray(t.reminded)?t.reminded.filter(n=>typeof n=="string"):[]}catch{return[]}}function zP(e,t){if(!e)return null;try{let n=JSON.parse(e),o=(Array.isArray(n.resolved)?n.resolved:[]).find(a=>a?.key===t);if(!o)return null;let i=o.doc_duty;return i!=="off"&&i!=="remind"&&i!=="require"?null:{docDuty:i,docMissing:o.doc_missing===!0}}catch{return null}}async function j3(){try{let e=await de(),t=typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():null,n=typeof e.cwd=="string"&&e.cwd.trim()?e.cwd:process.cwd(),r=Ce(e),o=e.stop_hook_active===!0;if(r||o||t===null)return 0;let i=te();if(i===null)return 0;let a=vn(Pt(i),{hostPids:ct(),cwd:n})?.snap;if(!a||a.announce_error)return 0;let c=_i({branchObjectId:a.branch_object_id??null,boundObjects:a.bound_objects??null});if(c.objectId===null||!c.key)return 0;let l={id:c.objectId,key:c.key},u=qP(),d=db(u,`${$3(t)}.json`),p=N3(d)?L3(d):[],f=VP(n,l.key);if(pb({standsDown:r,stopHookActive:o,object:l,alreadyReminded:p.includes(l.id),...f}))return 0;let g=Y(),y=g?await $t("get_my_work_objects",{project_key:i,session_id:a.own_session_id,keys:[l.key]},{apiKey:g,deviceId:me(),projectKey:i,bridgeVersion:G,timeoutMs:3e3}):null,_=WP({standsDown:r,stopHookActive:o,object:l,alreadyReminded:!1,...f,server:zP(y,l.key)});return _.remind&&(O3(u,{recursive:!0}),D3(d,JSON.stringify({reminded:[...p,l.id]})),process.stdout.write(JSON.stringify({decision:"block",reason:_.reason}))),0}catch{return 0}}var YP=k(()=>{"use strict";an();oo();he();xn();so();pe();ze();ua();je();Ie();en();s(pb,"decideLocally");s(WP,"decideDocDutyReminder");s(qa,"git");s(M3,"mergeBase");s(VP,"localDocFacts");s(qP,"reminderStateDir");s($3,"safeName");s(L3,"readReminded");s(zP,"readServerDocState");s(j3,"runDocDutyReminder")});import{randomUUID as F3}from"node:crypto";He();Cs();import{createInterface as _H}from"node:readline";var J1=[["claude-code","claude-code"],["claude-cli","claude-code"],["claude-desktop","claude-desktop"],["claude.app","claude-desktop"],["openai-codex","codex"],["codex-cli","codex"],["codex","codex"],["github-copilot","copilot"],["vscode-copilot","copilot"],["copilot","copilot"],["cursor","cursor"],["windsurf","windsurf"],["codeium","windsurf"],["cline","cline"],["continue","continue"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function Y1(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of J1)if(t.includes(n))return r;return null}s(Y1,"mapClientInfoNameToFamily");function rE(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Pm(t)||t.method!=="initialize")return null;let n=t.params;if(!Pm(n))return null;let r=n.clientInfo;if(!Pm(r))return null;let o=r.name,i=Y1(typeof o=="string"?o:null);if(i===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:c}}s(rE,"tryExtractInitializeClient");function Pm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Pm,"isRecord");import{fileURLToPath as X1}from"node:url";var Mm="maind-bridge-",Z1=8,oE=8e3;function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ln,"isRecord");function Q1(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!Ln(t)||t.method!=="initialize"||!Ln(t.params))return!1;let n=t.params.capabilities;return Ln(n)&&Ln(n.roots)}catch{return!1}}s(Q1,"clientDeclaresRoots");function eH(e){if(!e.includes("notifications/initialized"))return!1;try{let t=JSON.parse(e);return t.method==="notifications/initialized"&&t.id===void 0}catch{return!1}}s(eH,"isInitializedNotification");function tH(e){if(!Ln(e)||!Ln(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!Ln(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=X1(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=Z1)break}return n}s(tH,"rootPathsFrom");var Qc=class{constructor(t,n=!1){this.writeLine=t;this.initialized=n}static{s(this,"ClientRequestChannel")}initialized;closed=!1;waiters=[];pending=new Map;seq=0;observe(t){if(t.includes(Mm)){let n;try{n=JSON.parse(t)}catch{n=null}if(Ln(n)&&typeof n.id=="string"&&n.id.startsWith(Mm)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&eH(t)){this.initialized=!0;for(let n of this.waiters.splice(0))n(!0)}return!1}close(){if(!this.closed){this.closed=!0;for(let t of this.waiters.splice(0))t(!1);for(let t of[...this.pending.values()])t.settle(null)}}async request(t,n=oE){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(c=>{let l=s(d=>{clearTimeout(u),this.waiters=this.waiters.filter(p=>p!==l),c(d)},"done"),u=setTimeout(()=>l(!1),n);this.waiters.push(l)})||this.closed))return null;let o=`${Mm}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,i=new Promise(a=>{let c=s(u=>{clearTimeout(l),this.pending.delete(o),a(u)},"settle"),l=setTimeout(()=>c(null),Math.max(0,r-Date.now()));this.pending.set(o,{settle:c,timer:l})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:o,method:t})),i}};async function iE(e,t,n=oE){return Q1(e)?tH(await t.request("roots/list",n)):null}s(iE,"listClientRoots");Fm();Hm();function Um(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let i=JSON.parse(t);return Array.isArray(i)?i:[i]}catch{return[]}let n=[],r=[],o=s(()=>{if(r.length===0)return;let i=r.join(`
1185
1185
  `).trim();if(r=[],i.length!==0)try{n.push(JSON.parse(i))}catch{}},"flush");for(let i of t.split(`
1186
1186
  `)){let a=i.endsWith("\r")?i.slice(0,-1):i;if(a===""){o();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return o(),n}s(Um,"rpcMessagesOf");function pE(e,t){for(let n of Um(e)){if(typeof n!="object"||n===null)continue;let r=n;if(r.id!==t)continue;if(typeof r.error=="object"&&r.error!==null){let c=r.error;return{kind:"rpc_error",code:typeof c.code=="number"?c.code:-32603,message:typeof c.message=="string"?c.message:""}}let o=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(o.content)?o.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:o.isError===!0,text:a?.text??""}}return null}s(pE,"parseCloudToolResponse");qt();var bH="https://mcp.maind.dev/mcp",Rs=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},sl=class{static{s(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;onSessionReady;assignedInbox;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;stackHeader;initFrame=null;pendingFrame=null;clientChannel;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=jn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=kH(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=wH(r),this.clientVersionLocked=this.clientVersion!==null;let o=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=o&&/^[a-f0-9]{64}$/.test(o)?o:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.onConnectionOutcome=t.onConnectionOutcome??null,this.onSessionReady=t.onSessionReady??null,this.assignedInbox=t.assignedInbox??null;let i=t.carry??null;i!==null&&(this.initFrame=i.initFrame,this.clientFamily===null&&(this.clientFamily=i.clientFamily),this.clientVersion===null&&(this.clientVersion=i.clientVersion),this.replayFrame=i.pendingFrame),this.clientChannel=new Qc(a=>process.stdout.write(a+`
1187
1187
  `),i!==null&&i.initFrame!==null&&(i.pendingFrame===null||!Yo(i.pendingFrame))),this.shaRepoRoot=el(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??bH,this.stackHeader=CH(this.mcpUrl)?null:RH(t.stack!==void 0?t.stack:fn(this.shaRepoRoot??process.cwd()))}async run(t=Wm()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r){this.clientChannel.close();return}let o=n.trim();o.length!==0&&await this.forwardFrame(o)}}listClientRoots(t){return iE(this.initFrame,this.clientChannel,t)}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!n&&this.clientChannel.observe(t))return;if(!this.clientFamilyLocked&&this.clientFamily===null){let d=rE(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&Yo(t)&&(this.initFrame=t);let r=SH(t),o=null;if(r?.method==="tools/call"){this.presence?.onActivity();let d=tl(t,this.shaRepoRoot);if(d.length>0){let p=d.find(m=>m.verdict==="fabricated"),f=p??d[0];if(p!==void 0&&uE(p)&&r.id!==null){let m=Jo(p,!0);process.stderr.write(`[maind] ${m}
@@ -1203,7 +1203,7 @@ maind: sessions that are already running pick it up when their bridge restarts (
1203
1203
  `)}s(Km,"collectSseText");function ol(e){try{return JSON.parse(e).id??null}catch{return null}}s(ol,"tryExtractId");function Yo(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Yo,"isInitializeRequest");function _E(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}s(_E,"isSessionLossBody");function bE(e){return e instanceof Error?e.message:String(e)}s(bE,"stringifyErr");function EH(e){return e?.name==="TimeoutError"}s(EH,"isTimeoutError");function il(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
1204
1204
  `)}s(il,"emitJsonRpcError");function TH(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(TH,"extractHint");function AH(e){try{let t=Um(e);if(t.length===0)return null;let r=t[t.length-1]?.result?.content?.[0]?.text;return typeof r!="string"?null:JSON.parse(r)}catch{return null}}s(AH,"parsePresenceToolResult");function CH(e){try{return new URL(e).searchParams.has("stack")}catch{return!1}}s(CH,"urlDeclaresStack");function RH(e){let t=e?Ur(e):[];return t.length>0?t.join(","):null}s(RH,"stackHeaderValue");he();Jm();Ym();ze();pe();by();tr();tr();import{readFileSync as g4}from"node:fs";import{join as hO}from"node:path";function Ed(e){return e?Math.ceil(e.length/4):0}s(Ed,"estimateTokens");var gO=1e6,Td=class{static{s(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function yO(e){try{let t=g4(e,"utf8");return t.length>gO?t.slice(0,gO):t}catch{return""}}s(yO,"readFileCapped");function y4(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}s(y4,"distinctFilePaths");function _O(e,t,n,r){try{let o=Ed(n);if(e==="codebase_search"){let i=y4(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=Ed(yO(hO(r,c)));return Math.max(0,a-o)}if(e==="codebase_snippet"){let i=t?.filePath;if(typeof i!="string"||i.length===0)return 0;let a=Ed(yO(hO(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(_O,"measureLocalToolSaved");He();tr();import{createHash as M4}from"node:crypto";He();import{execFileSync as _4}from"node:child_process";import{createHash as b4}from"node:crypto";tr();a_();import{realpathSync as bO}from"node:fs";function k4(e,t){try{return bO(e)===bO(t)}catch{return e===t}}s(k4,"samePath");var __=30,w4=10,kO=20,v4=new Map;function b_(e){return e instanceof Error?e.message:String(e)}s(b_,"msg");function Ad(e){let t=e.split(`
1205
1205
  `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Ad,"firstLine");var wO=s(e=>e?e.slice(0,12):"?","short");async function x4(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await NN(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:b_(c)}}},n);return a.locked?a.value.ok?i?(r.push(`no local index found \u2014 built it now (${a.value.stats.filesParsed} file(s), ${Math.round(a.value.stats.durationMs/1e3)} s).`),{action:"built",files_parsed:a.value.stats.filesParsed,missing:!1}):{action:"refreshed",files_parsed:a.value.stats.filesParsed,missing:!1}:(i||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:i}):(i||r.push("another process holds the index lock (the Stop hook's refresh?) \u2014 reviewing with the existing index; stale files degrade to co_located and keep the run from being attestation-grade."),{action:"kept",note:"lock_busy",missing:i})}s(x4,"refreshIndex");function S4(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(S4,"isEmptyRange");function E4(e){let t=s(r=>`${r.detector_id}\0${r.rule_id}\0${r.title}`,"key"),n=new Set(e.commit.local.map(t));return e.local.local.filter(r=>!n.has(t(r)))}s(E4,"localOnly");function T4(e){let t=[],n=e.diff_stats;return e.base_sha||t.push("base_sha_missing"),n.stale_file_count!==0&&t.push("stale_files"),n.truncated!==!1&&t.push("truncated"),n.hunk_coverage!=="full"&&t.push("hunk_coverage_not_full"),n.detector_coverage!=="full"&&t.push("detector_coverage_not_full"),t}s(T4,"localGradeBlockers");function A4(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=Im(!1,e.projectKey,e.result);if(!t.persist)return t;let n=T4(e.payload);return n.length>0?{persist:!1,skipped:"not_grade_eligible",detail:n}:e.git===null||e.git.defaultBranch===null||e.git.forkPoint===null?{persist:!1,skipped:"fork_point_unknown",detail:[e.git?.defaultBranch?`origin/${e.git.defaultBranch}`:"no default branch"]}:e.git.forkPoint!==e.result.mergeBaseSha?{persist:!1,skipped:"base_not_fork_point",detail:[e.result.mergeBaseSha??"?",e.git.forkPoint,`origin/${e.git.defaultBranch}`]}:e.git.pushed?e.recordedRunId!==null?{persist:!1,skipped:"already_recorded",detail:[e.recordedRunId]}:{persist:!0,skipped:null}:{persist:!1,skipped:"head_not_pushed"}}s(A4,"bridgePersistDecision");function vO(e,t){try{return _4("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(vO,"git");function C4(e,t){let n=us(e),r=n&&vO(e,["merge-base",t,`origin/${n}`])||null,o=vO(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(C4,"gitPersistFacts");function R4(e,t){return b4("sha256").update(`${e??""}
1206
- ${JSON.stringify(t)}`).digest("hex")}s(R4,"payloadKey");function Lt(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(Lt,"fail");var _o="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function xO(e){let t=qo(e);if(t!==null&&Om(t))return Lt("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 Lt("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 Lt("cloud_unavailable",`review_verdict failed: ${Ad(t?.detail??e)||"no detail"}`,_o)}s(xO,"fromProtocolText");function I4(e,t,n){switch(e.kind){case"no_session":return Lt("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. ${_o}`);case"transport_error":return e.timedOut?Lt("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."):Lt("cloud_unavailable",`network error: ${e.message}`,_o);case"http_error":return e.status===401?Lt("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Ad(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?Lt("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."):Lt("cloud_unavailable",`HTTP ${e.status}: ${Ad(e.body)}`,_o);case"rpc_error":return xO(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return xO(e.text);let r;try{r=JSON.parse(e.text)}catch{return Lt("cloud_unavailable",`review_verdict returned non-JSON text: ${Ad(e.text)}`,_o)}return typeof r!="object"||r===null?Lt("cloud_unavailable","review_verdict returned no object",_o):{kind:"verdict",body:r}}}}s(I4,"interpretOutcome");var N4="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).",O4={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"},SO=s(e=>e.map(t=>O4[t]??t).join("; "),"adviceFor");function D4(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: ${SO(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,o]=t??[];return`the reviewed range starts at ${wO(n)}, but this branch forks off ${o??"the default branch"} at ${wO(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${o??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}s(D4,"skipText");function P4(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=SO(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let o=e.reason??"",i=D4(o,e.detail),a=t===!0&&o!=="no_report"?" The run itself is attestation-grade.":"";return i!==null?`Not recorded: ${i}${a}`:`Not recorded (${o||"the server gave no reason"}).${a}`}s(P4,"recordHint");async function EO(e,t,n){let r=n.repoRoot??it(),o=r,i=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let ae=Ai(c,r);if(ae===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(!k4(ae.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};o=ae.repoRoot,i=n.engineFor(o),a=n.projectKeyFor?.(o)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,u=l!==void 0&&t.include_uncommitted===!0,d=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??v4,m=[],g=await x4(i,o,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await i.reviewChanges(Cm(l,u)),_={repo_root:o,since:l??null,include_uncommitted:l===void 0?!0:u,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(S4(y,l,u))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${u?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:_,warnings:m};let b;try{b=await i.reviewDetectorScopes({baseRef:l})}catch(ae){let xo=pt(pn(`reviewDetectorScopes failed: ${b_(ae)}`));b={commit:xo,local:xo},m.push(`repo-health detectors unavailable (${b_(ae)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:w,dropped:v}=Rm(y,b.commit);v>0&&m.push(`${v} symbol(s) exceed the server schema (name > ${zc} or qualified name > ${Jc} chars) and were left out \u2014 this run is not attestation-grade.`);let S=R4(a,w),x=d&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",T=A4({persistWanted:d,since:l,projectKey:a,result:y,payload:w,git:x?(n.persistFacts??C4)(o,y.headSha):null,recordedRunId:f.get(S)??null}),I={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:w.changed_symbols.length,symbols_dropped:v,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,kO),local_only:E4(b).slice(0,kO)}},j=await n.callCloudTool("review_verdict",{attest:w,persist:T.persist,...a?{project_key:a}:{}},{timeoutMs:p}),C=I4(j,p,T.persist);if(C.kind==="error")return{ok:!1,error:C.error,message:C.message,hint:C.hint,base:_,local:I,warnings:m};let M=C.body;if(M.ok!==!0){let ae=M.error==="requires_team"||M.error==="requires_enterprise";return{ok:!1,error:M.error??"unknown_error",message:M.message??"review_verdict returned no message",hint:ae?N4:M.hint??_o,base:_,local:I,warnings:m}}if(M.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:_,local:I,warnings:m};let E=M.attest,R=M.run??null,V=R&&typeof R.id=="string"?{persisted:!0,run_id:R.id,commit_sha:R.commit_sha??null,attestation_format:R.attestation_format??null}:{persisted:!1,reason:T.skipped??M.run_note??"not_persisted",...T.detail?{detail:T.detail}:{}};V.persisted&&f.set(S,R.id);let le=typeof E?.attestation_grade=="boolean"?E.attestation_grade:null,jt=Array.isArray(E?.grade_blockers)?E.grade_blockers:[],kt=M.counts??{},oe=Array.isArray(M.findings)?M.findings:[],Ge=`Verdict ${M.verdict??"?"}: ${kt.block??0} block, ${kt.warn??0} warn, ${kt.note??0} note`+(M.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:M.verdict??null,counts:kt,record:V,attest:E?{attestation_grade:le,grade_blockers:jt,attestation_format:E.attestation_format??null,input_hash:E.input_hash??null,policy_hash:E.policy_hash??null,evaluated_convention_count:E.evaluated_convention_count??null,detector_coverage:E.detector_coverage??null}:null,hint:`${Ge} ${P4(V,le,jt,y.headSha)}`,findings:oe.slice(0,__).map(ae=>({convention_id:ae.convention_id,convention_version:ae.convention_version,severity:ae.severity,action:ae.action,...ae.downgrade_reason?{downgrade_reason:ae.downgrade_reason}:{},summary:ae.summary,matched_changed_symbols:(ae.matched_changed_symbols??[]).slice(0,w4),matched_symbol_count:ae.matched_symbols?.length??0})),...oe.length>__?{findings_not_shown:oe.length-__}:{},detector_findings:M.detector_findings??[],policy_source:M.policy_source??null,coverage_note:Nm(y,E?.evaluated_convention_count,v),base:_,local:I,warnings:m}}s(EO,"runAttestReview");var TO=(()=>{let e=Object.keys(gs),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Cd(e){return M4("sha256").update(e,"utf8").digest("hex")}s(Cd,"nodeKeyHash");var $4=["module","class","interface","function","method","type_alias","enum","variable"],k_=[{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:$4,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 "+TO+" \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 "+TO+", 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."}}}}],w_=new Map([["codebase_review_verdict","attest_review_changes"]]),RO=new Set([...k_.map(e=>e.name),...w_.keys()]),v_=new Set(["attest_review_changes",...[...w_].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function IO(e,t,n,r){if(!v_.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let o=await EO(e,n,r),i=w_.get(t);return i?{...o,renamed:{from:t,to:i,note:`${t} is ${i} since bridge 0.79.0 \u2014 call ${i}; the old name goes in a later minor.`}}:o}s(IO,"dispatchCloudBackedTool");function Ne(e){return typeof e=="string"&&e.length>0?e:void 0}s(Ne,"str");function bo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(bo,"num");function AO(e){if(e===void 0)return{repoRoot:it(),scanDirs:void 0};let t=Ai(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(AO,"anchorRepo");function CO(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}s(CO,"dirNotFound");async function NO(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let o=r.findings.filter(a=>a.status==="open").length,i=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:o,warn_count:i,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${o} blocking (open) + ${i} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,o=Ne(n.for_path);if(o!==void 0){let d=rR(o);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:o,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Pr(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,m=s(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:d.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let i=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(i!==void 0&&i.length>0){let d=new Map,p=[];for(let v of i){let S=Ai(v);if(S===null){p.push(v);continue}let x=d.get(S.repoRoot)??new Set;x.add(S.repoRelDir),d.set(S.repoRoot,x)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],m=[],g=[],y=[];for(let[v,S]of d){let x=[...S],T=x.includes(""),I=await Dr(v,{dirs:T?void 0:x,minFiles:r});f.push({repo_root:v,dirs:T?null:x}),m.push(...I.findings),g.push(...I.facts.namespaces.map(j=>({repo_root:v,dir:j.dir,prefix:j.prefix,file_count:j.fileCount}))),y.push(...I.facts.skipped)}let _=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=it(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:Ne(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),o=s(p=>r.findings.filter(f=>f.status===p),"of"),i=o("open"),a=o("warn"),c=o("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=i.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:c.length,findings:[...i,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${i.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${i.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=Ne(n.dir),o,i;if(r!==void 0){let d=Ai(r);if(d===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};o=d.repoRoot,i=d.repoRelDir===""?void 0:[d.repoRelDir]}else o=it(),i=void 0;let a=Fr(o,{dirs:i,baseRef:Ne(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:o,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:o,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=AO(Ne(n.dir));if(r===null)return CO("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=jr(r.repoRoot,{dirs:r.scanDirs,baseRef:Ne(n.base_ref),includeBaseline:n.include_baseline!==!1}),i="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(o.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=o.findings.filter(l=>l.status==="open"),c=o.findings.filter(l=>l.status==="info");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,base_ref:o.facts.baseRef,projects:o.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:o.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+i}}case"check_migration_ledger_drift":{let r=AO(Ne(n.dir));if(r===null)return CO("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=vm(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:Ne(n.remote_db_url)}),i=o.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(o.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:o.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>o.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=i.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,projects:i,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:u.map(p=>p.id),remote_consulted:o.facts.remoteConsulted,skipped:o.facts.skipped,database_targets:d,hint:(o.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:o.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=Ne(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:Ne(n.kind),limit:bo(n.limit)})).map(i=>({...i,nodeKeyHash:Cd(i.nodeKey)}))}case"codebase_trace":{let r=Ne(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let o=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:o,maxDepth:bo(n.max_depth),limit:bo(n.limit)})}case"codebase_snippet":{let r=Ne(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let o=await e.getCodeSnippet(r);if(!o)throw new Error(`no symbol found for node_key: ${r}`);return{...o,nodeKeyHash:Cd(r)}}case"codebase_map":return e.getArchitecture({topN:bo(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:Ne(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:bo(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language,file:o.filePath,start_line:o.startLine,node_key:o.nodeKey,node_key_hash:Cd(o.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:Ne(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:bo(n.limit)}),o;if(n.include_history!==!1)try{o=Gp(await e.fileHistory({since:Ne(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:Ne(n.since)})}catch(l){i=pt(pn(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:i.coverage},c=i.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Cd(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...o?{history:o}:{}},verdict_args:{detector_findings:i.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:i.coverage,truncated:i.truncated,block_eligible:c,engines:i.engines,findings:i.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${i.findings.length} detector row(s) (${c} block-eligible, coverage ${i.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(i=>typeof i=="string"):void 0,o=await e.fileHistory({paths:r,since:Ne(n.since),limit:bo(n.limit),includeOwnership:n.include_ownership!==!1});return{history:o.history.map(i=>({path:i.path,last_commits:i.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:i.ownership?{top_authors:i.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:i.ownership.commitsInWindow}:null})),regression:o.regression?{since_input:o.regression.sinceInput,since_resolved:o.regression.sinceResolved,truncated:o.regression.truncated,commits:o.regression.commits.map(i=>({sha:i.sha,date_iso:i.dateIso,author_name:i.authorName,subject:i.subject,files_touched:i.filesTouched}))}:null,ownership_window_commits:o.ownershipWindowCommits,paths_truncated:o.pathsTruncated,hint:o.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(NO,"dispatchLocalTool");var Rd=class{constructor(t=iR,n=null,r=it,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return k_}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&RO.has(r)}async handleToolCall(t,n){let r=n??{},o=typeof r.name=="string"?r.name:"",i=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=v_.has(o)?await IO(this.getEngine(),o,i,this.ctx??void 0):await NO(this.getEngine(),o,i),c=JSON.stringify(a,null,2);return this.recordSavings(o,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=tR(a)?`${nR} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(i=>i&&typeof i=="object"?i.name:void 0).filter(i=>typeof i=="string")),o=this.descriptors().filter(i=>!r.has(i.name));return n.result.tools=[...n.result.tools,...o],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let o=_O(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};Zo();var L4="/mcp-client-metrics-ingest",j4=4e3,F4="codebase_search_tokens_saved";async function OO(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Ns()}${L4}`,n=new AbortController,r=setTimeout(()=>n.abort(),j4);try{let o=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:F4,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await o.text().catch(()=>""),o.ok}catch(o){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${o instanceof Error?o.message:String(o)}
1206
+ ${JSON.stringify(t)}`).digest("hex")}s(R4,"payloadKey");function Lt(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(Lt,"fail");var _o="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function xO(e){let t=qo(e);if(t!==null&&Om(t))return Lt("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 Lt("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 Lt("cloud_unavailable",`review_verdict failed: ${Ad(t?.detail??e)||"no detail"}`,_o)}s(xO,"fromProtocolText");function I4(e,t,n){switch(e.kind){case"no_session":return Lt("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. ${_o}`);case"transport_error":return e.timedOut?Lt("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."):Lt("cloud_unavailable",`network error: ${e.message}`,_o);case"http_error":return e.status===401?Lt("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Ad(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?Lt("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."):Lt("cloud_unavailable",`HTTP ${e.status}: ${Ad(e.body)}`,_o);case"rpc_error":return xO(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return xO(e.text);let r;try{r=JSON.parse(e.text)}catch{return Lt("cloud_unavailable",`review_verdict returned non-JSON text: ${Ad(e.text)}`,_o)}return typeof r!="object"||r===null?Lt("cloud_unavailable","review_verdict returned no object",_o):{kind:"verdict",body:r}}}}s(I4,"interpretOutcome");var N4="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).",O4={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"},SO=s(e=>e.map(t=>O4[t]??t).join("; "),"adviceFor");function D4(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: ${SO(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,o]=t??[];return`the reviewed range starts at ${wO(n)}, but this branch forks off ${o??"the default branch"} at ${wO(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${o??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}s(D4,"skipText");function P4(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=SO(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let o=e.reason??"",i=D4(o,e.detail),a=t===!0&&o!=="no_report"?" The run itself is attestation-grade.":"";return i!==null?`Not recorded: ${i}${a}`:`Not recorded (${o||"the server gave no reason"}).${a}`}s(P4,"recordHint");async function EO(e,t,n){let r=n.repoRoot??it(),o=r,i=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let ae=Ai(c,r);if(ae===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(!k4(ae.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};o=ae.repoRoot,i=n.engineFor(o),a=n.projectKeyFor?.(o)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,u=l!==void 0&&t.include_uncommitted===!0,d=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??v4,m=[],g=await x4(i,o,n.lock,m);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:m};let y=await i.reviewChanges(Cm(l,u)),_={repo_root:o,since:l??null,include_uncommitted:l===void 0?!0:u,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(S4(y,l,u))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${u?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:_,warnings:m};let b;try{b=await i.reviewDetectorScopes({baseRef:l})}catch(ae){let xo=pt(pn(`reviewDetectorScopes failed: ${b_(ae)}`));b={commit:xo,local:xo},m.push(`repo-health detectors unavailable (${b_(ae)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:w,dropped:v}=Rm(y,b.commit);v>0&&m.push(`${v} symbol(s) exceed the server schema (name > ${zc} or qualified name > ${Jc} chars) and were left out \u2014 this run is not attestation-grade.`);let S=R4(a,w),x=d&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",T=A4({persistWanted:d,since:l,projectKey:a,result:y,payload:w,git:x?(n.persistFacts??C4)(o,y.headSha):null,recordedRunId:f.get(S)??null}),I={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:w.changed_symbols.length,symbols_dropped:v,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,kO),local_only:E4(b).slice(0,kO)}},j=await n.callCloudTool("review_verdict",{attest:w,persist:T.persist,...a?{project_key:a}:{}},{timeoutMs:p}),C=I4(j,p,T.persist);if(C.kind==="error")return{ok:!1,error:C.error,message:C.message,hint:C.hint,base:_,local:I,warnings:m};let M=C.body;if(M.ok!==!0){let ae=M.error==="requires_team"||M.error==="requires_enterprise";return{ok:!1,error:M.error??"unknown_error",message:M.message??"review_verdict returned no message",hint:ae?N4:M.hint??_o,base:_,local:I,warnings:m}}if(M.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:_,local:I,warnings:m};let E=M.attest,R=M.run??null,V=R&&typeof R.id=="string"?{persisted:!0,run_id:R.id,commit_sha:R.commit_sha??null,attestation_format:R.attestation_format??null}:{persisted:!1,reason:T.skipped??M.run_note??"not_persisted",...T.detail?{detail:T.detail}:{}};V.persisted&&f.set(S,R.id);let le=typeof E?.attestation_grade=="boolean"?E.attestation_grade:null,jt=Array.isArray(E?.grade_blockers)?E.grade_blockers:[],kt=M.counts??{},oe=Array.isArray(M.findings)?M.findings:[],Ge=`Verdict ${M.verdict??"?"}: ${kt.block??0} block, ${kt.warn??0} warn, ${kt.note??0} note`+(M.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:M.verdict??null,counts:kt,record:V,attest:E?{attestation_grade:le,grade_blockers:jt,attestation_format:E.attestation_format??null,input_hash:E.input_hash??null,policy_hash:E.policy_hash??null,evaluated_convention_count:E.evaluated_convention_count??null,detector_coverage:E.detector_coverage??null}:null,hint:`${Ge} ${P4(V,le,jt,y.headSha)}`,findings:oe.slice(0,__).map(ae=>({convention_id:ae.convention_id,convention_version:ae.convention_version,severity:ae.severity,action:ae.action,...ae.downgrade_reason?{downgrade_reason:ae.downgrade_reason}:{},summary:ae.summary,matched_changed_symbols:(ae.matched_changed_symbols??[]).slice(0,w4),matched_symbol_count:ae.matched_symbols?.length??0})),...oe.length>__?{findings_not_shown:oe.length-__}:{},detector_findings:M.detector_findings??[],policy_source:M.policy_source??null,coverage_note:Nm(y,E?.evaluated_convention_count,v),base:_,local:I,warnings:m}}s(EO,"runAttestReview");var TO=(()=>{let e=Object.keys(gs),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Cd(e){return M4("sha256").update(e,"utf8").digest("hex")}s(Cd,"nodeKeyHash");var $4=["module","class","interface","function","method","type_alias","enum","variable"],k_=[{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:$4,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 "+TO+" \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 "+TO+", 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 the repository's code_review convention set (global, the org's org-wide conventions, team conventions bound to this repository \u2014 the same set whoever runs it, ADR-383) 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."}}}}],w_=new Map([["codebase_review_verdict","attest_review_changes"]]),RO=new Set([...k_.map(e=>e.name),...w_.keys()]),v_=new Set(["attest_review_changes",...[...w_].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function IO(e,t,n,r){if(!v_.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let o=await EO(e,n,r),i=w_.get(t);return i?{...o,renamed:{from:t,to:i,note:`${t} is ${i} since bridge 0.79.0 \u2014 call ${i}; the old name goes in a later minor.`}}:o}s(IO,"dispatchCloudBackedTool");function Ne(e){return typeof e=="string"&&e.length>0?e:void 0}s(Ne,"str");function bo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(bo,"num");function AO(e){if(e===void 0)return{repoRoot:it(),scanDirs:void 0};let t=Ai(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(AO,"anchorRepo");function CO(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}s(CO,"dirNotFound");async function NO(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let o=r.findings.filter(a=>a.status==="open").length,i=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:o,warn_count:i,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${o} blocking (open) + ${i} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,o=Ne(n.for_path);if(o!==void 0){let d=rR(o);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:o,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Pr(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,m=s(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:d.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${m(p.number)} is already held (see held_by). Create the file as ${m(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let i=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(i!==void 0&&i.length>0){let d=new Map,p=[];for(let v of i){let S=Ai(v);if(S===null){p.push(v);continue}let x=d.get(S.repoRoot)??new Set;x.add(S.repoRelDir),d.set(S.repoRoot,x)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],m=[],g=[],y=[];for(let[v,S]of d){let x=[...S],T=x.includes(""),I=await Dr(v,{dirs:T?void 0:x,minFiles:r});f.push({repo_root:v,dirs:T?null:x}),m.push(...I.findings),g.push(...I.facts.namespaces.map(j=>({repo_root:v,dir:j.dir,prefix:j.prefix,file_count:j.fileCount}))),y.push(...I.facts.skipped)}let _=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=it(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:Ne(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),o=s(p=>r.findings.filter(f=>f.status===p),"of"),i=o("open"),a=o("warn"),c=o("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=i.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:c.length,findings:[...i,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${i.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${i.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=Ne(n.dir),o,i;if(r!==void 0){let d=Ai(r);if(d===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};o=d.repoRoot,i=d.repoRelDir===""?void 0:[d.repoRelDir]}else o=it(),i=void 0;let a=Fr(o,{dirs:i,baseRef:Ne(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:o,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:o,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=AO(Ne(n.dir));if(r===null)return CO("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=jr(r.repoRoot,{dirs:r.scanDirs,baseRef:Ne(n.base_ref),includeBaseline:n.include_baseline!==!1}),i="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(o.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=o.findings.filter(l=>l.status==="open"),c=o.findings.filter(l=>l.status==="info");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,base_ref:o.facts.baseRef,projects:o.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:o.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+i}}case"check_migration_ledger_drift":{let r=AO(Ne(n.dir));if(r===null)return CO("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=vm(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:Ne(n.remote_db_url)}),i=o.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(o.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:o.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>o.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=i.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,projects:i,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:u.map(p=>p.id),remote_consulted:o.facts.remoteConsulted,skipped:o.facts.skipped,database_targets:d,hint:(o.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:o.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=Ne(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:Ne(n.kind),limit:bo(n.limit)})).map(i=>({...i,nodeKeyHash:Cd(i.nodeKey)}))}case"codebase_trace":{let r=Ne(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let o=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:o,maxDepth:bo(n.max_depth),limit:bo(n.limit)})}case"codebase_snippet":{let r=Ne(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let o=await e.getCodeSnippet(r);if(!o)throw new Error(`no symbol found for node_key: ${r}`);return{...o,nodeKeyHash:Cd(r)}}case"codebase_map":return e.getArchitecture({topN:bo(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:Ne(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:bo(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language,file:o.filePath,start_line:o.startLine,node_key:o.nodeKey,node_key_hash:Cd(o.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:Ne(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:bo(n.limit)}),o;if(n.include_history!==!1)try{o=Gp(await e.fileHistory({since:Ne(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:Ne(n.since)})}catch(l){i=pt(pn(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:i.coverage},c=i.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Cd(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...o?{history:o}:{}},verdict_args:{detector_findings:i.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:i.coverage,truncated:i.truncated,block_eligible:c,engines:i.engines,findings:i.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${i.findings.length} detector row(s) (${c} block-eligible, coverage ${i.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(i=>typeof i=="string"):void 0,o=await e.fileHistory({paths:r,since:Ne(n.since),limit:bo(n.limit),includeOwnership:n.include_ownership!==!1});return{history:o.history.map(i=>({path:i.path,last_commits:i.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:i.ownership?{top_authors:i.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:i.ownership.commitsInWindow}:null})),regression:o.regression?{since_input:o.regression.sinceInput,since_resolved:o.regression.sinceResolved,truncated:o.regression.truncated,commits:o.regression.commits.map(i=>({sha:i.sha,date_iso:i.dateIso,author_name:i.authorName,subject:i.subject,files_touched:i.filesTouched}))}:null,ownership_window_commits:o.ownershipWindowCommits,paths_truncated:o.pathsTruncated,hint:o.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(NO,"dispatchLocalTool");var Rd=class{constructor(t=iR,n=null,r=it,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return k_}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&RO.has(r)}async handleToolCall(t,n){let r=n??{},o=typeof r.name=="string"?r.name:"",i=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=v_.has(o)?await IO(this.getEngine(),o,i,this.ctx??void 0):await NO(this.getEngine(),o,i),c=JSON.stringify(a,null,2);return this.recordSavings(o,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=tR(a)?`${nR} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(i=>i&&typeof i=="object"?i.name:void 0).filter(i=>typeof i=="string")),o=this.descriptors().filter(i=>!r.has(i.name));return n.result.tools=[...n.result.tools,...o],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let o=_O(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};Zo();var L4="/mcp-client-metrics-ingest",j4=4e3,F4="codebase_search_tokens_saved";async function OO(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Ns()}${L4}`,n=new AbortController,r=setTimeout(()=>n.abort(),j4);try{let o=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:F4,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await o.text().catch(()=>""),o.ok}catch(o){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${o instanceof Error?o.message:String(o)}
1207
1207
  `),!1}finally{clearTimeout(r)}}s(OO,"postSavingsMetric");Uy();so();Cs();pe();import{existsSync as H4,readFileSync as U4,readdirSync as B4,statSync as K4}from"node:fs";import{dirname as G4,join as $a,resolve as x_}from"node:path";var W4=8,V4=128;function q4(e){return B4(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>t.name).sort()}s(q4,"defaultListDirs");function z4(e){let t=$a(e,".git");if(!H4(t))return null;if(K4(t).isDirectory())return{isDir:!0,gitdir:null};let n=/^gitdir:\s*(.+)\s*$/m.exec(U4(t,"utf8"));return{isDir:!1,gitdir:n?x_(e,n[1].trim()):null}}s(z4,"defaultGitKind");function J4(e){let t=`${$a(".git","worktrees")}`,n=e.lastIndexOf(t);return n>0?G4($a(e.slice(0,n),".git")):null}s(J4,"mainCheckoutOf");function DO(e,t,n={}){try{let r=n.listDirs??q4,o=n.gitKind??z4,i=n.keyOf??Je,a=r(e).slice(0,V4),c=new Set,l=new Map;for(let d of a)try{let p=o($a(e,d));if(p===null)continue;l.set(d,p),p.isDir&&c.add(x_(e,d))}catch{}let u=new Map;for(let[d,p]of l){if(!p.isDir&&p.gitdir!==null){let g=J4(p.gitdir);if(g!==null&&c.has(x_(g)))continue}let f=null;try{f=i($a(e,d))}catch{f=null}if(f===null||f===t)continue;let m=u.get(f);(!m||p.isDir&&!m.isDir)&&u.set(f,{dir:d,isDir:p.isDir})}return[...u].map(([d,p])=>({dir:p.dir,projectKey:d})).sort((d,p)=>d.dir.localeCompare(p.dir)).slice(0,W4)}catch{return[]}}s(DO,"discoverNestedRepos");pe();import{execFile as Y4}from"node:child_process";var X4=64;function PO(e,t,n){if(e.size>=X4){let r=e.keys().next().value;r!==void 0&&e.delete(r)}e.set(t,n)}s(PO,"remember");var Id=class{static{s(this,"WorkRepoResolver")}agentCwd;repoRootOf;keyOf;roots=new Map;keys=new Map;constructor(t){this.agentCwd=t.agentCwd,this.repoRootOf=t.repoRootOf??Z4,this.keyOf=t.keyOf??Je}async current(){try{let t=this.agentCwd();if(t===null||t.length===0)return null;let n=this.roots.get(t);if(n===void 0&&(n=await this.repoRootOf(t),n!==null&&PO(this.roots,t,n)),n===null)return null;let r=this.keys.get(n);return r===void 0&&(r=this.keyOf(n),r!==null&&PO(this.keys,n,r)),r===null?null:{root:n,projectKey:r}}catch{return null}}};async function Z4(e){return await new Promise(t=>{Y4("git",["rev-parse","--show-toplevel"],{cwd:e,timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);let o=r.trim();t(o.length>0?o:null)})})}s(Z4,"defaultRepoRootOf");qt();pu();Qr();import{join as Q4}from"node:path";var eX="<synthetic>";function S_(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:Q4(Yh,Xh(e.cwd),`${e.transcript_stem}.jsonl`)}s(S_,"transcriptPathFromSideChannel");var Nd=class{constructor(t){this.deps=t}static{s(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let o=await(this.deps.stream??Jh)(n,{start:this.offset});for(let i of o.events)if(i.kind==="title"){let a=i.title.trim();a.length>0&&(this.title=a)}else i.kind==="assistant"&&!i.isSidechain&&typeof i.model=="string"&&i.model.length>0&&i.model!==eX&&(this.model=i.model);o.bytesRead>this.offset&&(this.offset=o.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as tX}from"node:child_process";var nX=8,rX=32;function oX(e){return e.split(`
1208
1208
  `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,rX)}s(oX,"parsePorcelain");function iX(e,t=nX){let n=[];for(let r of e){let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(o.length===0)continue;let i=o.includes("/")?o.slice(0,o.lastIndexOf("/")):o;if(!(i.length===0||n.includes(i))&&(n.push(i),n.length>=t))break}return n}s(iX,"condenseToDirs");async function MO(e=sX){let t=await e();if(t===null)return null;let n=iX(oX(t));return n.length>0?n:null}s(MO,"deriveWorkingPaths");async function sX(){return await new Promise(e=>{tX("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(sX,"defaultGitStatus");var E_=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],aX=["install","refresh-rules","doctor","on-session-end","session-end-run","on-session-briefing","on-session-reminder","on-cursor-session-start","guard","guard-inject","guard-gate","guard-stop","guard-difficulty","guard-outcome","guard-capture","guard-consult","guard-prompt-mark","guard-skip-note","gateway","activity","guard-cross-observe","guard-cross-check","on-index-refresh","index-refresh-run","on-prompt-context","on-read-context","on-hook","on-doc-duty",...E_],cX=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function T_(e){return e.find(t=>!t.startsWith("-"))}s(T_,"firstPositionalOf");function $O(e){let t=T_(e);return t===void 0||!cX.test(t)||aX.includes(t)?null:`maind-mcp-bridge: unknown subcommand "${t}" \u2014 this bridge does not have it (an older version?). Run \`maind-mcp-bridge --help\` for the list.`}s($O,"unknownSubcommandError");A_();import{basename as XO}from"node:path";Qi();wn();var La=3e3,R_=20,ja=3e3,lX=new Set(["Read","NotebookRead","LS"]),uX=new Set(["Glob","Grep"]),dX=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),pX=new Set(["WebFetch","WebSearch"]),fX=new Set(["Bash","Shell","bash","shell"]),UO=new Set(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"]),Hi="mcp__maind__work_object_ask_decision";function I_(e,t){if(UO.has(e)||e===Hi)return null;if(lX.has(e))return"read";if(uX.has(e))return"search";if(dX.has(e))return"edit";if(pX.has(e))return"web";if(fX.has(e)){let n=t.command;return typeof n=="string"?BO(n):"run"}return"other"}s(I_,"actionKindOf");var jO=new Set(["vitest","jest","pytest","mocha","ava","nextest","unittest","phpunit","rspec"]),mX=new Set(["npm","pnpm","yarn","bun","deno","go","cargo","make","just","turbo","nx","dotnet","mvn","gradle","gradlew","swift","mix","rake","tox","nox","python","python3"]),hX=new Set(["npx","pnpx","bunx","npm","pnpm","yarn","bun","deno","node","python","python3","uv","poetry","pipenv","hatch","pdm","rye","cargo","bundle"]),gX=new Set(["git","gh"]),FO=/^[A-Za-z][A-Za-z0-9._:-]*$/,yX=/^test(?:$|[:-])/,_X=/^--test(?:$|[=-])/;function BO(e){let t="run";for(let n of ou(e)){let r=ru(n)[0];if(!r||r===ea)continue;let o=r.split(" ")[0],i=n.trim().split(/\s+/),a=i.findIndex(l=>(l.split("/").pop()??l)===o),c=a>=0?i.slice(a+1):[];if(bX(o,c))return"test";gX.has(o)&&(t="git")}return t}s(BO,"bashActionKind");function bX(e,t){if(jO.has(e))return!0;let n=t.filter(r=>FO.test(r));if(e==="playwright")return n.includes("test");if(e==="node"&&t.some(r=>_X.test(r))||mX.has(e)&&n.some(r=>yX.test(r)))return!0;if(hX.has(e)){let r=t.map(o=>o.includes("/")?o.split("/").pop()??"":o).filter(o=>FO.test(o));if(r.some(o=>jO.has(o))||r.includes("playwright")&&n.includes("test"))return!0}return!1}s(bX,"isTestInvocation");var kX=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,wX=/```[\s\S]*?(?:```|$)/g;function ar(e,t){let n=e.replace(wX," \u2026 ").replace(kX,"").replace(/[ \t]+\n/g,`
1209
1209
  `).replace(/\n{3,}/g,`
@@ -1212,12 +1212,12 @@ ${JSON.stringify(t)}`).digest("hex")}s(R4,"payloadKey");function Lt(e,t,n){retur
1212
1212
 
1213
1213
  ${a}`,2e3)??a}:n.push({type:"thought",body:a});continue}if(r.type==="action"){let a=Math.max(1,Math.min(1e4,Math.floor(r.count)));o&&o.type==="action"&&o.ephemeral!==!0&&o.action===r.kind&&(o.count??1)+a<=1e4?n[n.length-1]={type:"action",action:r.kind,count:(o.count??1)+a}:n.push({type:"action",action:r.kind,count:a});continue}let i=t.textAllowed&&r.text?ar(r.text,2e3):null;if(r.type==="elicitation")n.push({type:"elicitation",...r.decisionId!==null?{decision_id:r.decisionId}:{},...i?{body:i}:{}});else{if(r.type==="response"&&r.textOnly===!0&&!i)continue;n.push({type:r.type,...i?{body:i}:{}})}}return t.ephemeral&&n.push({type:"action",action:t.ephemeral,count:1,ephemeral:!0}),n}s(Pd,"drainItems");function cr(e){let t=null,n=new Map,r=[];for(let i of e)i.type==="thought"?t=i:i.type==="action"?n.set(i.kind,(n.get(i.kind)??0)+i.count):r.push(i);let o=[];t&&o.push(t);for(let[i,a]of n)for(let c=a;c>0;c-=1e4)o.push({type:"action",kind:i,count:Math.min(c,1e4)});return o.push(...r),o}s(cr,"coalesceItems");var N_={steps:[]};function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(Tn,"isRecord");function C_(e){return e==="in_progress"||e==="completed"||e==="canceled"?e:"pending"}s(C_,"stepStatus");function Dd(e){return typeof e=="string"?e:""}s(Dd,"contentOf");function O_(e,t,n,r){if(t==="TodoWrite"){let o=n.todos;return Array.isArray(o)?{steps:o.filter(Tn).map(i=>({id:null,content:Dd(i.content),status:C_(i.status)}))}:null}if(t==="TaskCreate"){let o=Tn(r)&&Tn(r.task)?r.task:null,i=o&&typeof o.id=="string"?o.id:null,a=Dd(n.subject)||Dd(o?.subject);return{steps:[...e.steps,{id:i,content:a,status:"pending"}]}}if(t==="TaskUpdate"){let o=n.taskId;return typeof o!="string"||!e.steps.some(i=>i.id===o)?null:n.status==="deleted"?{steps:e.steps.filter(i=>i.id!==o)}:{steps:e.steps.map(i=>i.id!==o?i:{id:o,content:typeof n.subject=="string"?n.subject:i.content,status:n.status===void 0?i.status:C_(n.status)})}}if(t==="TaskList"){let o=Tn(r)?r.tasks:null;return Array.isArray(o)?{steps:o.filter(Tn).map(i=>({id:typeof i.id=="string"?i.id:null,content:Dd(i.subject),status:C_(i.status)}))}:null}return null}s(O_,"applyPlanTool");function D_(e,t){return e.steps.slice(0,30).map(n=>{let r=t?ar(n.content,200):null;return r?{content:r,status:n.status}:{status:n.status}})}s(D_,"wirePlan");var vX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function HO(e){let t=e.trim();try{return JSON.parse(t)}catch{let n=t.indexOf("{"),r=t.lastIndexOf("}");if(n<0||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}}s(HO,"parseJsonLoose");function KO(e){return typeof e=="string"?[HO(e)]:Array.isArray(e)?e.flatMap(t=>Tn(t)&&t.type==="text"&&typeof t.text=="string"?[HO(t.text)]:[]):Tn(e)?Array.isArray(e.content)?KO(e.content):[e]:[]}s(KO,"jsonCandidates");function P_(e){for(let t of KO(e)){if(!Tn(t)||t.ok!==!0||!Tn(t.decision))continue;let n=t.decision.id;if(typeof n=="string"&&vX.test(n))return{id:n.toLowerCase(),answered:t.answered===!0}}return null}s(P_,"decisionFrom");function M_(e){let t=e.question;return typeof t=="string"&&t.trim().length>0?t:null}s(M_,"questionOf");function $_(e){return e.length>=9&&e.length<=2048&&/^https:\/\/[^/?#@\s\p{Cc}]+([/?#][^\s\p{Cc}]*)?$/u.test(e)}s($_,"isAllowedLinkUrl");function L_(e,t){return e.slice(0,10).map(n=>{let r=t?ar(n.label,60):null;return r?{url:n.url,label:r}:{url:n.url}})}s(L_,"wireLinks");var Ui=30,GO=600-2*Ui,Md=10;function Fa(e,t){let n=Math.max(0,t-e.at)*GO/36e5;return Math.min(Ui,e.tokens+n)}s(Fa,"bucketLevel");function Ha(e,t,n){return{tokens:Fa(e,n)-t,at:n}}s(Ha,"bucketTake");function Bi(e){return/^[a-z][a-z0-9_]{0,39}$/.test(e)?e:"other"}s(Bi,"failureCode");Qi();function F_(e){return new Promise(t=>{setTimeout(t,e).unref?.()})}s(F_,"timerDelay");async function H_(e,t){let n,r=new Promise(o=>{n=setTimeout(()=>o({done:!1}),t),n.unref?.()});try{return await Promise.race([e.then(o=>({done:!0,value:o})),r])}finally{n&&clearTimeout(n)}}s(H_,"timerDeadline");var WO=1e4,VO=1e3,qO=15e3,j_=3,zO=20,JO=200,xX=new Set(["session_ended","agent_session_not_found","no_relation_to_object","object_not_found","invalid_key","auth_rejected","dev_mode_disabled","unknown_tool","invalid_params"]),SX=new Set(["session_ended","agent_session_not_found","invalid_key","auth_rejected","dev_mode_disabled","unknown_tool"]);function U_(e,t,n){let r=e.startActivities??[],o=e.finalResponse??"always",i=null,a=null,c=0,l=null,u=!1,d=!1,p=!1,f=null,m=null,g=Promise.resolve(),y=!1,_=[],b=null,w=new Map,v=new Map,S=N_,x=!1,T=null,I=e.summary??null,j=[],C=!1,M=!1,E=null,R={tokens:Ui,at:n.now()},V=0,le=!1,jt=0,kt=0,oe=0,Ge=0,ae=null,xo={},fr=s(O=>{let $=Bi(O);xo[$]=(xo[$]??0)+1},"fail"),So=s(O=>{l||(l=Bi(O))},"stop"),fb=s(O=>{V=n.now()+Math.max(1,O??60)*1e3,R={tokens:Ui,at:V},le=!0},"obeyRateLimit"),mb=s(O=>{g=g.then(O).catch(()=>fr("internal"))},"enqueue"),An=s(()=>{p||l||y||(y=!0,mb(async()=>{y=!1,await yb(!1)}))},"requestFlush"),hb=s(async O=>{try{let $=await n.deadline(O(),WO);return $.done?$.value:{ok:!1,error:"timeout",retryAfterSeconds:null,transient:!0}}catch{return{ok:!1,error:"unreachable",retryAfterSeconds:null,transient:!0}}},"attempt"),Vi=s(async O=>{let $=await hb(O);return!$.ok&&$.transient&&(fr($.error),await n.delay(VO),$=await hb(O)),$.ok?(jt=0,$):(fr($.error),$.transient?(jt+=1,jt>=zO&&So("unreachable")):xX.has($.error)&&(So($.error),SX.has($.error)&&(u=!0)),$)},"call"),gb=s(async()=>{if(i||l)return;if(c>=j_){So("start_failed");return}c+=1;let O=await Vi(()=>t.start({projectKey:e.projectKey,sessionId:e.sessionId,objectId:e.objectId,...r.length>0?{activities:r}:{}}));if(!O.ok){!O.transient&&O.error!=="rate_limited"&&So(O.error),c>=j_&&So("start_failed");return}if(!O.agentSessionId){So("invalid_response");return}i=O.agentSessionId,a=O.textStored===!0;let $=O.appended??0;if($>0){kt+=$,R=Ha(R,$,n.now());let X=r[r.length-1];E=X&&X.ephemeral===!0&&X.action?X.action:null}(a||T!==null||j.length>0)&&(C=!0)},"ensureStarted"),XP=s(async()=>{if(!i||l||!C)return;C=!1;let O=a&&!M&&I!==null?ar(I,255):null,$=L_(j,a===!0);if(T===null&&O===null&&$.length===0)return;let X=I,be=await Vi(()=>t.start({projectKey:e.projectKey,sessionId:e.sessionId,objectId:e.objectId,...T!==null?{model:T}:{},...O!==null?{summary:O}:{},...$.length>0?{links:$}:{}}));if(be.ok){O!==null&&I===X&&(M=!0);return}be.transient&&(C=!0)},"sendHeader"),ZP=s(O=>{let $=null;for(let X of w.values())X.kind!==null&&O-X.at>=ja&&(!$||X.at>$.at)&&($={kind:X.kind,at:X.at});for(let X of v.values())O-X.at>=ja&&(!$||X.at>$.at)&&($=X);return $?$.kind:null},"currentEphemeral"),QP=s(async O=>{if(!i||l)return;let $=n.now();if(!O&&$<V)return;let X=_.splice(0,_.length),be=le?cr(X):X,wt=O?null:ZP($),Xd=wt!==null&&(be.length>0||wt!==E),_b=a===!0,We=Pd(be,{textAllowed:_b,ephemeral:Xd?wt:null});if(We.length===0)return;let bb=Fa(R,$),kb=O?bb:bb-Md;if(We.length>kb||We.length>50){let Eo=Pd(cr(be),{textAllowed:_b,ephemeral:Xd?wt:null});if(!O&&Eo.length>kb){_.unshift(...cr(be));return}We=Eo}We.length>50&&(Ge+=We.length-50,We=We.slice(We.length-50));let tM=i,Ja=await Vi(()=>t.append({projectKey:e.projectKey,agentSessionId:tM,activities:We}));if(Ja.ok){kt+=We.length,R=Ha(R,We.length,n.now()),le=!1;let Eo=We[We.length-1];E=Eo.ephemeral===!0&&Eo.action?Eo.action:null;return}if(!O&&Ja.error==="rate_limited"){fb(Ja.retryAfterSeconds),_.unshift(...cr(be));return}if(!O&&Ja.transient&&!l){_.unshift(...cr(be));return}Ge+=be.length},"sendActivities"),eM=s(async O=>{if(!i||l||!x)return;let $=n.now();if(!O&&$<V||!O&&Fa(R,$)-Md<1)return;x=!1;let X=i,be=await Vi(()=>t.plan({projectKey:e.projectKey,agentSessionId:X,plan:D_(S,a===!0)}));if(be.ok){oe+=1,R=Ha(R,1,n.now());return}be.error==="rate_limited"&&fb(be.retryAfterSeconds),!O&&(be.transient||be.error==="rate_limited")&&(x=!0)},"sendPlan"),yb=s(async O=>{l||!i&&(await gb(),!i)||(await XP(),await QP(O),await eM(O))},"flushOnce"),Yd=s(()=>{if(_.length<=JO)return;let O=cr(_);_.length=0,_.push(...O)},"capPending"),za=s(()=>{b!==null&&(_.push({type:"thought",text:b}),b=null)},"flushThought");return{begin(){p||d||(d=!0,mb(gb),m=n.every(La,An))},onEvent(O){if(!(p||l))try{if(O.kind==="text"){if(O.subagent)return;za(),b=O.text}else if(O.kind==="tool_start")O.subagent||za(),w.set(O.id,{tool:O.tool,input:O.input,kind:I_(O.tool,O.input),at:n.now(),subagent:O.subagent});else{let $=w.get(O.id);if(!$)return;if(w.delete(O.id),$.kind!==null)_.push({type:"action",kind:$.kind,count:1});else if($.tool===Hi){let X=O.failed?null:P_(O.output);_.push(X&&!X.answered?{type:"elicitation",decisionId:X.id,text:M_($.input)}:{type:"action",kind:"other",count:1})}else if(!$.subagent&&!O.failed){let X=O_(S,$.tool,$.input,O.output);X&&(S=X,x=!0)}}Yd(),_.length>=R_&&An()}catch{fr("internal")}},setModel(O){if(p||l)return;let $=O.trim().slice(0,100);$.length===0||$===T||(T=$,C=!0,An())},setSummary(O){if(p||l)return;let $=O.trim();$.length===0||$===I||(I=$,M=!1,C=!0,An())},addLink(O){p||l||!$_(O.url)||j.some($=>$.url===O.url)||(j.push({url:O.url,label:O.label}),C=!0,An())},step(O,$,X){if(!(p||l)){if(X==="start")v.set(O,{kind:$,at:n.now()-ja});else{let be=v.get(O);if(!be)return;v.delete(O),_.push({type:"action",kind:be.kind,count:1})}An()}},elicit(O){if(!(p||l))try{za(),_.push({type:"elicitation",decisionId:null,text:O}),Yd(),An()}catch{fr("internal")}},endTurn(){p||l||b!==null&&(_.push({type:"response",text:b,textOnly:!0}),b=null,Yd(),An())},close(O){return f||(p=!0,m?.clear(),d?(f=(async()=>{try{for(let wt of w.values())wt.kind!==null&&_.push({type:"action",kind:wt.kind,count:1});w.clear();for(let wt of v.values())_.push({type:"action",kind:wt.kind,count:1});v.clear();let $=O.endState;$==="complete"?o==="always"?_.push({type:"response",text:b}):b!==null&&_.push({type:"response",text:b,textOnly:!0}):(za(),_.push({type:"error",text:O.reasonText??null})),b=null;let X=(async()=>{if(await g,await yb(!0),!i||u)return;let wt=i;(await Vi(()=>t.end({projectKey:e.projectKey,agentSessionId:wt,endState:$}))).ok&&(ae=$)})();(await n.deadline(X,qO)).done||fr("close_timeout")}catch{fr("internal")}Ge+=_.length,_.length=0})(),f):(f=Promise.resolve(),f))},record(){return{agentSessionId:i,textStored:a,sent:kt,plans:oe,dropped:Ge,endState:ae,failures:{...xo},stoppedBy:l}}}}s(U_,"makeActivityReporter");var B_="work_object_report_activity",EX=new Set(["rpc_failed","session_not_announced"]);function K_(e){let t=e!==null&&typeof e=="object"?e:{};if(t.ok===!0){let r=t.agent_session,o=r!==null&&typeof r=="object"?r:{};return{ok:!0,agentSessionId:typeof o.id=="string"?o.id:null,textStored:typeof t.text_stored=="boolean"?t.text_stored:null,appended:typeof t.appended=="number"?t.appended:null}}let n=typeof t.error=="string"?Bi(t.error):"invalid_response";return{ok:!1,error:n,retryAfterSeconds:typeof t.retry_after_seconds=="number"?t.retry_after_seconds:null,transient:EX.has(n)}}s(K_,"activityAnswerFrom");var Ua={start:s(e=>({op:"start",project_key:e.projectKey,session_id:e.sessionId,object_id:e.objectId,...e.model!==void 0?{model:e.model}:{},...e.summary!==void 0?{summary:e.summary}:{},...e.links!==void 0?{links:[...e.links]}:{},...e.activities!==void 0?{activities:[...e.activities]}:{}}),"start"),append:s(e=>({op:"append",project_key:e.projectKey,agent_session_id:e.agentSessionId,activities:[...e.activities]}),"append"),plan:s(e=>({op:"plan",project_key:e.projectKey,agent_session_id:e.agentSessionId,plan:[...e.plan]}),"plan"),end:s(e=>({op:"end",project_key:e.projectKey,agent_session_id:e.agentSessionId,end_state:e.endState}),"end")};function G_(e){return{start:s(t=>e(Ua.start(t)),"start"),append:s(t=>e(Ua.append(t)),"append"),plan:s(t=>e(Ua.plan(t)),"plan"),end:s(t=>e(Ua.end(t)),"end")}}s(G_,"activityTransportFrom");oo();var TX="AskUserQuestion",AX=/^mcp__.+__work_object_ask_decision$/,CX="<synthetic>",RX=new Set(["end_turn","stop_sequence","max_tokens","refusal"]),IX=new Set(["stop_hook_summary","turn_duration"]);function ko(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(ko,"isRecord");function NX(e){let t=e.questions;if(Array.isArray(t)){let r=t.filter(ko).map(o=>o.question).filter(o=>typeof o=="string"&&o.trim().length>0);if(r.length>0)return r.join(`
1214
1214
  `)}let n=e.question;return typeof n=="string"&&n.trim().length>0?n:null}s(NX,"questionText");var Ba=class{static{s(this,"TranscriptEventMapper")}turnEnding=!1;questions=new Set;lastModel=null;lastTitle=null;map(t){try{if(!ko(t)||t.isSidechain===!0)return[];switch(t.type){case"assistant":return this.assistant(t);case"user":return this.user(t);case"system":return typeof t.subtype=="string"&&IX.has(t.subtype)?this.turnEnd():[];case"ai-title":{let n=typeof t.aiTitle=="string"?t.aiTitle.trim():"";return n.length===0||n===this.lastTitle?[]:(this.lastTitle=n,[{kind:"title",title:n}])}case"pr-link":{let n=t.prUrl,r=t.prNumber;return typeof n!="string"||n.length===0?[]:[{kind:"link",url:n,label:typeof r=="number"?`PR #${r}`:"Pull request"}]}default:return[]}}catch{return[]}}idle(){return this.turnEnding?this.turnEnd():[]}turnEnd(){return this.turnEnding=!1,[{kind:"turn_end"}]}assistant(t){let n=t.message;if(!ko(n))return[];let r=[],o=n.model;typeof o=="string"&&o.length>0&&o!==CX&&o!==this.lastModel&&(this.lastModel=o,r.push({kind:"model",model:o}));let i=n.content;if(Array.isArray(i)){for(let c of i)if(ko(c)){if(c.type==="text"){let l=c.text;typeof l=="string"&&l.trim().length>0&&r.push({kind:"text",text:l,subagent:!1})}else if(c.type==="tool_use"){let l=c.id,u=c.name;if(typeof l!="string"||typeof u!="string")continue;let d=ko(c.input)?c.input:{};if(this.turnEnding=!1,u===TX){this.questions.add(l),r.push({kind:"question",text:NX(d)});continue}r.push({kind:"tool_start",id:l,tool:AX.test(u)?Hi:u,input:d,subagent:!1})}}}let a=n.stop_reason;return typeof a=="string"&&(this.turnEnding=RX.has(a)),r}user(t){if(t.isMeta===!0||t.isCompactSummary===!0||t.isVisibleInTranscriptOnly===!0)return[];let n=t.message,r=ko(n)?n.content:void 0,o=Array.isArray(r)?r.filter(c=>ko(c)&&c.type==="tool_result"&&typeof c.tool_use_id=="string"):[];if(o.length===0)return this.turnEnd();let i=o.length===1&&"toolUseResult"in t?t.toolUseResult:void 0,a=[];for(let c of o){let l=c.tool_use_id;this.questions.delete(l)||a.push({kind:"tool_end",id:l,failed:c.is_error===!0,output:i!==void 0?i:c.content??null,subagent:!1})}return a}};import{open as OX,stat as DX}from"node:fs/promises";var PX={async stat(e){try{let t=await DX(e);return{size:t.size,id:`${t.dev}:${t.ino}`}}catch{return null}},async read(e,t,n){let r=await OX(e,"r");try{let o=Buffer.alloc(n),{bytesRead:i}=await r.read(o,0,n,t);return o.subarray(0,i)}finally{await r.close()}}},MX=4*1024*1024,$X=16*1024*1024,YO=10,$d=class{constructor(t=PX,n=MX,r=$X){this.file=t;this.maxRead=n;this.maxLine=r}static{s(this,"TranscriptTail")}path=null;id=null;offset=0;partial=[];partialBytes=0;skipToNewline=!1;anchored=!1;reset(){this.path=null,this.id=null,this.offset=0,this.clearPartial(),this.skipToNewline=!1,this.anchored=!1}async poll(t){if(t===null)return this.reset(),[];let n=await this.file.stat(t);if(!this.anchored||t!==this.path)return this.path=t,await this.anchor(t,n),[];if(n===null)return[];if(this.id===null)this.id=n.id,this.offset=0,this.clearPartial(),this.skipToNewline=!1;else if(n.id!==this.id||n.size<this.offset)return await this.anchor(t,n),[];if(n.size<=this.offset)return[];let r=Math.min(n.size-this.offset,this.maxRead),o=await this.file.read(t,this.offset,r);return o.length===0?[]:(this.offset+=o.length,this.consume(o))}async anchor(t,n){if(this.anchored=!0,this.clearPartial(),this.skipToNewline=!1,n===null){this.id=null,this.offset=0;return}if(this.id=n.id,this.offset=n.size,n.size!==0)try{let r=await this.file.read(t,n.size-1,1);this.skipToNewline=r.length!==1||r[0]!==YO}catch{this.skipToNewline=!0}}clearPartial(){this.partial=[],this.partialBytes=0}consume(t){let n=[],r=0;for(;;){let i=t.indexOf(YO,r);if(i===-1)break;let a=t.subarray(r,i);if(r=i+1,this.skipToNewline){this.skipToNewline=!1,this.clearPartial();continue}let c=this.partialBytes>0?Buffer.concat([...this.partial,a]):a;if(this.clearPartial(),c.length>this.maxLine)continue;let l=LX(c);l!==void 0&&n.push(l)}let o=t.subarray(r);return o.length>0&&!this.skipToNewline&&(this.partialBytes+o.length>this.maxLine?(this.clearPartial(),this.skipToNewline=!0):(this.partial.push(Buffer.from(o)),this.partialBytes+=o.length)),n}};function LX(e){let t=e.toString("utf8").trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}s(LX,"parseLine");var jX=La,FX=2e3,HX=5*6e4,UX=10,BX=new Set(["unknown_tool","invalid_params","dev_mode_disabled","invalid_key","auth_rejected"]),KX={now:s(()=>Date.now(),"now"),every:s((e,t)=>{let n=setInterval(t,e);return n.unref?.(),{clear:s(()=>clearInterval(n),"clear")}},"every"),delay:F_,deadline:H_},Ld=class{constructor(t){this.deps=t;this.clock=t.clock??KX,this.tail=t.tail??new $d,this.log=t.log??(n=>process.stderr.write(n+`
1215
- `))}static{s(this,"ActivityProducer")}clock;tail;log;mapper=new Ba;ticker=null;busy=!1;stopping=!1;path=null;current=null;closing=new Set;flushers=new Set;model=null;title=null;links=[];cooldownUntil=new Map;blocked=new Set;loggedOwnError=!1;get isEnabled(){return this.deps.enabled&&this.deps.projectKey!==null}state(){return{ticking:this.ticker!==null,objectId:this.current?.objectId??null,agentSessionId:this.current?.reporter.record().agentSessionId??null}}refresh(){try{if(!this.isEnabled||this.stopping||this.ticker!==null||this.safeTarget().objectId===null)return;this.tail.reset(),this.path=null,this.ticker=this.clock.every(jX,()=>void this.tick())}catch(t){this.ownError(t)}}async tick(){if(!(!this.isEnabled||this.stopping||this.busy)){this.busy=!0;try{await this.step()}catch(t){this.ownError(t)}finally{this.busy=!1}}}async shutdown(t=FX){if(!this.stopping){this.stopping=!0;try{this.ticker?.clear(),this.ticker=null;let n=(async()=>{if(this.isEnabled&&!this.busy&&this.current!==null)try{await this.step()}catch{}this.retire(),await Promise.all([...this.closing])})();await this.clock.deadline(n,t)}catch{}}}async step(){let t=this.safeTarget(),n=null;try{n=this.deps.transcriptPath()}catch{n=null}if(n===null&&(n=this.path),n!==this.path&&(this.path!==null&&n!==null&&XO(this.path)===XO(n)||(this.retire(),this.mapper=new Ba,this.model=null,this.title=null),this.path=n),t.objectId===null){this.retire(),this.ticker?.clear(),this.ticker=null,this.tail.reset(),this.path=null;return}this.current!==null&&this.current.objectId!==t.objectId&&this.retire(),this.current!==null&&this.checkStopped();let r=await this.tail.poll(n),o=[];for(let i of r)o.push(...this.mapper.map(i));r.length===0&&o.push(...this.mapper.idle());for(let i of o)this.dispatch(i,t);for(let i of[...this.flushers])i()}dispatch(t,n){switch(t.kind){case"model":this.model=t.model,this.current?.reporter.setModel(t.model);return;case"title":this.title=t.title,this.current?.reporter.setSummary(t.title);return;case"link":this.links.length<UX&&!this.links.some(r=>r.url===t.url)&&this.links.push({url:t.url,label:t.label}),this.current?.reporter.addLink({url:t.url,label:t.label});return;case"turn_end":this.current?.reporter.endTurn();return;case"tool_end":this.current?.reporter.onEvent(t);return;case"question":{this.ensureReporter(n)?.elicit(t.text);return}case"text":case"tool_start":this.ensureReporter(n)?.onEvent(t);return}}ensureReporter(t){if(this.current!==null)return this.current.reporter;if(this.stopping)return null;let n=this.deps.projectKey;if(n===null||this.blocked.has(t.objectId))return null;let r=this.cooldownUntil.get(t.objectId);if(r!==void 0&&this.clock.now()<r)return null;let o=U_({projectKey:n,sessionId:this.deps.sessionId(),objectId:t.objectId,summary:this.title,finalResponse:"with_text"},this.deps.transport,this.reporterClock()),i=t.key??t.objectId;this.current={objectId:t.objectId,name:i,reporter:o},o.begin(),this.model!==null&&o.setModel(this.model);for(let a of this.links)o.addLink(a);return this.log(`[maind-mcp-bridge] activity: reporting this session to ${ca(t)}.`),o}reporterClock(){return{now:s(()=>this.clock.now(),"now"),every:s((t,n)=>(this.flushers.add(n),{clear:s(()=>void this.flushers.delete(n),"clear")}),"every"),delay:s(t=>this.clock.delay(t),"delay"),deadline:s((t,n)=>this.clock.deadline(t,n),"deadline")}}checkStopped(){let t=this.current;if(t===null)return;let n=t.reporter.record().stoppedBy;n!==null&&(BX.has(n)?(this.blocked.add(t.objectId),this.log(`[maind-mcp-bridge] activity: reporting to ${t.name} stopped (${n}) \u2014 not retried in this session.`)):(this.cooldownUntil.set(t.objectId,this.clock.now()+HX),this.log(`[maind-mcp-bridge] activity: reporting to ${t.name} stopped (${n}) \u2014 retried in 5 minutes.`)),this.retire())}retire(){let t=this.current;if(this.current=null,this.links=[],t===null)return;let n=t.reporter.close({endState:"complete"}).catch(()=>{});this.closing.add(n),n.finally(()=>this.closing.delete(n))}safeTarget(){try{return this.deps.target()}catch{return{objectId:null,reason:"not_announced",bound:0}}}ownError(t){if(!this.loggedOwnError){this.loggedOwnError=!0;try{this.log(`[maind-mcp-bridge] activity: reporting failed (advisory, the session is unaffected): ${t instanceof Error?t.message:String(t)}`)}catch{}}}};oo();He();var GX=1e4,lr=s((e,t)=>({ok:!1,error:e,retryAfterSeconds:null,transient:t}),"answer");function WX(e){switch(e.kind){case"no_session":return lr("no_session",!0);case"transport_error":return lr(e.timedOut?"timeout":"unreachable",!0);case"http_error":return e.status===401?lr("auth_rejected",!1):e.status>=400&&e.status<500&&e.status!==408&&e.status!==429?lr(`http_${e.status}`,!1):lr("unreachable",!0);case"rpc_error":{let t=qo(`MCP error ${e.code}: ${e.message}`);return lr(t?.kind??"tool_error",!1)}case"result":{if(e.isError){let n=qo(e.text);if(n!==null)return lr(n.kind,!1)}let t=null;try{t=JSON.parse(e.text)}catch{t=null}return K_(t)}}}s(WX,"activityAnswerFromOutcome");function ZO(e){return G_(async t=>{try{return WX(await e(B_,t,{timeoutMs:GX}))}catch{return lr("unreachable",!0)}})}s(ZO,"bridgeActivityTransport");var H9=1;function U9(e){return E_.includes(e)}s(U9,"isHookSubcommand");var B9=6e4;async function K9(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==Y()&&Kr(e),e;let t=Y();if(t!==null)return t;let n=await Qo(G);return n===null&&(Gr("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.
1216
- `),process.exit(1)),Gr("paired",null,{version:G}),n.apiKey}s(K9,"ensureApiKey");async function G9(e){let t=await Qo(G);return t===null&&(Gr("auth_failed",`${e}; re-authorization did not complete`,{version:G}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1217
- `),process.exit(1)),Gr("paired",null,{version:G}),t.apiKey}s(G9,"reauth");async function W9(){let e=T_(process.argv.slice(2)),t=$O(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1218
- `),process.exit(2)),e==="install"){let E=process.argv.indexOf("install"),R=process.argv.slice(E+1),V=await pO(R);process.exit(V)}if(e==="refresh-rules"){let{runRefreshRules:E}=await Promise.resolve().then(()=>(Sd(),y_));process.exit(await E(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:E}=await Promise.resolve().then(()=>(vy(),FR));process.exit(await E(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:E}=await Promise.resolve().then(()=>(s_(),i_));process.exit(await E())}if(e==="session-end-run"){let{runSessionEndWorker:E}=await Promise.resolve().then(()=>(o_(),wN));process.exit(await E())}if(e==="on-hook"){let{hooksFromArgv:E,runHooks:R}=await Promise.resolve().then(()=>(yt(),MN)),V=process.argv.slice(process.argv.indexOf("on-hook")+1);process.exit(await R(E(V),V))}if(e==="on-session-briefing"){let{runOnSessionBriefing:E}=await Promise.resolve().then(()=>(Iy(),Ry));process.exit(await E())}if(e==="on-session-reminder"){let{runOnSessionReminder:E}=await Promise.resolve().then(()=>(lg(),cg));process.exit(await E())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:E}=await Promise.resolve().then(()=>(aD(),sD));process.exit(await E())}if(e==="guard"){let E=process.argv.indexOf("guard"),{runGuard:R}=await Promise.resolve().then(()=>(yD(),gD));process.exit(await R(process.argv.slice(E+1)))}if(e==="guard-inject"){let{runGuardInject:E}=await Promise.resolve().then(()=>(po(),g0));process.exit(await E())}if(e==="guard-gate"){let{runGuardGate:E}=await Promise.resolve().then(()=>(ED(),SD));process.exit(await E())}if(e==="guard-stop"){let{runGuardStop:E}=await Promise.resolve().then(()=>(CD(),AD));process.exit(await E())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:E}=await Promise.resolve().then(()=>(Hd(),kD));process.exit(await E())}if(e==="guard-capture"){let{runGuardCapture:E}=await Promise.resolve().then(()=>(OD(),ND));process.exit(await E())}if(e==="guard-consult"){let{runGuardConsult:E}=await Promise.resolve().then(()=>(Wd(),Gd));process.exit(await E())}if(e==="guard-prompt-mark"){let{runGuardPromptMark:E}=await Promise.resolve().then(()=>(Wd(),Gd));process.exit(await E())}if(e==="guard-skip-note"){let{runGuardSkipNote:E}=await Promise.resolve().then(()=>(Wd(),Gd));process.exit(await E())}if(e==="gateway"){let E=process.argv.indexOf("gateway"),{runGateway:R}=await Promise.resolve().then(()=>(DP(),OP));process.exit(await R(process.argv.slice(E+1)))}if(e==="activity"){let{runActivity:E}=await Promise.resolve().then(()=>($P(),MP));process.exit(await E(process.argv.slice(process.argv.indexOf("activity")+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:E}=await Promise.resolve().then(()=>(ub(),lb));process.exit(await E())}if(e==="guard-cross-check"){let{runGuardCrossCheck:E}=await Promise.resolve().then(()=>(ub(),lb));process.exit(await E())}if(e==="on-index-refresh"){let{runOnIndexRefresh:E}=await Promise.resolve().then(()=>(_d(),yd));process.exit(await E())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:E}=await Promise.resolve().then(()=>(_d(),yd));process.exit(await E())}if(e==="on-doc-duty"){let{runDocDutyReminder:E}=await Promise.resolve().then(()=>(YP(),JP));process.exit(await E())}if(e==="on-prompt-context"){let{runOnPromptContext:E}=await Promise.resolve().then(()=>(Na(),Ia));process.exit(await E())}if(e==="on-read-context"){let{runOnReadContext:E}=await Promise.resolve().then(()=>(Na(),Ia));process.exit(await E())}if(e!==void 0&&U9(e)){let E=await Promise.resolve().then(()=>(en(),Pi)),R={"on-session-start":E.runOnSessionStart,"on-tool-use":E.runOnToolUse,"on-file-write":E.runOnFileWrite,"on-file-edit":E.runOnFileEdit,"on-repo-health":E.runOnRepoHealth,"on-write-health":E.runOnWriteHealth,"sync-config":E.runSyncConfig,flush:E.runFlush,status:E.runHookStatus}[e];process.exit(await R())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(G+`
1219
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(V9(),process.exit(0)),process.argv.includes("--reauth")&&(Is(),await Qo(G,process.stdout)===null&&process.exit(1),Gr("paired",null,{version:G}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1220
- `),process.exit(0));let n=me(),r=await K9(),o=te(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Td:null,c=null,l=new Map,u=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Rd(void 0,a,void 0,{callCloudTool:s((E,R,V)=>c===null?Promise.resolve({kind:"no_session"}):c.callCloudTool(E,R,V),"callCloudTool"),projectKey:o,engineFor:s(E=>{let R=l.get(E);return R===void 0&&(R=sR(E),l.set(E,R)),R},"engineFor"),projectKeyFor:Je}),d=`bridge-${F9()}`,p=s(async()=>{if(!a)return;let E=a.takePending();E.tokens<=0||await OO({apiKey:r,deviceId:n,sessionId:d,tokensSaved:E.tokens,bridgeVersion:G})},"flushSavings"),f=a?setInterval(()=>{p()},B9):null;f?.unref();let m=new du({projectKey:o}),g=new Nd({resolvePath:s(()=>S_(m.sideChannel()),"resolvePath"),fallbackModel:s(()=>m.sideChannel()?.model??null,"fallbackModel")}),y=new Xc,_=null,b=s(()=>(_===null&&(_=o!==null?DO(At(),o):[]),_),"nestedRepos"),w=s(E=>b().find(R=>R.projectKey===E)?.dir??null,"nestedDirOf"),v=new Id({agentCwd:s(()=>m.sideChannel()?.cwd??null,"agentCwd")}),S=null,x=new pd({projectKey:o,identity:m,sessionMeta:s(()=>g.read(),"sessionMeta"),postToolCall:s((E,R)=>c===null?Promise.reject(new Error("presence: no active forwarder")):c.postPresenceToolCall(E,R),"postToolCall"),deriveWorkingPaths:s(()=>MO(),"deriveWorkingPaths"),snapshot:o!==null?q9(AC({projectKey:o}),y,w):void 0,nestedProjectKeys:s(()=>b().map(E=>E.projectKey),"nestedProjectKeys"),workRepo:s(()=>v.current(),"workRepo"),onAnnounced:s(()=>S?.refresh(),"onAnnounced")});S=new Ld({enabled:Od().enabled&&x.isEnabled,projectKey:o,sessionId:s(()=>x.sessionId,"sessionId"),transcriptPath:s(()=>S_(m.sideChannel()),"transcriptPath"),target:s(()=>_i({branchObjectId:x.branchObjectId(),boundObjects:x.boundObjects()}),"target"),transport:ZO((E,R,V)=>c===null?Promise.resolve({kind:"no_session"}):c.callCloudTool(E,R,V))});let T=x.isEnabled?setInterval(()=>{x.pollActivity()},GI):null;if(T?.unref(),x.isEnabled){let E=s(R=>{(S?.shutdown()??Promise.resolve()).then(()=>x.end()).finally(()=>process.exit(R))},"endAndExit");process.on("SIGTERM",()=>E(143)),process.on("SIGINT",()=>E(130))}let I=!1,j=s(E=>{if(I)return;I=!0;let R=s(()=>c?.listClientRoots()??Promise.resolve(null),"listRoots");setTimeout(()=>{Promise.resolve().then(()=>(kd(),sO)).then(({refreshAgentsMdForSession:le})=>le(E,{apiKey:r,projectKey:o,listRoots:R})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(Sd(),y_))).then(({refreshRulesForSession:le})=>le(E,{apiKey:s(()=>r,"apiKey"),listRoots:R})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),C=0,M=Wm();try{for(;;){let E=c?.carryOver()??null,R=new sl({apiKey:r,deviceId:n,bridgeVersion:G,projectKey:o,localRouter:u,presence:x,onConnectionOutcome:s((V,le)=>Gr(V,le,{version:G}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:V})=>j(V),"onSessionReady"),assignedInbox:y,carry:E});c=R;try{await R.run(M);return}catch(V){if(V instanceof Rs&&C<H9){C+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${V.message}; re-authorizing\u2026
1221
- `),r=await G9(V.reason);continue}throw V}}}finally{f&&clearInterval(f),T&&clearInterval(T),await S?.shutdown(),await x.end(),await p()}}s(W9,"main");function V9(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, hooks, user-level rule files; --team: AGENTS.md + .mcp.json)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge doctor # offline self-diagnosis with fix commands (--json)"," npx -y @maind-dev/mcp-bridge doctor --remove-phantoms [--yes]"," # list (then remove) maind entries of clients that are not installed"," npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks [--yes]"," # list (then remove) the maind blocks earlier installs wrote into this repository"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-mcp [--yes]"," # with the Claude Code plugin maind: list (then remove) the second maind server in ~/.claude.json"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-hooks [--yes]"," # with the Claude Code plugin maind: list (then remove) the bridge's own hooks in settings.json"," npx -y @maind-dev/mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]"," # refresh the user-level rule files with the conventions of <dir>'s repository"," npx -y @maind-dev/mcp-bridge activity [on|off|status]"," # Claude Code sessions report their agent activity to the one work object"," # they are bound to (opt-in, MAIND-673); status names the target per session"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-reminder add ~/.claude/maind-session-start-reminder.md at session start (replaces `cat`; MAIND-630)"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-session-briefing add the session briefing + project conventions at session start (MAIND-620, never blocks)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end close the tracked session, queue analytics + cost upload for a detached run (MAIND-633)"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>"," guard difficulty <on|off> | guard capture <on|off> in-loop triggers (ADR-360)"," guard consult <on|off> consultation triggers: plan mode, agent docs, risky paths (ADR-375)",' guard skip --session <id> --reason "\u2026" [--kind consult|difficulty|capture|plan|agent_doc|risk] 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,"," guard-consult, guard-prompt-mark, guard-skip-note)","","Cursor hook subcommand (wired by `install` into ~/.cursor/hooks.json where Cursor is installed):"," on-cursor-session-start return the session briefing + project conventions as additional_context (MAIND-620)","Codex and Copilot: `install` wires one entry per event into Codex's config.toml and ~/.copilot/hooks/maind.json"," where they are installed (MAIND-725):"," on-hook --host=<codex|copilot> <hook> \u2026 run the named core hooks above in one process, answer in the host's JSON","","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_AGENT_ACTIVITY 'on'/'off' overrides the agent activity switch of `activity on|off` for one session"," MAIND_NO_AGENTS_MD_REFRESH Set to 1 to stop refreshing the team conventions block in AGENTS.md (install --team; ADR-364 E4)"," MAIND_NO_RULES_REFRESH Set to 1 to stop refreshing the user-level rule files (Copilot, Cline, Continue; ADR-364 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," MAIND_DEVIN_HOOK_OUTPUT 'off' keeps every hook silent when Devin Local runs it (default on; or",' "devin_hook_output": false in config.json \u2014 MAIND-630, unmeasured there)'," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
1222
- `))}s(V9,"printHelp");W9().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1223
- `),process.exit(1)});function q9(e,t,n){return{...e,write(r,o){let i=r;try{i=tE(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(q9,"withAssignedCapture");
1215
+ `))}static{s(this,"ActivityProducer")}clock;tail;log;mapper=new Ba;ticker=null;busy=!1;stopping=!1;path=null;current=null;closing=new Set;flushers=new Set;model=null;title=null;links=[];cooldownUntil=new Map;blocked=new Set;loggedOwnError=!1;get isEnabled(){return this.deps.enabled&&this.deps.projectKey!==null}state(){return{ticking:this.ticker!==null,objectId:this.current?.objectId??null,agentSessionId:this.current?.reporter.record().agentSessionId??null}}refresh(){try{if(!this.isEnabled||this.stopping||this.ticker!==null||this.safeTarget().objectId===null)return;this.tail.reset(),this.path=null,this.ticker=this.clock.every(jX,()=>void this.tick())}catch(t){this.ownError(t)}}async tick(){if(!(!this.isEnabled||this.stopping||this.busy)){this.busy=!0;try{await this.step()}catch(t){this.ownError(t)}finally{this.busy=!1}}}async shutdown(t=FX){if(!this.stopping){this.stopping=!0;try{this.ticker?.clear(),this.ticker=null;let n=(async()=>{if(this.isEnabled&&!this.busy&&this.current!==null)try{await this.step()}catch{}this.retire(),await Promise.all([...this.closing])})();await this.clock.deadline(n,t)}catch{}}}async step(){let t=this.safeTarget(),n=null;try{n=this.deps.transcriptPath()}catch{n=null}if(n===null&&(n=this.path),n!==this.path&&(this.path!==null&&n!==null&&XO(this.path)===XO(n)||(this.retire(),this.mapper=new Ba,this.model=null,this.title=null),this.path=n),t.objectId===null){this.retire(),this.ticker?.clear(),this.ticker=null,this.tail.reset(),this.path=null;return}this.current!==null&&this.current.objectId!==t.objectId&&this.retire(),this.current!==null&&this.checkStopped();let r=await this.tail.poll(n),o=[];for(let i of r)o.push(...this.mapper.map(i));r.length===0&&o.push(...this.mapper.idle());for(let i of o)this.dispatch(i,t);for(let i of[...this.flushers])i()}dispatch(t,n){switch(t.kind){case"model":this.model=t.model,this.current?.reporter.setModel(t.model);return;case"title":this.title=t.title,this.current?.reporter.setSummary(t.title);return;case"link":this.links.length<UX&&!this.links.some(r=>r.url===t.url)&&this.links.push({url:t.url,label:t.label}),this.current?.reporter.addLink({url:t.url,label:t.label});return;case"turn_end":this.current?.reporter.endTurn();return;case"tool_end":this.current?.reporter.onEvent(t);return;case"question":{this.ensureReporter(n)?.elicit(t.text);return}case"text":case"tool_start":this.ensureReporter(n)?.onEvent(t);return}}ensureReporter(t){if(this.current!==null)return this.current.reporter;if(this.stopping)return null;let n=this.deps.projectKey;if(n===null||this.blocked.has(t.objectId))return null;let r=this.cooldownUntil.get(t.objectId);if(r!==void 0&&this.clock.now()<r)return null;let o=U_({projectKey:n,sessionId:this.deps.sessionId(),objectId:t.objectId,summary:this.title,finalResponse:"with_text"},this.deps.transport,this.reporterClock()),i=t.key??t.objectId;this.current={objectId:t.objectId,name:i,reporter:o},o.begin(),this.model!==null&&o.setModel(this.model);for(let a of this.links)o.addLink(a);return this.log(`[maind-mcp-bridge] activity: reporting this session to ${ca(t)}.`),o}reporterClock(){return{now:s(()=>this.clock.now(),"now"),every:s((t,n)=>(this.flushers.add(n),{clear:s(()=>void this.flushers.delete(n),"clear")}),"every"),delay:s(t=>this.clock.delay(t),"delay"),deadline:s((t,n)=>this.clock.deadline(t,n),"deadline")}}checkStopped(){let t=this.current;if(t===null)return;let n=t.reporter.record().stoppedBy;n!==null&&(BX.has(n)?(this.blocked.add(t.objectId),this.log(`[maind-mcp-bridge] activity: reporting to ${t.name} stopped (${n}) \u2014 not retried in this session.`)):(this.cooldownUntil.set(t.objectId,this.clock.now()+HX),this.log(`[maind-mcp-bridge] activity: reporting to ${t.name} stopped (${n}) \u2014 retried in 5 minutes.`)),this.retire())}retire(){let t=this.current;if(this.current=null,this.links=[],t===null)return;let n=t.reporter.close({endState:"complete"}).catch(()=>{});this.closing.add(n),n.finally(()=>this.closing.delete(n))}safeTarget(){try{return this.deps.target()}catch{return{objectId:null,reason:"not_announced",bound:0}}}ownError(t){if(!this.loggedOwnError){this.loggedOwnError=!0;try{this.log(`[maind-mcp-bridge] activity: reporting failed (advisory, the session is unaffected): ${t instanceof Error?t.message:String(t)}`)}catch{}}}};oo();He();var GX=1e4,lr=s((e,t)=>({ok:!1,error:e,retryAfterSeconds:null,transient:t}),"answer");function WX(e){switch(e.kind){case"no_session":return lr("no_session",!0);case"transport_error":return lr(e.timedOut?"timeout":"unreachable",!0);case"http_error":return e.status===401?lr("auth_rejected",!1):e.status>=400&&e.status<500&&e.status!==408&&e.status!==429?lr(`http_${e.status}`,!1):lr("unreachable",!0);case"rpc_error":{let t=qo(`MCP error ${e.code}: ${e.message}`);return lr(t?.kind??"tool_error",!1)}case"result":{if(e.isError){let n=qo(e.text);if(n!==null)return lr(n.kind,!1)}let t=null;try{t=JSON.parse(e.text)}catch{t=null}return K_(t)}}}s(WX,"activityAnswerFromOutcome");function ZO(e){return G_(async t=>{try{return WX(await e(B_,t,{timeoutMs:GX}))}catch{return lr("unreachable",!0)}})}s(ZO,"bridgeActivityTransport");var H3=1;function U3(e){return E_.includes(e)}s(U3,"isHookSubcommand");var B3=6e4;async function K3(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==Y()&&Kr(e),e;let t=Y();if(t!==null)return t;let n=await Qo(G);return n===null&&(Gr("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.
1216
+ `),process.exit(1)),Gr("paired",null,{version:G}),n.apiKey}s(K3,"ensureApiKey");async function G3(e){let t=await Qo(G);return t===null&&(Gr("auth_failed",`${e}; re-authorization did not complete`,{version:G}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1217
+ `),process.exit(1)),Gr("paired",null,{version:G}),t.apiKey}s(G3,"reauth");async function W3(){let e=T_(process.argv.slice(2)),t=$O(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1218
+ `),process.exit(2)),e==="install"){let E=process.argv.indexOf("install"),R=process.argv.slice(E+1),V=await pO(R);process.exit(V)}if(e==="refresh-rules"){let{runRefreshRules:E}=await Promise.resolve().then(()=>(Sd(),y_));process.exit(await E(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:E}=await Promise.resolve().then(()=>(vy(),FR));process.exit(await E(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:E}=await Promise.resolve().then(()=>(s_(),i_));process.exit(await E())}if(e==="session-end-run"){let{runSessionEndWorker:E}=await Promise.resolve().then(()=>(o_(),wN));process.exit(await E())}if(e==="on-hook"){let{hooksFromArgv:E,runHooks:R}=await Promise.resolve().then(()=>(yt(),MN)),V=process.argv.slice(process.argv.indexOf("on-hook")+1);process.exit(await R(E(V),V))}if(e==="on-session-briefing"){let{runOnSessionBriefing:E}=await Promise.resolve().then(()=>(Iy(),Ry));process.exit(await E())}if(e==="on-session-reminder"){let{runOnSessionReminder:E}=await Promise.resolve().then(()=>(lg(),cg));process.exit(await E())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:E}=await Promise.resolve().then(()=>(aD(),sD));process.exit(await E())}if(e==="guard"){let E=process.argv.indexOf("guard"),{runGuard:R}=await Promise.resolve().then(()=>(yD(),gD));process.exit(await R(process.argv.slice(E+1)))}if(e==="guard-inject"){let{runGuardInject:E}=await Promise.resolve().then(()=>(po(),g0));process.exit(await E())}if(e==="guard-gate"){let{runGuardGate:E}=await Promise.resolve().then(()=>(ED(),SD));process.exit(await E())}if(e==="guard-stop"){let{runGuardStop:E}=await Promise.resolve().then(()=>(CD(),AD));process.exit(await E())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:E}=await Promise.resolve().then(()=>(Hd(),kD));process.exit(await E())}if(e==="guard-capture"){let{runGuardCapture:E}=await Promise.resolve().then(()=>(OD(),ND));process.exit(await E())}if(e==="guard-consult"){let{runGuardConsult:E}=await Promise.resolve().then(()=>(Wd(),Gd));process.exit(await E())}if(e==="guard-prompt-mark"){let{runGuardPromptMark:E}=await Promise.resolve().then(()=>(Wd(),Gd));process.exit(await E())}if(e==="guard-skip-note"){let{runGuardSkipNote:E}=await Promise.resolve().then(()=>(Wd(),Gd));process.exit(await E())}if(e==="gateway"){let E=process.argv.indexOf("gateway"),{runGateway:R}=await Promise.resolve().then(()=>(DP(),OP));process.exit(await R(process.argv.slice(E+1)))}if(e==="activity"){let{runActivity:E}=await Promise.resolve().then(()=>($P(),MP));process.exit(await E(process.argv.slice(process.argv.indexOf("activity")+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:E}=await Promise.resolve().then(()=>(ub(),lb));process.exit(await E())}if(e==="guard-cross-check"){let{runGuardCrossCheck:E}=await Promise.resolve().then(()=>(ub(),lb));process.exit(await E())}if(e==="on-index-refresh"){let{runOnIndexRefresh:E}=await Promise.resolve().then(()=>(_d(),yd));process.exit(await E())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:E}=await Promise.resolve().then(()=>(_d(),yd));process.exit(await E())}if(e==="on-doc-duty"){let{runDocDutyReminder:E}=await Promise.resolve().then(()=>(YP(),JP));process.exit(await E())}if(e==="on-prompt-context"){let{runOnPromptContext:E}=await Promise.resolve().then(()=>(Na(),Ia));process.exit(await E())}if(e==="on-read-context"){let{runOnReadContext:E}=await Promise.resolve().then(()=>(Na(),Ia));process.exit(await E())}if(e!==void 0&&U3(e)){let E=await Promise.resolve().then(()=>(en(),Pi)),R={"on-session-start":E.runOnSessionStart,"on-tool-use":E.runOnToolUse,"on-file-write":E.runOnFileWrite,"on-file-edit":E.runOnFileEdit,"on-repo-health":E.runOnRepoHealth,"on-write-health":E.runOnWriteHealth,"sync-config":E.runSyncConfig,flush:E.runFlush,status:E.runHookStatus}[e];process.exit(await R())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(G+`
1219
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(V3(),process.exit(0)),process.argv.includes("--reauth")&&(Is(),await Qo(G,process.stdout)===null&&process.exit(1),Gr("paired",null,{version:G}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1220
+ `),process.exit(0));let n=me(),r=await K3(),o=te(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Td:null,c=null,l=new Map,u=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Rd(void 0,a,void 0,{callCloudTool:s((E,R,V)=>c===null?Promise.resolve({kind:"no_session"}):c.callCloudTool(E,R,V),"callCloudTool"),projectKey:o,engineFor:s(E=>{let R=l.get(E);return R===void 0&&(R=sR(E),l.set(E,R)),R},"engineFor"),projectKeyFor:Je}),d=`bridge-${F3()}`,p=s(async()=>{if(!a)return;let E=a.takePending();E.tokens<=0||await OO({apiKey:r,deviceId:n,sessionId:d,tokensSaved:E.tokens,bridgeVersion:G})},"flushSavings"),f=a?setInterval(()=>{p()},B3):null;f?.unref();let m=new du({projectKey:o}),g=new Nd({resolvePath:s(()=>S_(m.sideChannel()),"resolvePath"),fallbackModel:s(()=>m.sideChannel()?.model??null,"fallbackModel")}),y=new Xc,_=null,b=s(()=>(_===null&&(_=o!==null?DO(At(),o):[]),_),"nestedRepos"),w=s(E=>b().find(R=>R.projectKey===E)?.dir??null,"nestedDirOf"),v=new Id({agentCwd:s(()=>m.sideChannel()?.cwd??null,"agentCwd")}),S=null,x=new pd({projectKey:o,identity:m,sessionMeta:s(()=>g.read(),"sessionMeta"),postToolCall:s((E,R)=>c===null?Promise.reject(new Error("presence: no active forwarder")):c.postPresenceToolCall(E,R),"postToolCall"),deriveWorkingPaths:s(()=>MO(),"deriveWorkingPaths"),snapshot:o!==null?q3(AC({projectKey:o}),y,w):void 0,nestedProjectKeys:s(()=>b().map(E=>E.projectKey),"nestedProjectKeys"),workRepo:s(()=>v.current(),"workRepo"),onAnnounced:s(()=>S?.refresh(),"onAnnounced")});S=new Ld({enabled:Od().enabled&&x.isEnabled,projectKey:o,sessionId:s(()=>x.sessionId,"sessionId"),transcriptPath:s(()=>S_(m.sideChannel()),"transcriptPath"),target:s(()=>_i({branchObjectId:x.branchObjectId(),boundObjects:x.boundObjects()}),"target"),transport:ZO((E,R,V)=>c===null?Promise.resolve({kind:"no_session"}):c.callCloudTool(E,R,V))});let T=x.isEnabled?setInterval(()=>{x.pollActivity()},GI):null;if(T?.unref(),x.isEnabled){let E=s(R=>{(S?.shutdown()??Promise.resolve()).then(()=>x.end()).finally(()=>process.exit(R))},"endAndExit");process.on("SIGTERM",()=>E(143)),process.on("SIGINT",()=>E(130))}let I=!1,j=s(E=>{if(I)return;I=!0;let R=s(()=>c?.listClientRoots()??Promise.resolve(null),"listRoots");setTimeout(()=>{Promise.resolve().then(()=>(kd(),sO)).then(({refreshAgentsMdForSession:le})=>le(E,{apiKey:r,projectKey:o,listRoots:R})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(Sd(),y_))).then(({refreshRulesForSession:le})=>le(E,{apiKey:s(()=>r,"apiKey"),listRoots:R})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),C=0,M=Wm();try{for(;;){let E=c?.carryOver()??null,R=new sl({apiKey:r,deviceId:n,bridgeVersion:G,projectKey:o,localRouter:u,presence:x,onConnectionOutcome:s((V,le)=>Gr(V,le,{version:G}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:V})=>j(V),"onSessionReady"),assignedInbox:y,carry:E});c=R;try{await R.run(M);return}catch(V){if(V instanceof Rs&&C<H3){C+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${V.message}; re-authorizing\u2026
1221
+ `),r=await G3(V.reason);continue}throw V}}}finally{f&&clearInterval(f),T&&clearInterval(T),await S?.shutdown(),await x.end(),await p()}}s(W3,"main");function V3(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, hooks, user-level rule files; --team: AGENTS.md + .mcp.json)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge doctor # offline self-diagnosis with fix commands (--json)"," npx -y @maind-dev/mcp-bridge doctor --remove-phantoms [--yes]"," # list (then remove) maind entries of clients that are not installed"," npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks [--yes]"," # list (then remove) the maind blocks earlier installs wrote into this repository"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-mcp [--yes]"," # with the Claude Code plugin maind: list (then remove) the second maind server in ~/.claude.json"," npx -y @maind-dev/mcp-bridge doctor --remove-duplicate-hooks [--yes]"," # with the Claude Code plugin maind: list (then remove) the bridge's own hooks in settings.json"," npx -y @maind-dev/mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]"," # refresh the user-level rule files with the conventions of <dir>'s repository"," npx -y @maind-dev/mcp-bridge activity [on|off|status]"," # Claude Code sessions report their agent activity to the one work object"," # they are bound to (opt-in, MAIND-673); status names the target per session"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-reminder add ~/.claude/maind-session-start-reminder.md at session start (replaces `cat`; MAIND-630)"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-session-briefing add the session briefing + project conventions at session start (MAIND-620, never blocks)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end close the tracked session, queue analytics + cost upload for a detached run (MAIND-633)"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>"," guard difficulty <on|off> | guard capture <on|off> in-loop triggers (ADR-360)"," guard consult <on|off> consultation triggers: plan mode, agent docs, risky paths (ADR-375)",' guard skip --session <id> --reason "\u2026" [--kind consult|difficulty|capture|plan|agent_doc|risk] 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,"," guard-consult, guard-prompt-mark, guard-skip-note)","","Cursor hook subcommand (wired by `install` into ~/.cursor/hooks.json where Cursor is installed):"," on-cursor-session-start return the session briefing + project conventions as additional_context (MAIND-620)","Codex and Copilot: `install` wires one entry per event into Codex's config.toml and ~/.copilot/hooks/maind.json"," where they are installed (MAIND-725):"," on-hook --host=<codex|copilot> <hook> \u2026 run the named core hooks above in one process, answer in the host's JSON","","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_AGENT_ACTIVITY 'on'/'off' overrides the agent activity switch of `activity on|off` for one session"," MAIND_NO_AGENTS_MD_REFRESH Set to 1 to stop refreshing the team conventions block in AGENTS.md (install --team; ADR-364 E4)"," MAIND_NO_RULES_REFRESH Set to 1 to stop refreshing the user-level rule files (Copilot, Cline, Continue; ADR-364 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," MAIND_DEVIN_HOOK_OUTPUT 'off' keeps every hook silent when Devin Local runs it (default on; or",' "devin_hook_output": false in config.json \u2014 MAIND-630, unmeasured there)'," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
1222
+ `))}s(V3,"printHelp");W3().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1223
+ `),process.exit(1)});function q3(e,t,n){return{...e,write(r,o){let i=r;try{i=tE(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(q3,"withAssignedCapture");