@maind-dev/mcp-bridge 0.129.0 → 0.129.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
@@ -7,7 +7,7 @@ ${cc(e.body)}`:[...e.verbs,e.solvedBy??""].join(`
7
7
  `)&&!e.startsWith(`---\r
8
8
  `))return{meta:"",body:e};let t=e.indexOf(`
9
9
  ---`,3);if(t===-1)return{meta:"",body:e};let n=e.indexOf(`
10
- `,t+4);return{meta:e.slice(4,t),body:n===-1?"":e.slice(n+1)}}function hc(e){return e.replace(/\s+/g," ").trim()}function sm(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${r>t*.6?n.slice(0,r):n}\u2026`}function vx(e,t){let{meta:n,body:r}=im(e),i=/^#\s+(.+)$/m.exec(r)??/^#{2,6}\s+(.+)$/m.exec(r),a=/^title:\s*["']?(.+?)["']?\s*$/m.exec(n),l=i?.[1]??a?.[1]??bx(t);return sm(hc(l),zH)}function Sx(e){let{body:t}=im(e),n=t.split(/\r?\n/),r=[],o=!1;for(let i of n){let a=i.trim();if(o){a.includes("-->")&&(o=!1);continue}if(a.startsWith("<!--")){a.includes("-->")||(o=!0);continue}if(a===""){if(r.length>0)break;continue}r.length===0&&(a.startsWith("#")||YH.test(a)||/^[-*_]{3,}$/.test(a))||r.push(a)}if(r.length!==0)return sm(hc(r.join(" ")),JH)}function xx(e){return(/\*\*(?:Datum|Date):\*\*\s*(\d{4}-\d{2}-\d{2})/.exec(e)??/^date:\s*["']?(\d{4}-\d{2}-\d{2})/m.exec(im(e).meta))?.[1]}function Bs(e,t,n,r){let o=kx(n);if(!o)return[];let i=[];for(let a of e){let l=a.trim();if(l===""||!li(l)||i.some(m=>m.path===l))continue;let c=t(l);if(c===null||!o.test(c))continue;let u={path:l,title:vx(c,l),kind:wx(l)},d=Sx(c);d&&(u.excerpt=d);let p=xx(c);p&&(u.doc_date=p);let f=r?.(l);if(f&&(u.url=f),i.push(u),i.length>=Ff)break}return i}function yc(e){let t=e.trim();return t.length<4?!1:!["1","true","false","yes","no","on","skip","none","n/a","na","ok"].includes(t.toLowerCase())}function Gs(e){let t={kind:"none"};for(let n of e)for(let r of n.matchAll(XH)){let o=hc(r[2]??"");t=yc(o)?{kind:"ok",decision:{decision:r[1].toLowerCase(),reason:sm(o,ac)}}:{kind:"invalid",line:hc(r[0])}}return t}function _x(e){let t=e.split(/\s*[,/]\s*/).map(r=>r.trim()),n=[];for(let r of t){let o=QH.exec(r);if(!o)return null;n.push(`${o[1]}-${Number.parseInt(o[2],10)}`)}return n.length>0?n:null}function _c(e){let t=[],n=s(r=>{for(let o of r??[])!t.includes(o)&&t.length<rU&&t.push(o)},"add");for(let r of e){let o=r.split(/\r?\n/),i=o[0]??"";for(let a of i.matchAll(eU))n(_x(a[1].trim()));for(let a of o.slice(1)){let l=nU.exec(a);l&&n(_x(l[1].trim()))}}return t}function lm(e,t){return`[maind] Documentation duty for ${e} is still open: this work has no document that names ${e} and no recorded exception. In THIS branch, before the merge approval, either add or update a Markdown document (ADR, note, session note) that names ${e}, or \u2014 if none is needed \u2014 put a trailer in a commit: "Doc-Decision: none - <reason>" (or "Doc-Decision: elsewhere - <owner/repo#pr>"). The approval binds the head, and a document written after the merge needs a pull request of its own.`+(t?" This organization requires it: `maind feature promote` refuses to merge without it.":"")}function um(e){return`${e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}.json`}function dm(e,t){if(e===null)return!1;try{let n=Date.parse(String(JSON.parse(e).said_at));return!Number.isNaN(n)&&n<=t&&t-n<Ex}catch{return!1}}var zH,JH,gc,YH,XH,ZH,QH,eU,am,tU,nU,bre,rU,cm,Ex,Tx=w(()=>{"use strict";lc();zH=ic,JH=sc,gc=["CLAUDE.md","AGENTS.md","GEMINI.md",".cursorrules",".windsurfrules",".github/copilot-instructions.md"];s(bx,"basename");s(li,"isDocumentCandidate");s(kx,"keyPattern");s(wx,"documentKind");s(im,"splitFrontMatter");YH=/^\s*\*\*[^*]{1,40}:\*\*/;s(hc,"clean");s(sm,"cap");s(vx,"documentTitle");s(Sx,"documentExcerpt");s(xx,"documentDate");s(Bs,"collectDocuments");s(yc,"isDocDecisionReason");XH=/^Doc-Decision:[ \t]*(none|elsewhere)[ \t]*(?:[-–—:][ \t]*)?(.*)$/gim;s(Gs,"parseDocDecision");ZH="([A-Z][A-Z0-9]{0,5})-0*([0-9]{1,9})",QH=new RegExp(`^${ZH}$`),eU=/\(([^()]{1,200})\)/g,am=String.raw`close[sd]?|fix(?:e[sd])?|resolve[sd]?`,tU=String.raw`refs?|references|part\s+of|related\s+to|contributes\s+to|towards?`,nU=new RegExp(String.raw`^\s*(?:${am}|${tU}):?\s+(.+)$`,"i"),bre=new RegExp(String.raw`^\s*(?:${am}):?\s+(.+)$`,"i"),rU=20;s(_x,"keysOfList");s(_c,"objectKeysInCommits");s(lm,"docDutyReminderText");cm="said",Ex=12*60*60*1e3;s(um,"docDutySaidFile");s(dm,"docDutySaidRecently")});var Ax,oU,Rx=w(()=>{"use strict";De();Ax=y.object({version:y.literal(1).default(1),org_visibility:y.boolean().default(!1),session_span_visibility:y.boolean().default(!0)}),oU=Ax.parse({})});var Cx,Ix,iU,sU,Ox=w(()=>{"use strict";De();Cx=y.object({tools:y.array(y.string()).default([]),languages:y.array(y.string()).default([]),platforms:y.array(y.string()).default([]),tags:y.array(y.string()).default([])}),Ix=y.object({id:y.string().uuid(),user_id:y.string().uuid(),project:y.string().max(200).nullable().optional(),title:y.string().min(1).max(200),body:y.string().min(1).max(2e4),context:Cx.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:y.string(),updated_at:y.string(),last_recalled_at:y.string().nullable().optional(),recall_count:y.number().int().nonnegative().default(0),graduated_draft_id:y.string().uuid().nullable().optional(),deleted_at:y.string().nullable().optional()}),iU=Ix.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:y.number()}),sU=y.object({id:y.string().uuid(),title:y.string(),summary:y.string(),tags:y.array(y.string()).default([])})});var Nx=w(()=>{"use strict"});function bc(e){let t=[],n=null;return e.split(`
10
+ `,t+4);return{meta:e.slice(4,t),body:n===-1?"":e.slice(n+1)}}function hc(e){return e.replace(/\s+/g," ").trim()}function sm(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${r>t*.6?n.slice(0,r):n}\u2026`}function vx(e,t){let{meta:n,body:r}=im(e),i=/^#\s+(.+)$/m.exec(r)??/^#{2,6}\s+(.+)$/m.exec(r),a=/^title:\s*["']?(.+?)["']?\s*$/m.exec(n),l=i?.[1]??a?.[1]??bx(t);return sm(hc(l),zH)}function Sx(e){let{body:t}=im(e),n=t.split(/\r?\n/),r=[],o=!1;for(let i of n){let a=i.trim();if(o){a.includes("-->")&&(o=!1);continue}if(a.startsWith("<!--")){a.includes("-->")||(o=!0);continue}if(a===""){if(r.length>0)break;continue}r.length===0&&(a.startsWith("#")||YH.test(a)||/^[-*_]{3,}$/.test(a))||r.push(a)}if(r.length!==0)return sm(hc(r.join(" ")),JH)}function xx(e){return(/\*\*(?:Datum|Date):\*\*\s*(\d{4}-\d{2}-\d{2})/.exec(e)??/^date:\s*["']?(\d{4}-\d{2}-\d{2})/m.exec(im(e).meta))?.[1]}function Bs(e,t,n,r){let o=kx(n);if(!o)return[];let i=[];for(let a of e){let l=a.trim();if(l===""||!li(l)||i.some(m=>m.path===l))continue;let c=t(l);if(c===null||!o.test(c))continue;let u={path:l,title:vx(c,l),kind:wx(l)},d=Sx(c);d&&(u.excerpt=d);let p=xx(c);p&&(u.doc_date=p);let f=r?.(l);if(f&&(u.url=f),i.push(u),i.length>=Ff)break}return i}function yc(e){let t=e.trim();return t.length<4?!1:!["1","true","false","yes","no","on","skip","none","n/a","na","ok"].includes(t.toLowerCase())}function Gs(e){let t={kind:"none"};for(let n of e)for(let r of n.matchAll(XH)){let o=hc(r[2]??"");t=yc(o)?{kind:"ok",decision:{decision:r[1].toLowerCase(),reason:sm(o,ac)}}:{kind:"invalid",line:hc(r[0])}}return t}function _x(e){let t=e.split(/\s*[,/]\s*/).map(r=>r.trim()),n=[];for(let r of t){let o=QH.exec(r);if(!o)return null;n.push(`${o[1]}-${Number.parseInt(o[2],10)}`)}return n.length>0?n:null}function _c(e){let t=[],n=s(r=>{for(let o of r??[])!t.includes(o)&&t.length<rU&&t.push(o)},"add");for(let r of e){let o=r.split(/\r?\n/),i=o[0]??"";for(let a of i.matchAll(eU))n(_x(a[1].trim()));for(let a of o.slice(1)){let l=nU.exec(a);l&&n(_x(l[1].trim()))}}return t}function lm(e,t){return`[maind] Documentation duty for ${e} is still open: this work has no document that names ${e} and no recorded exception. In THIS branch, before the merge approval, either add or update a Markdown document (ADR, note, session note) that names ${e}, or \u2014 if none is needed \u2014 put a trailer in a commit: "Doc-Decision: none - <reason>" (or "Doc-Decision: elsewhere - <owner/repo#pr>"). The approval binds the head, and a document written after the merge needs a pull request of its own.`+(t?" This organization requires it: `maind feature promote` refuses to merge without it.":"")}function um(e){return`${e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}.json`}function dm(e,t){if(e===null)return!1;try{let n=Date.parse(String(JSON.parse(e).said_at));return!Number.isNaN(n)&&n<=t&&t-n<Ex}catch{return!1}}var zH,JH,gc,YH,XH,ZH,QH,eU,am,tU,nU,wre,rU,cm,Ex,Tx=w(()=>{"use strict";lc();zH=ic,JH=sc,gc=["CLAUDE.md","AGENTS.md","GEMINI.md",".cursorrules",".windsurfrules",".github/copilot-instructions.md"];s(bx,"basename");s(li,"isDocumentCandidate");s(kx,"keyPattern");s(wx,"documentKind");s(im,"splitFrontMatter");YH=/^\s*\*\*[^*]{1,40}:\*\*/;s(hc,"clean");s(sm,"cap");s(vx,"documentTitle");s(Sx,"documentExcerpt");s(xx,"documentDate");s(Bs,"collectDocuments");s(yc,"isDocDecisionReason");XH=/^Doc-Decision:[ \t]*(none|elsewhere)[ \t]*(?:[-–—:][ \t]*)?(.*)$/gim;s(Gs,"parseDocDecision");ZH="([A-Z][A-Z0-9]{0,5})-0*([0-9]{1,9})",QH=new RegExp(`^${ZH}$`),eU=/\(([^()]{1,200})\)/g,am=String.raw`close[sd]?|fix(?:e[sd])?|resolve[sd]?`,tU=String.raw`refs?|references|part\s+of|related\s+to|contributes\s+to|towards?`,nU=new RegExp(String.raw`^\s*(?:${am}|${tU}):?\s+(.+)$`,"i"),wre=new RegExp(String.raw`^\s*(?:${am}):?\s+(.+)$`,"i"),rU=20;s(_x,"keysOfList");s(_c,"objectKeysInCommits");s(lm,"docDutyReminderText");cm="said",Ex=12*60*60*1e3;s(um,"docDutySaidFile");s(dm,"docDutySaidRecently")});var Ax,oU,Rx=w(()=>{"use strict";De();Ax=y.object({version:y.literal(1).default(1),org_visibility:y.boolean().default(!1),session_span_visibility:y.boolean().default(!0)}),oU=Ax.parse({})});var Cx,Ix,iU,sU,Ox=w(()=>{"use strict";De();Cx=y.object({tools:y.array(y.string()).default([]),languages:y.array(y.string()).default([]),platforms:y.array(y.string()).default([]),tags:y.array(y.string()).default([])}),Ix=y.object({id:y.string().uuid(),user_id:y.string().uuid(),project:y.string().max(200).nullable().optional(),title:y.string().min(1).max(200),body:y.string().min(1).max(2e4),context:Cx.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:y.string(),updated_at:y.string(),last_recalled_at:y.string().nullable().optional(),recall_count:y.number().int().nonnegative().default(0),graduated_draft_id:y.string().uuid().nullable().optional(),deleted_at:y.string().nullable().optional()}),iU=Ix.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:y.number()}),sU=y.object({id:y.string().uuid(),title:y.string(),summary:y.string(),tags:y.array(y.string()).default([])})});var Nx=w(()=>{"use strict"});function bc(e){let t=[],n=null;return e.split(`
11
11
  `).forEach((r,o)=>{let i=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(i===""||a>n)return;n=null}if(i===""||i.startsWith("#"))return;let l=lU.exec(r);if(!l)return;let c=l[3]??"";if(aU.has(c.trim())){n=a;return}let u=c.split(/\s+#/)[0].trim();u===""||`'"[{&*`.includes(u[0])||u.includes(": ")&&t.push({line:o+1,value:u})}),t}var aU,lU,Dx=w(()=>{"use strict";aU=new Set(["|",">","|-",">-","|+",">+"]),lU=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;s(bc,"plainScalarViolations")});function Ks(e,t){let n=s(l=>{let[c,u=""]=l.split("-",2),d=c.split(".").map(p=>{let f=Number(p);return Number.isFinite(f)?f:0});for(;d.length<3;)d.push(0);return[d,u.length>0?u.split("."):[]]},"split"),[r,o]=n(e),[i,a]=n(t);for(let l=0;l<Math.max(r.length,i.length);l+=1){let c=(r[l]??0)-(i[l]??0);if(c!==0)return c<0?-1:1}if(o.length===0&&a.length===0)return 0;if(o.length===0)return 1;if(a.length===0)return-1;for(let l=0;l<Math.max(o.length,a.length);l+=1){let c=o[l],u=a[l];if(c===void 0)return-1;if(u===void 0)return 1;let d=/^\d+$/.test(c),p=/^\d+$/.test(u);if(d&&p){let f=Number(c)-Number(u);if(f!==0)return f<0?-1:1}else{if(d!==p)return d?-1:1;if(c!==u)return c<u?-1:1}}return 0}var Px=w(()=>{"use strict";s(Ks,"compareSemver")});var pm,Mx=w(()=>{"use strict";pm="(Org, team and private conventions could not be loaded for this session \u2014 call get_conventions before relying on this list.)"});var $x=w(()=>{"use strict"});var fm=w(()=>{"use strict"});var Lx=w(()=>{"use strict";fm()});var Et=w(()=>{"use strict";Sn();Ov();Sn();Sn();Mv();$v();Lv();Gv();qv();fS();Sn();Nf();AS();WS();yx();js();tm();lc();Tx();Rx();Ox();Nx();Df();Dx();Px();Mx();zf();$x();fm();Lx()});function Wx(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
12
12
  `).slice(0,1e3)}var Vx=w(()=>{"use strict";s(Wx,"nodeEmbedText")});var mm,hm=w(()=>{"use strict";mm=["function","method","class","interface","enum","type_alias"]});function qx(e,t){let n=Math.min(e.length,t.length),r=0,o=0,i=0;for(let a=0;a<n;a++){let l=e[a],c=t[a];r+=l*c,o+=l*l,i+=c*c}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var zx=w(()=>{"use strict";s(qx,"cosineSimilarity")});import{execFileSync as uU}from"node:child_process";import{createHash as dU}from"node:crypto";import{readFileSync as pU}from"node:fs";import{posix as Gt}from"node:path";function Jx(e){let t=dU("sha256"),n=[];try{n=uU("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
13
13
  `).filter(c=>fU.test(c)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,o=s(c=>{if(r.has(c))return r.get(c);try{let u=pU(Gt.join(e,c),"utf8");return r.set(c,u),u}catch{return null}},"read"),i=[],a=new Map;for(let c of n.filter(u=>!u.endsWith("package.json"))){let u=Yx(c,o,0),d=Gt.dirname(c)==="."?"":Gt.dirname(c);c.endsWith("tsconfig.json")&&a.set(d,u),u.paths&&i.push({dir:u.pathsDir??d,baseUrl:u.baseUrl,paths:u.paths})}let l=[];for(let c of n.filter(u=>u.endsWith("package.json"))){let u=Xx(o(c));if(!u||typeof u.name!="string")continue;let d=Gt.dirname(c)==="."?"":Gt.dirname(c),p=a.get(d);l.push({name:u.name,dir:d,exports:u.exports,main:typeof u.main=="string"?u.main:void 0,module:typeof u.module=="string"?u.module:void 0,types:typeof u.types=="string"?u.types:void 0,outDir:p?.outDir,rootDir:p?.rootDir})}for(let c of[...r.keys()].sort())t.update(c).update("\0").update(r.get(c)).update("\0");return{config:{packages:l,tsconfigs:i},fingerprint:t.digest("hex")}}function Yx(e,t,n){let r=Xx(t(e));if(!r)return{};let o=Gt.dirname(e)==="."?"":Gt.dirname(e),i={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let u=Gt.normalize(Gt.join(o,a.endsWith(".json")?a:a+".json"));i=Yx(u,t,n+1)}let l=r.compilerOptions??{},c={...i};return typeof l.outDir=="string"&&(c.outDir=Gt.normalize(l.outDir)),typeof l.rootDir=="string"&&(c.rootDir=Gt.normalize(l.rootDir)),l.paths&&typeof l.paths=="object"&&(c.paths=l.paths,c.pathsDir=o,c.baseUrl=typeof l.baseUrl=="string"?l.baseUrl:void 0),c}function Xx(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(n){t+=o,o==="\\"?t+=e[++r]??"":o==='"'&&(n=!1);continue}if(o==='"')n=!0,t+=o;else if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
@@ -142,7 +142,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
142
142
  `))c.startsWith("worktree ")?i=c.slice(9):c.startsWith("branch ")?a=c.slice(7).replace(/^refs\/heads\//,""):c.startsWith("prunable")&&(l=!0);i&&a&&!l&&n.push({path:i,branch:a})}),n}function HA(e){let t=new Set;for(let n of e.split(`
143
143
  `)){let[r,o]=n.split(" ");r&&o?.trim()==="[gone]"&&t.add(r.trim())}return t}function ug(e,t){let n=HA(t);return FA(e).filter(r=>n.has(r.branch)).sort((r,o)=>r.path.localeCompare(o.path))}function jA(e,t,n){try{return CK("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:n})}catch{return null}}function UA(e){let t=e.trim();if(!/^\[(ahead|behind) /.test(t))return null;let n=/ahead (\d+)/.exec(t),r=/behind (\d+)/.exec(t);return{ahead:n?Number(n[1]):0,behind:r?Number(r[1]):0}}function BA(e,t){let n=e.split(/\n\s*\n/).find(i=>i.trim().length>0);if(!n)return null;let r=null,o=null;for(let i of n.split(`
144
144
  `))i.startsWith("worktree ")?r=i.slice(9):i.startsWith("branch ")&&(o=i.slice(7).replace(/^refs\/heads\//,""));if(!r||!o)return null;for(let i of t.split(`
145
- `)){let[a,l,c]=i.split(" ");if(a?.trim()!==o)continue;let u=UA(l??""),d=c?.trim()??"";return u===null||u.behind===0||d.length===0?null:{path:r,branch:o,upstream:d,behind:u.behind,ahead:u.ahead}}return null}function tu(e,t={}){let n=t.timeoutMs??2e3,r=jA(e,["worktree","list","--porcelain"],n);if(r===null)return null;let o=jA(e,["for-each-ref","--format=%(refname:short)%09%(upstream:track)%09%(upstream:short)","refs/heads/"],n);if(o===null)return null;let i=BA(r,o);if(i!==null&&i.ahead===0){let a=ag(i.path,i.upstream,{timeoutMs:n});if(a!==null)return{gone:ug(r,o),mainLag:{...i,blockedBy:a}}}return{gone:ug(r,o),mainLag:i}}function dg(e,t={}){return tu(e,t)?.gone??null}var GA=w(()=>{"use strict";cg();s(FA,"parseLinkedWorktrees");s(HA,"parseGoneBranches");s(ug,"goneBranchWorktrees");s(jA,"gitQuick");s(UA,"parseUpstreamTrack");s(BA,"mainCheckoutLag");s(tu,"readWorktreeHealth");s(dg,"listGoneBranchWorktrees")});var IK,Vle,KA=w(()=>{"use strict";Pe();IK=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],Vle=new RegExp(IK.join("|"),"g")});import{existsSync as pg,readdirSync as OK,readFileSync as NK}from"node:fs";import{spawnSync as DK}from"node:child_process";import{dirname as PK,join as nu,posix as fg}from"node:path";function VA(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 ${mg} 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 ${mg} 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,h={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:h.title,detail:h.detailText,hint:h.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(mt);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 l=r.versions.filter(p=>!i.has(p)).sort(mt),c=new Map,u=[];for(let p of l){let f=e.siblingVersions.get(p);if(f){let m=c.get(f)??[];m.push(p),c.set(f,m)}else u.push(p)}for(let[p,f]of c)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(h=>!p.has(h)).sort(mt),m=e.remote.versions.filter(h=>!i.has(h)).sort(mt);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 qA(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function JA(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(`
145
+ `)){let[a,l,c]=i.split(" ");if(a?.trim()!==o)continue;let u=UA(l??""),d=c?.trim()??"";return u===null||u.behind===0||d.length===0?null:{path:r,branch:o,upstream:d,behind:u.behind,ahead:u.ahead}}return null}function tu(e,t={}){let n=t.timeoutMs??2e3,r=jA(e,["worktree","list","--porcelain"],n);if(r===null)return null;let o=jA(e,["for-each-ref","--format=%(refname:short)%09%(upstream:track)%09%(upstream:short)","refs/heads/"],n);if(o===null)return null;let i=BA(r,o);if(i!==null&&i.ahead===0){let a=ag(i.path,i.upstream,{timeoutMs:n});if(a!==null)return{gone:ug(r,o),mainLag:{...i,blockedBy:a}}}return{gone:ug(r,o),mainLag:i}}function dg(e,t={}){return tu(e,t)?.gone??null}var GA=w(()=>{"use strict";cg();s(FA,"parseLinkedWorktrees");s(HA,"parseGoneBranches");s(ug,"goneBranchWorktrees");s(jA,"gitQuick");s(UA,"parseUpstreamTrack");s(BA,"mainCheckoutLag");s(tu,"readWorktreeHealth");s(dg,"listGoneBranchWorktrees")});var IK,Jle,KA=w(()=>{"use strict";Pe();IK=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],Jle=new RegExp(IK.join("|"),"g")});import{existsSync as pg,readdirSync as OK,readFileSync as NK}from"node:fs";import{spawnSync as DK}from"node:child_process";import{dirname as PK,join as nu,posix as fg}from"node:path";function VA(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 ${mg} 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 ${mg} 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,h={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:h.title,detail:h.detailText,hint:h.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(mt);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 l=r.versions.filter(p=>!i.has(p)).sort(mt),c=new Map,u=[];for(let p of l){let f=e.siblingVersions.get(p);if(f){let m=c.get(f)??[];m.push(p),c.set(f,m)}else u.push(p)}for(let[p,f]of c)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(h=>!p.has(h)).sort(mt),m=e.remote.versions.filter(h=>!i.has(h)).sort(mt);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 qA(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function JA(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(`
146
146
  `).filter(Boolean).slice(-1)[0]}}function WA(e,t,n){let r=e(t,MK,n);return r.ok===!1?JA(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
147
147
  `).map(o=>o.trim()).filter(Boolean)}}function YA(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 $K(e){let t=I(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=PK(t);return n===e?null:n}function LK(e,t,n){let r=fg.dirname(t),i=[{path:nu(e,r,"config.toml"),source:"worktree"}],a=$K(e);a&&i.push({path:nu(a,r,"config.toml"),source:"main_worktree"});for(let l of i)if(pg(l.path))try{let c=YA(NK(l.path,"utf8"));if(c===null){n.push(`${l.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:l.source,port:c}}catch{n.push(`${l.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function jK(e,t){let n=new Map,r=I(e,["worktree","list","--porcelain"]);if(r===null)return n;let o=I(e,["rev-parse","--show-toplevel"])?.trim();for(let i of r.split(`
148
148
  `)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===o||!pg(a))continue;let l=nu(a,t);if(pg(l))try{for(let c of OK(l)){let u=di(c);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function hg(e,t={}){let n=t.runPsql??zA,r=t.timeoutMs??15e3,o=[],i=to(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=[],l=[],c=[];for(let p of i){let f=LK(e,p.dir,o),m=f.source==="missing"?null:WA(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),h=t.remoteDbUrl!==void 0?WA(n,t.remoteDbUrl,r):null,g=VA({dir:p.dir,projectRoot:nu(e,fg.dirname(fg.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:f,ledger:m,siblingVersions:jK(e,p.dir),remote:h});a.push(...g.findings),c.push(g.verdict),l.push({dir:p.dir,migrationCount:p.files.length,verdict:g.verdict,db:g.db})}let u=qA(c),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:l,remoteConsulted:t.remoteDbUrl!==void 0,skipped:o}}}var mg,zA,MK,XA=w(()=>{"use strict";Pe();ro();mg=54322;s(VA,"evaluateLedgerProject");s(qA,"deriveLedgerVerdict");zA=s((e,t,n)=>{let r=DK("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"),MK="select version from supabase_migrations.schema_migrations order by version";s(JA,"classifyLedgerError");s(WA,"readLedger");s(YA,"parseDbPort");s($K,"mainWorktreeRoot");s(LK,"resolveConfig");s(jK,"gatherSiblingVersions");s(hg,"checkMigrationLedgerDrift")});function Ct(e){return typeof e=="string"?e:String(e??"")}function pa(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function gg(e){return{nodeKey:Ct(e.node_key),kind:Ct(e.kind),name:Ct(e.name),qualifiedName:Ct(e.qualified_name),filePath:Ct(e.file_path),startLine:pa(e.start_line),endLine:pa(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function eR(e){return{path:Ct(e.path),language:Ct(e.language),contentHash:Ct(e.content_hash),mtimeMs:pa(e.mtime_ms),size:pa(e.size),indexedAt:pa(e.indexed_at)}}function yg(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(Qn.meta).get(o);return i===void 0?null:Ct(i.value)},"metaValue");return{meta(){let o=r(Zn),i=r(ua);return{schemaVersion:o,schemaCurrent:o===Xn,edgesDirty:r(_i)==="1",lastIndexedAt:i===null?null:Number(i)}},file(o){let i=n(Qn.file).get(o);return i===void 0?null:eR(i)},files(o){let i=new Map;for(let a of new Set(o)){let l=n(Qn.file).get(a);l!==void 0&&i.set(a,eR(l))}return i},symbolsInFile(o,i=FK){return n(Qn.symbolsInFile).all(o,i).map(gg)},symbolsNamed(o,i=HK){let a=new Map;for(let l of new Set(o)){let c=n(Qn.symbolsNamed).all(l,i);c.length>0&&a.set(l,c.map(gg))}return a},callersOfFile(o,i=UK){return n(Qn.callersOfFile).all(o,o,i).map(l=>({calleeKey:Ct(l.callee_key),kind:Ct(l.edge_kind),caller:gg(l)}))},importersOf(o,i=BK){let a=n(Qn.importersOf).all(sn(o),i),l=[];for(let c of a){let u=Ct(c.src_key),d=u.endsWith(QA)?u.slice(0,-QA.length):u;d!==o&&!l.includes(d)&&l.push(d)}return l},close(){e.close()}}}function fa(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var ZA,Qn,FK,HK,UK,BK,QA,_g=w(()=>{"use strict";eo();bi();ZA="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",Qn={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 ${ZA} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${ZA} 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 ?"},FK=400,HK=8,UK=600,BK=200,QA="#<module>";s(Ct,"str");s(pa,"num");s(gg,"toSymbol");s(eR,"toFileRow");s(yg,"createIndexReader");s(fa,"isFileCurrent")});var bg,kg=w(()=>{"use strict";bg="0.2.0"});function wg(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:zn,attest:!0}}function vg(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>ru||a!==void 0&&a.length>ou){n+=1;continue}r.push({name:i.name,...a!==void 0?{qualified_name:a}:{},...i.kind&&i.kind.length<=nR?{kind:i.kind}:{},...i.language&&i.language.length<=rR?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),oR)})}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:bg},dropped:n}}function Sg(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 xg(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 ${zn} (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 ki(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===tR&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===tR?{kind:"invalid_params",code:n,detail:r,issues:GK(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function GK(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 Eg(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 ru,ou,nR,rR,oR,tR,KK,iR=w(()=>{"use strict";Et();kg();ru=200,ou=512,nR=64,rR=32,oR=1e4;s(wg,"attestReviewOptions");s(vg,"buildAttestPayload");s(Sg,"attestPersistDecision");s(xg,"attestCoverageNote");tR=-32602;s(ki,"classifyMcpErrorText");s(GK,"parseIssues");s(Eg,"isLegacyAttestRejection");KK=`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 WK}from"node:child_process";import{existsSync as VK,readFileSync as qK,readdirSync as zK}from"node:fs";import{basename as JK,join as sR}from"node:path";function iu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cR(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=JK(i);for(let[u,d]of XK)a===u&&r.add(d);if(ZK.test(i)&&(n.add("supabase"),n.add("postgres")),a!=="package.json"||o>=lR)continue;o+=1;let l=t(i);if(!iu(l))continue;r.add("javascript");let c={...iu(l.dependencies)?l.dependencies:{},...iu(l.devDependencies)?l.devDependencies:{},...iu(l.peerDependencies)?l.peerDependencies:{}};Object.prototype.hasOwnProperty.call(c,"typescript")&&r.add("typescript");for(let[u,d]of YK)Object.prototype.hasOwnProperty.call(c,u)&&n.add(d)}return{platforms:[...n].sort(),languages:[...r].sort()}}function ho(e){return[...e.platforms,...e.languages]}function aR(e,t){try{return WK("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3,maxBuffer:64*1024*1024})}catch{return null}}function Rn(e){let t=aR(e,["rev-parse","--show-toplevel"])?.trim()||null,n=e,r,o=t===null?null:aR(t,["ls-files","-z"]);if(t!==null&&o!==null)n=t,r=o.split("\0").filter(i=>i.length>0);else{try{r=zK(e)}catch{return{platforms:[],languages:[]}}VK(sR(e,"supabase","migrations"))&&r.push("supabase/migrations/")}return cR(r,i=>{try{return JSON.parse(qK(sR(n,i),"utf8"))}catch{return null}})}var lR,YK,XK,ZK,uR=w(()=>{"use strict";lR=200,YK=[["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"]],XK=[["tsconfig.json","typescript"],["pyproject.toml","python"],["requirements.txt","python"],["go.mod","go"],["Cargo.toml","rust"]],ZK=/(^|\/)supabase\/(config\.toml$|migrations\/)/;s(iu,"isRecord");s(cR,"inferRepoStack");s(ho,"repoStackSlugs");s(aR,"git");s(Rn,"detectRepoStack")});var Me=w(()=>{"use strict";Jw();ig();Am();Qh();Pe();Fc();hh();sh();uh();ph();Lm();MA();GA();cg();KA();Om();ta();Kc();Mh();Fh();Bh();ia();ro();la();XA();Zm();Yh();ta();ia();Kc();la();vc();hm();bi();_g();xc();kg();iR();uR()});import{homedir as QK}from"node:os";import{join as eW}from"node:path";function au(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=ma(r.id),i=ma(r.key),a=ma(r.title),l=ma(r.status);if(!o||!i||!a||!l)continue;let c=r.here===!1?!1:void 0,u=ma(r.where);if(t.push({id:o,key:i,title:a,status:l,...c===!1?{here:c}:{},...u?{where:u}:{}}),t.length>=tW)break}return t}function Tg(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. This lists what is ASSIGNED to your user, not the newest or most urgent work: when your user asks for something else (e.g. the newest object), answer that question \u2014 list_available_work({order:'newest'}).`}function Ag(e=QK()){return eW(e,".maind","assigned-told")}function dR(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 pR(e){return e==="claude-code"}var tW,ma,su,ha=w(()=>{"use strict";tW=5,ma=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(au,"parseAssignedList");s(Tg,"assignedNoticeText");s(Ag,"assignedToldDir");su=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=au(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 Tg(t)}};s(dR,"labelNestedItems");s(pR,"clientHasHooks")});function gR(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 l=a.name;typeof l=="string"&&(i.toolName=l)}}return i}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function wi(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 Ig(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Og(e,t,n,r,o,i){return{at:r,event:e,server:t,tool:n,convention_id:o,convention_version:i}}function Ng(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Dg=w(()=>{"use strict";s(gR,"parseFrame");s(wi,"denyResult");s(Ig,"toolEvent");s(Og,"policyEvent");s(Ng,"shaEvent")});import{execFileSync as bR}from"node:child_process";function kR(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=pW}function fW(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 cW){let a=r[i];typeof a=="string"&&yR.test(a)&&o.push({field:i,sha:a})}for(let[i,a]of uW){let l=r[i];if(typeof l!="object"||l===null)continue;let c=l[a];typeof c=="string"&&yR.test(c)&&o.push({field:`${i}.${a}`,sha:c})}return o}function mW(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,_R);for(let o=_R;o>=dW;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 vi(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 wR(){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 Si(e=process.cwd()){try{let n=bR("git",["rev-parse","--show-toplevel"],{cwd:e,env:wR(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function hW(e){return t=>{try{let r=bR("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:wR(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function cu(e,t){if(t===null)return[];let n=fW(e);if(n.length===0)return[];let r=hW(t),o=[];for(let{field:i,sha:a}of n){let l=mW(a,r);l.verdict!=="proven"&&o.push({...l,field:i})}return o}var cW,uW,yR,dW,_R,pW,uu=w(()=>{"use strict";cW=["commit_sha","base_sha","head_sha"],uW=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],yR=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,dW=7,_R=12,pW=10;s(kR,"isDenyGrade");s(fW,"extractShaArgs");s(mW,"classifySha");s(vi,"shaFindingText");s(wR,"cleanGitEnv");s(Si,"resolveRepoRootForSha");s(hW,"gitShaResolver");s(cu,"inspectLineForShas")});import{execFileSync as gW}from"node:child_process";import{createHash as yW}from"node:crypto";import{mkdirSync as _W,readFileSync as bW,renameSync as kW,writeFileSync as wW}from"node:fs";import{dirname as SR,join as xR}from"node:path";function gt(e=process.cwd()){try{let t=gW("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function tr(e){return yW("sha256").update(e).digest("hex").slice(0,16)}function du(e){return xR(e,vW)}function ER(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function TR(e,t,n,r=new Date().toISOString()){try{if(!ER(n))return;let o={version:Mg,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,client_family:t.clientFamily??null,result:n},i=du(e);_W(SR(i),{recursive:!0}),Ys(SR(i));let a=`${i}.${process.pid}.tmp`;wW(a,JSON.stringify(o,null,2),"utf8"),kW(a,i)}catch{}}function pu(e,t){try{let n=bW(du(e),"utf8"),r=JSON.parse(n);return r.version!==Mg||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||(r.client_family??null)!==(t.clientFamily??null)||typeof r.cached_at!="string"||!ER(r.result)?null:{version:Mg,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,client_family:r.client_family??null,result:r.result}}catch{return null}}function AR(e,t,n=new Date){let r=SW(t.cached_at,n),o=t.result.instructions??"",i={...t.result,instructions:`${r}
@@ -157,7 +157,7 @@ ${o}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function SW(e,t){ret
157
157
  `),null}async function JW(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 YW(e){return new Promise(t=>setTimeout(t,e))}function XW(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: ${PR(e.verification_uri,56)} \u2502`,` \u2502 Code: ${PR(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(`
158
158
  `)+`
159
159
  `)}function PR(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}async function ZW(e){let t,n;switch(zW()){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=qW(t,n,{stdio:"ignore",detached:!0});i.on("error",o),i.unref(),r()}catch(i){o(i)}})}var Bg=w(()=>{"use strict";we();Ti();s(Ai,"runDeviceFlow");s(JW,"pollOnce");s(YW,"sleep");s(XW,"printAuthInstructions");s(PR,"pad");s(ZW,"openExternalBrowser")});import{mkdirSync as QW,readFileSync as e2,renameSync as t2,writeFileSync as n2}from"node:fs";import{join as r2}from"node:path";function MR(e=Vt()){return r2(e,i2)}function a2(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,s2)}function _o(e,t,n){try{let r=n.dir??Vt();QW(r,{recursive:!0,mode:448});let o={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:a2(t),bridge_version:n.version},i=MR(r),a=`${i}.${process.pid}.tmp`;n2(a,JSON.stringify(o)+`
160
- `,{encoding:"utf8",mode:384}),t2(a,i)}catch{}}function $R(e=Vt()){try{let t=JSON.parse(e2(MR(e),"utf8"));return t.v!==1||typeof t.at!="string"||!o2.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 o2,i2,s2,Gg=w(()=>{"use strict";we();o2=["ok","paired","auth_failed","not_paired"],i2="connection-state.json",s2=200;s(MR,"connectionStatePath");s(a2,"redactDetail");s(_o,"writeConnectionState");s($R,"readConnectionState")});var K,Xe=w(()=>{"use strict";K="0.129.0"});import{execFileSync as LR}from"node:child_process";import{createHash as l2}from"node:crypto";function Kg(e){return l2("sha256").update(e).digest("hex")}function Wg(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function nr(e){let t=Wg(e);return t?Kg(t):null}function Z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&c2.test(e))return e;let t;try{t=LR("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nr(t):null}function Ke(e){let t;try{t=LR("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nr(t):null}var c2,de=w(()=>{"use strict";s(Kg,"sha256Hex");s(Wg,"normalizeRemoteUrl");s(nr,"projectKeyFromRemote");c2=/^[a-f0-9]{64}$/;s(Z,"computeProjectKey");s(Ke,"projectKeyForRepo")});import u2 from"node:path";import{fileURLToPath as d2}from"node:url";function p2(e,t=u2.sep){return e.split(t).includes("_npx")}function Ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",jR,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):p2(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 se(){try{let e=d2(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function at(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${ba(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:ba(n)).join(" ")}function It(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(jR)}function _u(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function ba(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var jR,Ze=w(()=>{"use strict";jR="@maind-dev/mcp-bridge";s(p2,"isEphemeralEntry");s(Ee,"resolveBridgeLaunch");s(se,"currentBridgeEntry");s(at,"launchToShellCommand");s(It,"isNpxForm");s(_u,"isLegacyHookForm");s(ba,"shellQuote")});import{readFileSync as f2}from"node:fs";import*as H from"node:path";function UR(e){let t=e.launch??Ee({entryPath:se(),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 GR(e){return vu(e,"Claude")}function h2(e){return H.join(GR(e),BR)}function vu(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 g2(e){return H.join(vu(e,"Code"),"User")}function ku(e,t,n=[]){return{kind:"foreign-entries",dir:vu(e,t),ours:["User",...n]}}function FR(e){return e.localAppData??H.join(e.homeDir,"AppData","Local")}function _2(e){let t=[{kind:"foreign-entries",dir:GR(e),ours:[BR]}];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(FR(e),"AnthropicClaude")},{kind:"dir",path:H.join(FR(e),"Packages",y2)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Cn(e){return{evidence:[ku(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 KR(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 b2(e){return H.join(KR(e),"mcp_config.json")}function WR(e){return H.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function wu(e){let t=[ku(e,"Devin",["mcp_config.json"]),{kind:"dir",path:H.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:KR(e),ours:["mcp_config.json"]}),t.push(ku(e,"Windsurf"),{kind:"foreign-entries",dir:H.dirname(WR(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 x2(e){return e===null?null:S2.exec(e)?.[1]??null}function qR(e,t){let n=VR.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 v2)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 zR(e){return e.clineDataDir?e.clineDataDir:H.join(e.clineDir??H.join(e.homeDir,".cline"),"data")}function E2(e){return e.clineMcpSettingsPath??H.join(zR(e),"settings","cline_mcp_settings.json")}function Vg(e){return{evidence:[{kind:"foreign-entries",dir:zR(e),ours:["settings"]},...k2.map(t=>({kind:"dir",path:H.join(vu(e,t),"User","globalStorage",HR)})),...qR(e,HR)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function Su(e){return e.continueGlobalDir??H.join(e.homeDir,".continue")}function T2(e){return H.join(Su(e),"mcpServers","maind.json")}function qg(e){return{evidence:[{kind:"foreign-entries",dir:Su(e),ours:["mcpServers","rules"]},...qR(e,w2)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function rr(e){return e.codexHome??H.join(e.homeDir,".codex")}function bo(e){return H.join(rr(e),"config.toml")}function Ci(e){let t=rr(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 JR(e){return H.join(e.geminiCliHome??e.homeDir,".gemini")}function Ii(e){return H.join(JR(e),"settings.json")}function Oi(e){let t=JR(e),n=H.join(e.homeDir,".gemini"),r=[{kind:"foreign-entries",dir:t,ours:["settings.json"]}];return t!==n&&r.push({kind:"foreign-entries",dir:n,ours:["settings.json"]}),{evidence:r,skipDetail:t===n?"Gemini CLI not found (nothing of Gemini's in ~/.gemini)":"Gemini CLI not found (nothing of Gemini's in $GEMINI_CLI_HOME/.gemini or ~/.gemini)"}}function ka(e){return{evidence:[ku(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function A2(e){return H.join(g2(e),"mcp.json")}function wa(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:h2(e),kind:"json",presence:_2(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:H.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Cn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:b2(e),kind:"json",presence:wu(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:WR(e),kind:"json",presence:wu(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:A2(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:ka(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:E2(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:Vg(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:T2(e),kind:"json",presence:qg(e)},{key:"gemini-cli",label:"Gemini CLI (~/.gemini/settings.json)",clientFamilyEnv:"gemini-cli",scope:"user",path:Ii(e),kind:"json",presence:Oi(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:bo(e),kind:"toml",presence:Ci(e)}]}function YR(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function XR(e){return e.jsonShape??m2}function ZR(e){let{homeDir:t,platform:n,env:r}=e,o=H.join(t,"Documents");if(n==="win32"){let c=["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,...c])]}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,l=a===null?null:QR(a,t);return l!==null&&l!==o?[l,o]:[o]}function QR(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 qt(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:bu(e.env.XDG_CONFIG_HOME),appData:bu(e.env.APPDATA),localAppData:bu(e.env.LOCALAPPDATA),clineDir:Ri(e.env.CLINE_DIR),clineDataDir:Ri(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:Ri(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:Ri(e.env.CONTINUE_GLOBAL_DIR),codexHome:Ri(e.env.CODEX_HOME),geminiCliHome:Ri(e.env.GEMINI_CLI_HOME),bundleAppRoot:x2(e.bridgeEntry??null),documentsDirs:ZR({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return f2(t,"utf8")}catch{return null}},"readText")})}}function bu(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Ri(e){let t=bu(e);return t!==null&&H.isAbsolute(t)?t:null}var m2,BR,y2,VR,k2,HR,w2,v2,S2,zg,We=w(()=>{"use strict";Ze();m2={serversKey:"mcpServers"};s(UR,"buildMaindServerEntry");BR="claude_desktop_config.json";s(GR,"claudeDesktopAppDataDir");s(h2,"claudeDesktopConfigPath");s(vu,"editorAppDataDir");s(g2,"vsCodeUserDir");s(ku,"editorRan");s(FR,"localAppDataDir");y2="Claude_pzs8sxrjxfjjc";s(_2,"claudeDesktopPresence");s(Cn,"cursorPresence");s(KR,"devinConfigDir");s(b2,"devinMcpConfigPath");s(WR,"windsurfLegacyMcpConfigPath");s(wu,"devinDesktopPresence");VR=[{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"}],k2=VR.map(e=>e.appData),HR="saoudrizwan.claude-dev",w2="continue.continue",v2=["AgentComposer"],S2=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(x2,"bundleAppRootOf");s(qR,"agentExtensionEvidence");s(zR,"clineDataDir");s(E2,"clineMcpSettingsPath");s(Vg,"clinePresence");s(Su,"continueGlobalDir");s(T2,"continueMcpConfigPath");s(qg,"continuePresence");s(rr,"codexHomeDir");s(bo,"codexConfigPath");s(Ci,"codexPresence");s(JR,"geminiDir");s(Ii,"geminiSettingsPath");s(Oi,"geminiPresence");s(ka,"vsCodePresence");s(A2,"vsCodeUserMcpPath");s(wa,"getClientTargets");s(YR,"filterTargetsByFamily");s(XR,"jsonShapeOf");zg=[...new Set(wa({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(ZR,"documentsDirCandidates");s(QR,"parseXdgDocumentsDir");s(qt,"makeDefaultContext");s(bu,"nonEmpty");s(Ri,"absoluteOrNull")});function Jg(){return zg.map(e=>{let t=Object.keys(xu).filter(n=>xu[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function eC(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(R2),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 Ot("--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 Ot("--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 Ot("--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 Ot("--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 Ot(`--client requires a family argument (${Jg()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(xu,i)?xu[i]:i;if(!zg.includes(a))throw new Ot(`--client "${o}" is not a known client family. Known: ${Jg()}`);t.client=a,n++;break}default:throw new Ot(`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 Ot(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function tC(){process.stdout.write(C2())}function C2(){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:",` ${Jg()}`," (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(`
160
+ `,{encoding:"utf8",mode:384}),t2(a,i)}catch{}}function $R(e=Vt()){try{let t=JSON.parse(e2(MR(e),"utf8"));return t.v!==1||typeof t.at!="string"||!o2.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 o2,i2,s2,Gg=w(()=>{"use strict";we();o2=["ok","paired","auth_failed","not_paired"],i2="connection-state.json",s2=200;s(MR,"connectionStatePath");s(a2,"redactDetail");s(_o,"writeConnectionState");s($R,"readConnectionState")});var K,Xe=w(()=>{"use strict";K="0.129.1"});import{execFileSync as LR}from"node:child_process";import{createHash as l2}from"node:crypto";function Kg(e){return l2("sha256").update(e).digest("hex")}function Wg(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function nr(e){let t=Wg(e);return t?Kg(t):null}function Z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&c2.test(e))return e;let t;try{t=LR("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nr(t):null}function Ke(e){let t;try{t=LR("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?nr(t):null}var c2,de=w(()=>{"use strict";s(Kg,"sha256Hex");s(Wg,"normalizeRemoteUrl");s(nr,"projectKeyFromRemote");c2=/^[a-f0-9]{64}$/;s(Z,"computeProjectKey");s(Ke,"projectKeyForRepo")});import u2 from"node:path";import{fileURLToPath as d2}from"node:url";function p2(e,t=u2.sep){return e.split(t).includes("_npx")}function Ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",jR,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):p2(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 se(){try{let e=d2(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function at(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${ba(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:ba(n)).join(" ")}function It(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(jR)}function _u(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function ba(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var jR,Ze=w(()=>{"use strict";jR="@maind-dev/mcp-bridge";s(p2,"isEphemeralEntry");s(Ee,"resolveBridgeLaunch");s(se,"currentBridgeEntry");s(at,"launchToShellCommand");s(It,"isNpxForm");s(_u,"isLegacyHookForm");s(ba,"shellQuote")});import{readFileSync as f2}from"node:fs";import*as H from"node:path";function UR(e){let t=e.launch??Ee({entryPath:se(),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 GR(e){return vu(e,"Claude")}function h2(e){return H.join(GR(e),BR)}function vu(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 g2(e){return H.join(vu(e,"Code"),"User")}function ku(e,t,n=[]){return{kind:"foreign-entries",dir:vu(e,t),ours:["User",...n]}}function FR(e){return e.localAppData??H.join(e.homeDir,"AppData","Local")}function _2(e){let t=[{kind:"foreign-entries",dir:GR(e),ours:[BR]}];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(FR(e),"AnthropicClaude")},{kind:"dir",path:H.join(FR(e),"Packages",y2)}),{evidence:t,skipDetail:"Claude Desktop not found (no Claude app, no Claude Desktop app data beyond our config file)"}}function Cn(e){return{evidence:[ku(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 KR(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 b2(e){return H.join(KR(e),"mcp_config.json")}function WR(e){return H.join(e.homeDir,".codeium","windsurf","mcp_config.json")}function wu(e){let t=[ku(e,"Devin",["mcp_config.json"]),{kind:"dir",path:H.join(e.homeDir,".devin")}];return e.platform!=="win32"&&t.push({kind:"foreign-entries",dir:KR(e),ours:["mcp_config.json"]}),t.push(ku(e,"Windsurf"),{kind:"foreign-entries",dir:H.dirname(WR(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 x2(e){return e===null?null:S2.exec(e)?.[1]??null}function qR(e,t){let n=VR.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 v2)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 zR(e){return e.clineDataDir?e.clineDataDir:H.join(e.clineDir??H.join(e.homeDir,".cline"),"data")}function E2(e){return e.clineMcpSettingsPath??H.join(zR(e),"settings","cline_mcp_settings.json")}function Vg(e){return{evidence:[{kind:"foreign-entries",dir:zR(e),ours:["settings"]},...k2.map(t=>({kind:"dir",path:H.join(vu(e,t),"User","globalStorage",HR)})),...qR(e,HR)],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline extension or storage in any editor)"}}function Su(e){return e.continueGlobalDir??H.join(e.homeDir,".continue")}function T2(e){return H.join(Su(e),"mcpServers","maind.json")}function qg(e){return{evidence:[{kind:"foreign-entries",dir:Su(e),ours:["mcpServers","rules"]},...qR(e,w2)],skipDetail:"Continue not found (nothing of Continue's in ~/.continue, no Continue extension in any editor)"}}function rr(e){return e.codexHome??H.join(e.homeDir,".codex")}function bo(e){return H.join(rr(e),"config.toml")}function Ci(e){let t=rr(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 JR(e){return H.join(e.geminiCliHome??e.homeDir,".gemini")}function Ii(e){return H.join(JR(e),"settings.json")}function Oi(e){let t=JR(e),n=H.join(e.homeDir,".gemini"),r=[{kind:"foreign-entries",dir:t,ours:["settings.json"]}];return t!==n&&r.push({kind:"foreign-entries",dir:n,ours:["settings.json"]}),{evidence:r,skipDetail:t===n?"Gemini CLI not found (nothing of Gemini's in ~/.gemini)":"Gemini CLI not found (nothing of Gemini's in $GEMINI_CLI_HOME/.gemini or ~/.gemini)"}}function ka(e){return{evidence:[ku(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}}function A2(e){return H.join(g2(e),"mcp.json")}function wa(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:h2(e),kind:"json",presence:_2(e)},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:H.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Cn(e)},{key:"windsurf",label:"Devin Desktop (formerly Windsurf)",clientFamilyEnv:"windsurf",scope:"user",path:b2(e),kind:"json",presence:wu(e)},{key:"windsurf-legacy",label:"Devin Desktop (formerly Windsurf), legacy ~/.codeium/windsurf/mcp_config.json",clientFamilyEnv:"windsurf",scope:"user",path:WR(e),kind:"json",presence:wu(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:A2(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:ka(e)},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:E2(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:Vg(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:T2(e),kind:"json",presence:qg(e)},{key:"gemini-cli",label:"Gemini CLI (~/.gemini/settings.json)",clientFamilyEnv:"gemini-cli",scope:"user",path:Ii(e),kind:"json",presence:Oi(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:bo(e),kind:"toml",presence:Ci(e)}]}function YR(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function XR(e){return e.jsonShape??m2}function ZR(e){let{homeDir:t,platform:n,env:r}=e,o=H.join(t,"Documents");if(n==="win32"){let c=["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,...c])]}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,l=a===null?null:QR(a,t);return l!==null&&l!==o?[l,o]:[o]}function QR(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 qt(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:bu(e.env.XDG_CONFIG_HOME),appData:bu(e.env.APPDATA),localAppData:bu(e.env.LOCALAPPDATA),clineDir:Ri(e.env.CLINE_DIR),clineDataDir:Ri(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:Ri(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:Ri(e.env.CONTINUE_GLOBAL_DIR),codexHome:Ri(e.env.CODEX_HOME),geminiCliHome:Ri(e.env.GEMINI_CLI_HOME),bundleAppRoot:x2(e.bridgeEntry??null),documentsDirs:ZR({homeDir:e.homeDir,platform:e.platform,env:e.env,readText:s(t=>{try{return f2(t,"utf8")}catch{return null}},"readText")})}}function bu(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Ri(e){let t=bu(e);return t!==null&&H.isAbsolute(t)?t:null}var m2,BR,y2,VR,k2,HR,w2,v2,S2,zg,We=w(()=>{"use strict";Ze();m2={serversKey:"mcpServers"};s(UR,"buildMaindServerEntry");BR="claude_desktop_config.json";s(GR,"claudeDesktopAppDataDir");s(h2,"claudeDesktopConfigPath");s(vu,"editorAppDataDir");s(g2,"vsCodeUserDir");s(ku,"editorRan");s(FR,"localAppDataDir");y2="Claude_pzs8sxrjxfjjc";s(_2,"claudeDesktopPresence");s(Cn,"cursorPresence");s(KR,"devinConfigDir");s(b2,"devinMcpConfigPath");s(WR,"windsurfLegacyMcpConfigPath");s(wu,"devinDesktopPresence");VR=[{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"}],k2=VR.map(e=>e.appData),HR="saoudrizwan.claude-dev",w2="continue.continue",v2=["AgentComposer"],S2=/^(.+)[\\/]maind-bridge[\\/]node_modules[\\/]@maind-dev[\\/]mcp-bridge[\\/]build[\\/]index\.js$/;s(x2,"bundleAppRootOf");s(qR,"agentExtensionEvidence");s(zR,"clineDataDir");s(E2,"clineMcpSettingsPath");s(Vg,"clinePresence");s(Su,"continueGlobalDir");s(T2,"continueMcpConfigPath");s(qg,"continuePresence");s(rr,"codexHomeDir");s(bo,"codexConfigPath");s(Ci,"codexPresence");s(JR,"geminiDir");s(Ii,"geminiSettingsPath");s(Oi,"geminiPresence");s(ka,"vsCodePresence");s(A2,"vsCodeUserMcpPath");s(wa,"getClientTargets");s(YR,"filterTargetsByFamily");s(XR,"jsonShapeOf");zg=[...new Set(wa({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];s(ZR,"documentsDirCandidates");s(QR,"parseXdgDocumentsDir");s(qt,"makeDefaultContext");s(bu,"nonEmpty");s(Ri,"absoluteOrNull")});function Jg(){return zg.map(e=>{let t=Object.keys(xu).filter(n=>xu[n]===e);return t.length>0?`${e} (or ${t.join(", ")})`:e}).join(", ")}function eC(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(R2),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 Ot("--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 Ot("--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 Ot("--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 Ot("--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 Ot(`--client requires a family argument (${Jg()})`);let i=o.trim().toLowerCase(),a=Object.hasOwn(xu,i)?xu[i]:i;if(!zg.includes(a))throw new Ot(`--client "${o}" is not a known client family. Known: ${Jg()}`);t.client=a,n++;break}default:throw new Ot(`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 Ot(`--hooks-only sets up the user-level channels and nothing else \u2014 drop ${n.join(", ")}`)}return t}function tC(){process.stdout.write(C2())}function C2(){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:",` ${Jg()}`," (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(`
161
161
  `)}var xu,R2,Ot,nC=w(()=>{"use strict";We();xu={devin:"windsurf"};s(Jg,"familyChoices");R2="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(eC,"parseInstallFlags");Ot=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};s(tC,"printInstallHelp");s(C2,"installHelpText")});var va,rC=w(()=>{"use strict";va=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_
162
162
  `;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"),l=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(o)} | ${"-".repeat(i)} |`,c=[];c.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],o)} | ${a(t[3],i)} |`),c.push(l);for(let u of this.results)c.push(`| ${a(u.target,n)} | ${a(u.action,r)} | ${a(u.status,o)} | ${a(u.detail??"",i)} |`);return c.join(`
163
163
  `)+`
@@ -734,7 +734,7 @@ const tools = await mcp.getTools();
734
734
  "env": {
735
735
  "MAIND_MCP_URL": "${t}"
736
736
  }
737
- }`}]}var lV,cV,py,uV,ape,HC,cn,$u,pV,lpe,Lu=w(()=>{"use strict";lV="__STACK__",cV="__INTENT__",py="https://mcp.maind.dev/mcp",uV=`?stack=${lV}&intent=${cV}`;s(dV,"buildStackAwareEndpoint");ape=dV(py,{stack:["nextjs","supabase"],intent:"mixed"}),HC="npx -y @maind-dev/mcp-bridge on-session-reminder",cn=`## maind MCP integration \u2014 Mandatory consultation
737
+ }`}]}var lV,cV,py,uV,upe,HC,cn,$u,pV,dpe,Lu=w(()=>{"use strict";lV="__STACK__",cV="__INTENT__",py="https://mcp.maind.dev/mcp",uV=`?stack=${lV}&intent=${cV}`;s(dV,"buildStackAwareEndpoint");upe=dV(py,{stack:["nextjs","supabase"],intent:"mixed"}),HC="npx -y @maind-dev/mcp-bridge on-session-reminder",cn=`## maind MCP integration \u2014 Mandatory consultation
738
738
 
739
739
  This project uses the maind MCP server (mcp.maind.dev/mcp) as
740
740
  authoritative source for vetted coding conventions and lessons. The
@@ -803,7 +803,7 @@ For non-trivial changes, resolve documentation path in this order:
803
803
  If no path is discoverable, provide a guided fallback:
804
804
  \`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
805
805
 
806
- Full tool set + provenance via \`get_conventions\`.`,$u="hooks for Claude Code, Codex, Cursor, GitHub Copilot and Gemini CLI, user-level rule files for GitHub Copilot, Cline and Continue",pV="Claude Code, Codex, Cursor, Devin Desktop (formerly Windsurf), GitHub Copilot, Cline, Continue, Gemini CLI and Claude Desktop";s(fV,"buildAiPromptBody");s(lr,"buildJsonConfigInstaller");s(mV,"buildCodexTomlInstaller");s(hV,"buildSnippetTemplates");lpe=hV(py)});function yV(e){return`${Hu}always-on policies served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on Codex session start, do not edit by hand.`}function _V(e){return`${Hu}always-on policies for everyone working in this repository, served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on session start, do not edit by hand.`}function Uu(e,t,n={}){let r=(e??"").replace(/\r\n/g,`
806
+ Full tool set + provenance via \`get_conventions\`.`,$u="hooks for Claude Code, Codex, Cursor, GitHub Copilot and Gemini CLI, user-level rule files for GitHub Copilot, Cline and Continue",pV="Claude Code, Codex, Cursor, Devin Desktop (formerly Windsurf), GitHub Copilot, Cline, Continue, Gemini CLI and Claude Desktop";s(fV,"buildAiPromptBody");s(lr,"buildJsonConfigInstaller");s(mV,"buildCodexTomlInstaller");s(hV,"buildSnippetTemplates");dpe=hV(py)});function yV(e){return`${Hu}always-on policies served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on Codex session start, do not edit by hand.`}function _V(e){return`${Hu}always-on policies for everyone working in this repository, served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on session start, do not edit by hand.`}function Uu(e,t,n={}){let r=(e??"").replace(/\r\n/g,`
807
807
  `).trim(),o=r.length===0?UC:my(r,fy).text,i=n.team===!0?[gV,_V(t)]:[yV(t)];return[ju,...i,o,Fu].join(`
808
808
  `)}function my(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
809
809
  `),r=s(a=>{let l=n.slice(a),c=l.filter(u=>/^- /.test(u)).length;return`\u2026 (${c>0?c:l.length} more via get_conventions)`},"tailFor"),o=[],i=0;for(let a=0;a<n.length;a++){let l=(o.length===0?0:1)+n[a].length,c=a+1<n.length?1+r(a+1).length:0;if(i+l+c>t){if(o.length===0){let d=r(1);o.push(n[0].slice(0,Math.max(0,t-d.length-1)))}let u=r(o.length);return{text:[...o,u].join(`
@@ -851,7 +851,7 @@ commands, file contents or tool output; the agent's own words only when your
851
851
  organization sets agent_activity_text = on. Revocable any time with
852
852
  \`maind-mcp-bridge activity off\` or {"agent_activity": false} in the bridge config.
853
853
  [y/N]: `;s(a0,"applyAgentActivityConsent");s(GV,"promptYesNoDefaultNo")});function vy(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Sy=w(()=>{"use strict";s(vy,"newModeState")});import{createReadStream as KV,existsSync as WV}from"node:fs";import{stat as VV}from"node:fs/promises";import{createInterface as qV}from"node:readline";async function xy(e){if(!e||!WV(e))return null;let t;try{t=await VV(e)}catch{return null}let n=new Set,r=0,o=0,i=0;return await new Promise(a=>{let l=KV(e,{encoding:"utf-8"}),c=qV({input:l});c.on("line",u=>{let d=u.trim();if(d){i++;try{let p=JSON.parse(d),f=p.message?.usage;if(!f)return;let m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,h=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=m??h;if(g!==null){if(n.has(g))return;n.add(g)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(o+=f.output_tokens)}catch{}}}),c.on("close",()=>{a({input_tokens:r,output_tokens:o,total_tokens:r+o,lines_seen:i,last_modified_ms:t.mtimeMs})}),c.on("error",()=>a(null)),l.on("error",()=>a(null))})}var c0=w(()=>{"use strict";s(xy,"summariseTranscript")});var u0=w(()=>{"use strict"});function Pa(e){if(!e)return null;let t=null;for(let n of e.matchAll(JV)){let r=n[1].toLowerCase();zV.has(r)&&(t=r)}return t}var zV,JV,Wu=w(()=>{"use strict";zV=new Set(["low","medium","high","xhigh","max"]),JV=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(Pa,"detectEffortLevel")});function $i(e){for(let t of d0)if(e.startsWith(t)){let n=e.slice(t.length);return n.length>0?n:null}return null}var d0,Vu=w(()=>{"use strict";d0=["mcp__maind__","mcp__plugin_maind_maind__"];s($i,"maindToolName")});import{createReadStream as YV,existsSync as XV,readdirSync as ZV}from"node:fs";import{basename as m0,dirname as QV,join as p0}from"node:path";import{createInterface as eq}from"node:readline";function g0(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!rq.test(n)||e.ids.includes(n)||e.ids.length>=h0||e.ids.push(n)}function oq(e,t){if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let o=$i(r.name);if(o===null||nq.has(o))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?g0(e,i.session_id):o==="announce_session"&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function iq(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t="";for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&(t+=n.text);return t}function sq(e,t){if(!(e.pendingAnnounce.size===0||!Array.isArray(t)))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_result"||typeof r.tool_use_id!="string"||!e.pendingAnnounce.delete(r.tool_use_id))continue;let o=iq(r.content),i=null;try{let a=JSON.parse(o);a&&a.ok===!0&&(i=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(o);i=a?a[1]:null}g0(e,i)}}function Li(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function lq(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let o=aq[r.name];if(!o||!r.input||typeof r.input!="object")continue;let i=r.input[o];typeof i=="string"&&i.length>0&&t.push(i)}return t}function qu(e){let t=m0(e).replace(/\.jsonl$/,""),n=p0(QV(e),t,"subagents"),r;try{r=ZV(n)}catch{return[]}return r.filter(o=>o.endsWith(".jsonl")).sort().map(o=>p0(n,o))}async function f0(e,t,n,r,o,i){XV(e)&&await new Promise(a=>{let l=YV(e,{encoding:"utf-8"}),c=eq({input:l}),u=0;c.on("line",d=>{u++;let p=d.trim();if(!p)return;let f;try{f=JSON.parse(p)}catch{return}if(f.message?.role==="user"){sq(i,f.message.content);return}if(f.message?.role!=="assistant")return;oq(i,f.message.content);let m=typeof f.message.id=="string"&&f.message.id?f.message.id:null,h=typeof f.requestId=="string"&&f.requestId?f.requestId:null,g=m??h??`${e}#${u}`,_=lq(f.message.content),b=r.get(g);if(b){for(let T of _)b.edited_paths.includes(T)||b.edited_paths.push(T);return}if(n.has(g))return;n.add(g);let k=f.message.usage??{},v=typeof f.timestamp=="string"?Date.parse(f.timestamp):Number.NaN,S=typeof f.message.model=="string"&&f.message.model?f.message.model:"",x={ts:Number.isFinite(v)?v:0,model:S||"<unknown>",synthetic:S===tq,input_tokens:Li(k.input_tokens),output_tokens:Li(k.output_tokens),cache_read_tokens:Li(k.cache_read_input_tokens),cache_creation_tokens:Li(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Li(k.cache_creation?.ephemeral_1h_input_tokens),Li(k.cache_creation_input_tokens)),sidechain:f.isSidechain===!0,stream:t,edited_paths:_,cwd:typeof f.cwd=="string"&&f.cwd?f.cwd:null};r.set(g,x),o.push(x)}),c.on("close",()=>a()),c.on("error",()=>a()),l.on("error",()=>a())})}function Ey(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];o.ts>0?n=o.ts:n>0&&(o.ts=n)}}async function Ma(e){let t=new Set,n=new Map,r=[],o=e?qu(e):[],i={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:o,coordination_ids:[]};let a=[];await f0(e,xo,t,n,a,i),Ey(a),r.push(...a);for(let l of o){let c=[],u=m0(l).replace(/\.jsonl$/,"");i.pendingAnnounce.clear(),await f0(l,u,t,n,c,i),Ey(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:o,coordination_ids:i.ids}}var xo,tq,nq,rq,h0,aq,zu=w(()=>{"use strict";Vu();xo="main",tq="<synthetic>",nq=new Set(["get_session_analysis","get_session_cost_context"]),rq=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,h0=32;s(g0,"addCoordinationId");s(oq,"noteCoordinationUse");s(iq,"resultText");s(sq,"noteAnnounceResult");aq={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(Li,"num");s(lq,"editedPathsOf");s(qu,"subagentFilesOf");s(f0,"readStream");s(Ey,"fillTimestamps");s(Ma,"collectTurns")});import{createReadStream as y0,existsSync as cq}from"node:fs";import{createInterface as _0}from"node:readline";function gq(e,t,n,r,o){let i=`${n?"s":"m"}:${t}`,a=e.get(i);if(!a){e.set(i,{model:t,turns:1,output_tokens:r,first_ts:o,last_ts:o,sidechain:n});return}a.turns++,a.output_tokens+=r,o>0&&((a.first_ts===0||o<a.first_ts)&&(a.first_ts=o),o>a.last_ts&&(a.last_ts=o))}function Ju(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function yq(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
854
- `)}function _q(e,t){let n=s(c=>new Set(c.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),o=n(t);if(r.size<3||o.size<3)return!1;let[i,a]=r.size<=o.size?[r,o]:[o,r],l=0;for(let c of i)a.has(c)&&l++;return l/i.size>=.8}function bq(e,t,n){return uq.test(e)?{polarity:-1,magnitude:ji.rework,kind:"rework"}:n&&dq.test(e)?{polarity:-1,magnitude:ji.correction,kind:"correction"}:pq.test(e)?{polarity:1,magnitude:ji.acceptance,kind:"acceptance"}:t!==null&&_q(t,e)?{polarity:-1,magnitude:ji.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function kq(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:b0,behaviour_measured:!0}}async function wq(e,t){for(let n of qu(e))await new Promise(r=>{let o=_0({input:y0(n,{encoding:"utf-8"})});o.on("line",i=>{let a=i.trim();if(!a)return;let l;try{l=JSON.parse(a)}catch{return}if(l.message?.role==="assistant")for(let c of Ju(l.message?.content)){if(c.type!=="tool_use"||typeof c.name!="string")continue;let u=$i(c.name);u!==null&&(t.maind_tool_calls??={},t.maind_tool_calls[u]=(t.maind_tool_calls[u]??0)+1)}}),o.on("error",()=>r()),o.on("close",()=>r())})}async function Ty(e,t={}){let n=kq("");if(!e||!cq(e))return n;let r=t.turns??(await Ma(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let o=[],i=new Map,a=null,l=!1,c=null;await new Promise(m=>{let h=y0(e,{encoding:"utf-8"}),g=_0({input:h}),_=s(b=>{let k=b.trim();if(!k)return;let v;try{v=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let D=v.sessionId??v.session_id;typeof D=="string"&&D&&(n.session_id=D)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let S=v.message?.role,x=v.isSidechain===!0;if(S==="assistant")for(let D of Ju(v.message?.content)){if(D.type!=="tool_use"||typeof D.name!="string")continue;let E=$i(D.name);E!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[E]=(n.maind_tool_calls[E]??0)+1)}if(x)return;if(S==="assistant"){let D=Ju(v.message?.content),E=!1;for(let F of D)F.type==="tool_use"&&(n.tool_calls++,E=!0,F.name==="AskUserQuestion"&&n.agent_questions++);l=E;return}if(S!=="user")return;let T=Ju(v.message?.content),A=yq(T);if(A.includes(fq)){n.interrupts++,o.push({polarity:-1,magnitude:ji.interrupt,kind:"interrupt"});return}if(T.some(D=>D.type==="tool_result"&&D.is_error===!0&&typeof D.content=="string"&&D.content.includes(mq))){n.tool_denials++,o.push({polarity:-1,magnitude:ji.denial,kind:"denial"});return}if(T.some(D=>D.type==="tool_result")||!A.trim())return;n.user_turns++,n.user_chars+=A.length;let R=Pa(A);R&&(a=R);let P=bq(A,c,l);c=A,P.kind==="correction"?n.corrections++:P.kind==="rework"?n.reworks++:P.kind==="repeat"?n.repeated_instructions++:P.kind==="acceptance"&&n.acceptances++,P.polarity!==0&&o.push(P),l=!1},"processLine");g.on("line",b=>{try{_(b)}catch{}}),g.on("close",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),await wq(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||gq(i,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...i.values()].sort((m,h)=>m.first_ts-h.first_ts||m.model.localeCompare(h.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,p=0,f=[];return o.forEach((m,h)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,d=d*hq+m.polarity*m.magnitude;let g=Number(d.toFixed(3));f.push({t:h,value:g,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=g,h>0&&o[h-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var b0,uq,dq,pq,fq,mq,hq,ji,k0=w(()=>{"use strict";Wu();Vu();zu();b0="2026-10-01",uq=/(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i,dq=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,pq=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,fq="[Request interrupted by user",mq="The user doesn't want to proceed with this tool use",hq=.7,ji={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(gq,"bumpModel");s(Ju,"asBlocks");s(yq,"textOf");s(_q,"isRepeat");s(bq,"classifyGenuine");s(kq,"emptyAnalysis");s(wq,"tallySubagentMaindCalls");s(Ty,"analyzeSession")});function Ay(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function Ry(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Yu(e,t,n,r="unknown",o){let i={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...o?{cost_slices:o.slices,cost_context_ok:o.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...l}=n;i.session_span={...t,...l}}else i.session_span=t;return i}var w0=w(()=>{"use strict";s(Ay,"parseIngestResponse");s(Ry,"describeSliceVerdict");s(Yu,"ingestBody")});import{isAbsolute as v0,relative as vq,resolve as S0,sep as x0}from"node:path";function E0(e){return e>Zu[1]?"above_272k":e>Zu[0]?"band_200k_272k":"standard"}function T0(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Xu(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Fi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=s(a=>{if(!Array.isArray(a))return[];let l=[];for(let c of a){if(!c||typeof c!="object")continue;let u=c,d=Xu(u.from);typeof u.object_id!="string"||!Cy.test(u.object_id)||d===null||l.push({object_id:u.object_id.toLowerCase(),from:d,to:Xu(u.to)})}return l},"windows"),o=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let l=a,c=Xu(l.from);typeof l.path_prefix!="string"||c===null||o.push({path_prefix:l.path_prefix,from:c,to:Xu(l.to)})}let i=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let l=a;typeof l.object_id!="string"||!Cy.test(l.object_id)||typeof l.path_prefix=="string"&&i.push({object_id:l.object_id.toLowerCase(),path_prefix:l.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Cy.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:o,anchors:i}}function Qu(e,t){if(!v0(e))return null;let n=vq(S0(t),S0(e));return!n||n==="."||n.startsWith("..")||v0(n)?null:x0==="/"?n:n.split(x0).join("/")}function xq(e,t){return t===""||e===t||e.startsWith(t+"/")}function Oy(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function A0(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Ny(e,t){for(let n of A0(t))if(xq(e,n.path_prefix))return n.object_id;return null}function Eq(e,t){for(let n of A0(t))if(Oy(e,n.path_prefix))return n.object_id;return null}function Iy(e,t){return e>=t.from&&(t.to===null||e<t.to)}function R0(e,t,n,r){let o=e.ts,i=r?.anchors??[],a=t.map(l=>Ny(l,i)).filter(l=>l!==null);if(r&&o>0){let l=r.leases.filter(d=>Iy(o,d));if(l.length)return l.sort((d,p)=>p.from-d.from||d.object_id.localeCompare(p.object_id)),{object_id:l[0].object_id,source:"lease"};let c=r.bindings.filter(d=>Iy(o,d));if(c.length)return{object_id:(c.find(p=>a.includes(p.object_id))??c.find(p=>n!==null&&p.object_id===n.object_id)??[...c].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Iy(o,d));if(u.length){let d=t[0]??n?.rel??null,p=(d===null?u:u.filter(f=>Oy(f.path_prefix,d))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=Eq(f.path_prefix,i);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function Dy(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?_=>Qu(_,o):null),a=s(_=>{if(!i)return[];let b=[];for(let k of _.edited_paths){let v=i(k);v!==null&&!b.includes(v)&&b.push(v)}return b},"relOf"),l=s(_=>{for(let b of _){let k=Ny(b,r);if(k)return{object_id:k,rel:b}}return null},"firstAnchoredEdit"),c=new Map;for(let _ of e){let b=c.get(_.stream)??[];b.push(_),c.set(_.stream,b)}let u=[...c.entries()].sort(([_],[b])=>_===xo?-1:b===xo?1:0),d=[],p=s(_=>{let b=null;for(let k of d){if(k.ts>_&&_>0)break;b=k.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of u){let k=b.map((S,x)=>({t:S,i:x,rels:a(S)})).sort((S,x)=>S.t.ts-x.t.ts||S.i-x.i),v=null;for(let S of k){let x=l(S.rels);if(x){v=x;break}}!v&&_!==xo&&k.length&&(v=p(k[0].t.ts));for(let S of k){let x=l(S.rels);x&&(v=x),_===xo&&d.push({ts:S.t.ts,seg:v});let T=S.t;if(T.input_tokens+T.output_tokens+T.cache_read_tokens+T.cache_creation_tokens===0)continue;let L=R0(T,S.rels,v,t),R=E0(T.input_tokens+T.cache_read_tokens+T.cache_creation_tokens),P=T0(T.model),D=`${L.object_id??""}|${L.source}|${P}|${R}`,E=f.get(D);E||(E={object_id:L.object_id,attribution_source:L.source,model:P,context_tier:R,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},f.set(D,E)),E.input_tokens+=T.input_tokens,E.output_tokens+=T.output_tokens,E.cache_read_tokens+=T.cache_read_tokens,E.cache_creation_tokens+=T.cache_creation_tokens,E.cache_creation_1h_tokens+=T.cache_creation_1h_tokens,E.turns+=1,T.ts>0&&((E.firstMs===0||T.ts<E.firstMs)&&(E.firstMs=T.ts),T.ts>E.lastMs&&(E.lastMs=T.ts))}}let m=n.nowMs??Date.now(),h=[];for(let _ of f.values()){let{firstMs:b,lastMs:k,...v}=_;v.first_ts=new Date(b>0?b:m).toISOString(),v.last_ts=new Date(k>0?k:m).toISOString(),h.push(v)}let g={lease:0,binding:1,claim:2,path:3,none:4};return h.sort((_,b)=>g[_.attribution_source]-g[b.attribution_source]||(_.object_id??"").localeCompare(b.object_id??"")||_.model.localeCompare(b.model)||_.context_tier.localeCompare(b.context_tier)),h}var Zu,Sq,Cy,Py=w(()=>{"use strict";zu();Zu=[2e5,272e3];s(E0,"contextTierOf");s(T0,"normalizeModelId");Sq=Zu[0],Cy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Xu,"msOf");s(Fi,"parseCostContext");s(Qu,"toRepoRelative");s(xq,"underPrefix");s(Oy,"prefixesOverlap");s(A0,"sortedAnchors");s(Ny,"anchorFor");s(Eq,"bestAnchorOverlapping");s(Iy,"inWindow");s(R0,"assignTurn");s(Dy,"sliceSession")});import{mkdirSync as Tq,readFileSync as Aq,renameSync as Rq,writeFileSync as Cq}from"node:fs";import{dirname as Iq,isAbsolute as ed,sep as My}from"node:path";function Oq(e){let t=e.split(My).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function Nq(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function td(e){let t=new Map,n=s(d=>{let p=t.get(d);if(p!==void 0)return p;let f=e.keyOfRoot(d);return t.set(d,f),f},"keyOf"),r=new Map,o=s(d=>{let p=r.get(d);if(p!==void 0)return p;let f=e.gitRoot(d);return r.set(d,f),f},"gitRoot"),i=new Map,a=[...(e.known??new Map).entries()].filter(([d])=>ed(d)).sort((d,p)=>p[0].length-d[0].length),l=new Map,c=s(d=>{if(!e.isDir)return null;let p=l.get(d);if(p!==void 0)return p;let f=u(d);return l.set(d,f),f},"byConvention"),u=s(d=>{if(!e.isDir)return null;let p=d.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let h=p.slice(0,f-1).join("/")||"/",g=p[f-1];for(let _=g.lastIndexOf("-");_>0;_=g.lastIndexOf("-",_-1)){let b=`${h==="/"?"":h}/${g.slice(0,_)}`;if(e.isDir(b)&&o(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(d){if(!ed(d))return null;let p=d.split(My).join("/"),f=Oq(p),m=o(f);if(m){let h=n(m);return i.set(m,h),{root:m,key:h}}for(let[h,g]of a)if(!(!Nq(p,h)||p===h)&&!(e.isDir&&e.isDir(h)))return{root:h,key:g};return c(f)},seenLive(){return[...i.entries()].map(([d,p])=>({root:d,key:p}))}}}function nd(e,t){let n=new Map;for(let a of e){let l=new Map;for(let c of a.edited_paths){let u=t.of(c);!u||!u.key||l.set(u.key,Math.max(l.get(u.key)??0,u.root.length))}for(let[c,u]of l){let d=n.get(c)??{turns:0,depth:0};d.turns+=1,d.depth=Math.max(d.depth,u),n.set(c,d)}}let r=null,o=0,i=0;for(let[a,l]of n)(l.turns>o||l.turns===o&&(l.depth>i||l.depth===i&&r!==null&&a<r))&&(r=a,o=l.turns,i=l.depth);return r}function rd(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:Qu(n.split(My).join("/"),r.root)}}function O0(e){try{let t=JSON.parse(Aq(e,"utf8"));if(t&&t.v===1&&t.checkouts&&typeof t.checkouts=="object")return{v:1,checkouts:t.checkouts}}catch{}return{v:1,checkouts:{}}}function $a(e){let t=new Map,n=O0(e);for(let[r,o]of Object.entries(n.checkouts)){if(!ed(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&I0.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}function La(e,t,n=Date.now()){try{let r=O0(e),o=new Date(n).toISOString(),i=!1;for(let l of t){if(!ed(l.root))continue;let c=l.key&&I0.test(l.key)?l.key:null,u=r.checkouts[l.root],d=Date.parse(u?.seen_at??"");(!u||u.project_key!==c||!Number.isFinite(d)||n-d>Dq)&&(r.checkouts[l.root]={project_key:c,seen_at:o},i=!0)}for(let[l,c]of Object.entries(r.checkouts)){let u=Date.parse(c?.seen_at??"");(!Number.isFinite(u)||n-u>C0)&&(delete r.checkouts[l],i=!0)}if(!i)return;Tq(Iq(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;Cq(a,JSON.stringify(r),{mode:384}),Rq(a,e)}catch{}}var C0,Dq,I0,N0=w(()=>{"use strict";Py();s(Oq,"dirOf");s(Nq,"within");s(td,"createCheckoutResolver");s(nd,"dominantProjectKey");s(rd,"relativizerFor");C0=90*24*60*60*1e3,Dq=60*60*1e3,I0=/^[a-f0-9]{64}$/;s(O0,"readMemory");s($a,"loadCheckoutMemory");s(La,"rememberCheckouts")});import{createReadStream as Pq,existsSync as Mq}from"node:fs";import{createInterface as $q}from"node:readline";import{homedir as Lq}from"node:os";import{isAbsolute as Ffe,join as jq}from"node:path";function D0(e){let t=$y(e.cached_input_tokens),n=$y(e.input_tokens);return{input_tokens:Math.max(0,n-t),cache_read_tokens:t,output_tokens:$y(e.output_tokens),cache_creation_tokens:0,cache_creation_1h_tokens:0}}function Hq(e){if(typeof e!="string"||e.length===0)return[];let t=[];Ly.lastIndex=0;for(let n=Ly.exec(e);n!==null;n=Ly.exec(e)){let r=n[1]?.trim();r&&!t.includes(r)&&t.push(r)}return t}async function ja(e){if(!e||!Mq(e))return{turns:[],skipped:0};let t=[],n=0,r=null,o=null,i=[];return await new Promise(a=>{let l=$q({input:Pq(e,{encoding:"utf-8"})});l.on("line",u=>{let d=u.trim();if(!d)return;let p;try{p=JSON.parse(d)}catch{return}let f=p.payload??{};if(p.type==="session_meta"||p.type==="turn_context"){typeof f.cwd=="string"&&f.cwd&&(o=f.cwd),typeof f.model=="string"&&f.model&&(r=f.model);return}if(f.name==="apply_patch"){for(let _ of Hq(f.input))i.includes(_)||i.push(_);return}if(f.type!=="token_count")return;let m=f.info?.last_token_usage;if(!m){n++;return}let h=D0(m);if(h.input_tokens+h.output_tokens+h.cache_read_tokens===0){n++;return}let g=p.timestamp?Date.parse(p.timestamp):Number.NaN;t.push({ts:Number.isFinite(g)?g:0,model:r??"<unknown>",synthetic:!1,...h,sidechain:!1,stream:"main",edited_paths:i,cwd:o}),i=[]});let c=s(()=>a({turns:t,skipped:n}),"done");l.on("close",c),l.on("error",c)})}var Fq,$y,Ly,jy=w(()=>{"use strict";Fq=jq(Lq(),".codex","sessions"),$y=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,"num");s(D0,"mapCodexUsage");Ly=/^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm;s(Hq,"codexEditedPaths");s(ja,"collectCodexTurns")});function M0(e){let t={user_turns:0,assistant_turns:0,tool_calls:0,session_id:null,lines_seen:e.length,maind_tool_calls:{},coordination_ids:[]};for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=r.payload??{},i=typeof o.type=="string"?o.type:"";if(r.type==="session_meta"&&!t.session_id){let a=typeof o.session_id=="string"&&o.session_id?o.session_id:o.id;typeof a=="string"&&a&&(t.session_id=a)}r.type==="event_msg"&&(i==="user_message"?t.user_turns++:i==="agent_message"?t.assistant_turns++:i==="mcp_tool_call_end"&&Kq(t,o.invocation)),r.type==="response_item"&&Gq.has(i)&&t.tool_calls++}return t}function Kq(e,t){if(!t||typeof t!="object")return;let n=t;if(n.server!==Bq||typeof n.tool!="string"||!n.tool)return;e.maind_tool_calls[n.tool]=(e.maind_tool_calls[n.tool]??0)+1;let r=n.arguments;if(!r||typeof r!="object")return;let o=r.session_id;if(typeof o!="string"||!Uq.test(o.trim()))return;let i=o.trim().toLowerCase();e.coordination_ids.includes(i)||e.coordination_ids.push(i)}async function Fy(e,t={}){let n=t.turns??(await ja(e)).turns,r=[],{readFile:o}=await import("node:fs/promises"),i;try{i=await o(e,"utf-8")}catch{return null}for(let u of i.split(`
854
+ `)}function _q(e,t){let n=s(c=>new Set(c.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),o=n(t);if(r.size<3||o.size<3)return!1;let[i,a]=r.size<=o.size?[r,o]:[o,r],l=0;for(let c of i)a.has(c)&&l++;return l/i.size>=.8}function bq(e,t,n){return uq.test(e)?{polarity:-1,magnitude:ji.rework,kind:"rework"}:n&&dq.test(e)?{polarity:-1,magnitude:ji.correction,kind:"correction"}:pq.test(e)?{polarity:1,magnitude:ji.acceptance,kind:"acceptance"}:t!==null&&_q(t,e)?{polarity:-1,magnitude:ji.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function kq(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:b0,behaviour_measured:!0}}async function wq(e,t){for(let n of qu(e))await new Promise(r=>{let o=_0({input:y0(n,{encoding:"utf-8"})});o.on("line",i=>{let a=i.trim();if(!a)return;let l;try{l=JSON.parse(a)}catch{return}if(l.message?.role==="assistant")for(let c of Ju(l.message?.content)){if(c.type!=="tool_use"||typeof c.name!="string")continue;let u=$i(c.name);u!==null&&(t.maind_tool_calls??={},t.maind_tool_calls[u]=(t.maind_tool_calls[u]??0)+1)}}),o.on("error",()=>r()),o.on("close",()=>r())})}async function Ty(e,t={}){let n=kq("");if(!e||!cq(e))return n;let r=t.turns??(await Ma(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let o=[],i=new Map,a=null,l=!1,c=null;await new Promise(m=>{let h=y0(e,{encoding:"utf-8"}),g=_0({input:h}),_=s(b=>{let k=b.trim();if(!k)return;let v;try{v=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let D=v.sessionId??v.session_id;typeof D=="string"&&D&&(n.session_id=D)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let S=v.message?.role,x=v.isSidechain===!0;if(S==="assistant")for(let D of Ju(v.message?.content)){if(D.type!=="tool_use"||typeof D.name!="string")continue;let E=$i(D.name);E!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[E]=(n.maind_tool_calls[E]??0)+1)}if(x)return;if(S==="assistant"){let D=Ju(v.message?.content),E=!1;for(let F of D)F.type==="tool_use"&&(n.tool_calls++,E=!0,F.name==="AskUserQuestion"&&n.agent_questions++);l=E;return}if(S!=="user")return;let T=Ju(v.message?.content),A=yq(T);if(A.includes(fq)){n.interrupts++,o.push({polarity:-1,magnitude:ji.interrupt,kind:"interrupt"});return}if(T.some(D=>D.type==="tool_result"&&D.is_error===!0&&typeof D.content=="string"&&D.content.includes(mq))){n.tool_denials++,o.push({polarity:-1,magnitude:ji.denial,kind:"denial"});return}if(T.some(D=>D.type==="tool_result")||!A.trim())return;n.user_turns++,n.user_chars+=A.length;let R=Pa(A);R&&(a=R);let P=bq(A,c,l);c=A,P.kind==="correction"?n.corrections++:P.kind==="rework"?n.reworks++:P.kind==="repeat"?n.repeated_instructions++:P.kind==="acceptance"&&n.acceptances++,P.polarity!==0&&o.push(P),l=!1},"processLine");g.on("line",b=>{try{_(b)}catch{}}),g.on("close",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),await wq(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||gq(i,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...i.values()].sort((m,h)=>m.first_ts-h.first_ts||m.model.localeCompare(h.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,p=0,f=[];return o.forEach((m,h)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,d=d*hq+m.polarity*m.magnitude;let g=Number(d.toFixed(3));f.push({t:h,value:g,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=g,h>0&&o[h-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var b0,uq,dq,pq,fq,mq,hq,ji,k0=w(()=>{"use strict";Wu();Vu();zu();b0="2026-10-01",uq=/(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i,dq=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,pq=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,fq="[Request interrupted by user",mq="The user doesn't want to proceed with this tool use",hq=.7,ji={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(gq,"bumpModel");s(Ju,"asBlocks");s(yq,"textOf");s(_q,"isRepeat");s(bq,"classifyGenuine");s(kq,"emptyAnalysis");s(wq,"tallySubagentMaindCalls");s(Ty,"analyzeSession")});function Ay(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function Ry(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Yu(e,t,n,r="unknown",o){let i={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...o?{cost_slices:o.slices,cost_context_ok:o.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...l}=n;i.session_span={...t,...l}}else i.session_span=t;return i}var w0=w(()=>{"use strict";s(Ay,"parseIngestResponse");s(Ry,"describeSliceVerdict");s(Yu,"ingestBody")});import{isAbsolute as v0,relative as vq,resolve as S0,sep as x0}from"node:path";function E0(e){return e>Zu[1]?"above_272k":e>Zu[0]?"band_200k_272k":"standard"}function T0(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Xu(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Fi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=s(a=>{if(!Array.isArray(a))return[];let l=[];for(let c of a){if(!c||typeof c!="object")continue;let u=c,d=Xu(u.from);typeof u.object_id!="string"||!Cy.test(u.object_id)||d===null||l.push({object_id:u.object_id.toLowerCase(),from:d,to:Xu(u.to)})}return l},"windows"),o=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let l=a,c=Xu(l.from);typeof l.path_prefix!="string"||c===null||o.push({path_prefix:l.path_prefix,from:c,to:Xu(l.to)})}let i=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let l=a;typeof l.object_id!="string"||!Cy.test(l.object_id)||typeof l.path_prefix=="string"&&i.push({object_id:l.object_id.toLowerCase(),path_prefix:l.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Cy.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:o,anchors:i}}function Qu(e,t){if(!v0(e))return null;let n=vq(S0(t),S0(e));return!n||n==="."||n.startsWith("..")||v0(n)?null:x0==="/"?n:n.split(x0).join("/")}function xq(e,t){return t===""||e===t||e.startsWith(t+"/")}function Oy(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function A0(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Ny(e,t){for(let n of A0(t))if(xq(e,n.path_prefix))return n.object_id;return null}function Eq(e,t){for(let n of A0(t))if(Oy(e,n.path_prefix))return n.object_id;return null}function Iy(e,t){return e>=t.from&&(t.to===null||e<t.to)}function R0(e,t,n,r){let o=e.ts,i=r?.anchors??[],a=t.map(l=>Ny(l,i)).filter(l=>l!==null);if(r&&o>0){let l=r.leases.filter(d=>Iy(o,d));if(l.length)return l.sort((d,p)=>p.from-d.from||d.object_id.localeCompare(p.object_id)),{object_id:l[0].object_id,source:"lease"};let c=r.bindings.filter(d=>Iy(o,d));if(c.length)return{object_id:(c.find(p=>a.includes(p.object_id))??c.find(p=>n!==null&&p.object_id===n.object_id)??[...c].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Iy(o,d));if(u.length){let d=t[0]??n?.rel??null,p=(d===null?u:u.filter(f=>Oy(f.path_prefix,d))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=Eq(f.path_prefix,i);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function Dy(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?_=>Qu(_,o):null),a=s(_=>{if(!i)return[];let b=[];for(let k of _.edited_paths){let v=i(k);v!==null&&!b.includes(v)&&b.push(v)}return b},"relOf"),l=s(_=>{for(let b of _){let k=Ny(b,r);if(k)return{object_id:k,rel:b}}return null},"firstAnchoredEdit"),c=new Map;for(let _ of e){let b=c.get(_.stream)??[];b.push(_),c.set(_.stream,b)}let u=[...c.entries()].sort(([_],[b])=>_===xo?-1:b===xo?1:0),d=[],p=s(_=>{let b=null;for(let k of d){if(k.ts>_&&_>0)break;b=k.seg}return b},"mainSegmentAt"),f=new Map;for(let[_,b]of u){let k=b.map((S,x)=>({t:S,i:x,rels:a(S)})).sort((S,x)=>S.t.ts-x.t.ts||S.i-x.i),v=null;for(let S of k){let x=l(S.rels);if(x){v=x;break}}!v&&_!==xo&&k.length&&(v=p(k[0].t.ts));for(let S of k){let x=l(S.rels);x&&(v=x),_===xo&&d.push({ts:S.t.ts,seg:v});let T=S.t;if(T.input_tokens+T.output_tokens+T.cache_read_tokens+T.cache_creation_tokens===0)continue;let L=R0(T,S.rels,v,t),R=E0(T.input_tokens+T.cache_read_tokens+T.cache_creation_tokens),P=T0(T.model),D=`${L.object_id??""}|${L.source}|${P}|${R}`,E=f.get(D);E||(E={object_id:L.object_id,attribution_source:L.source,model:P,context_tier:R,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},f.set(D,E)),E.input_tokens+=T.input_tokens,E.output_tokens+=T.output_tokens,E.cache_read_tokens+=T.cache_read_tokens,E.cache_creation_tokens+=T.cache_creation_tokens,E.cache_creation_1h_tokens+=T.cache_creation_1h_tokens,E.turns+=1,T.ts>0&&((E.firstMs===0||T.ts<E.firstMs)&&(E.firstMs=T.ts),T.ts>E.lastMs&&(E.lastMs=T.ts))}}let m=n.nowMs??Date.now(),h=[];for(let _ of f.values()){let{firstMs:b,lastMs:k,...v}=_;v.first_ts=new Date(b>0?b:m).toISOString(),v.last_ts=new Date(k>0?k:m).toISOString(),h.push(v)}let g={lease:0,binding:1,claim:2,path:3,none:4};return h.sort((_,b)=>g[_.attribution_source]-g[b.attribution_source]||(_.object_id??"").localeCompare(b.object_id??"")||_.model.localeCompare(b.model)||_.context_tier.localeCompare(b.context_tier)),h}var Zu,Sq,Cy,Py=w(()=>{"use strict";zu();Zu=[2e5,272e3];s(E0,"contextTierOf");s(T0,"normalizeModelId");Sq=Zu[0],Cy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Xu,"msOf");s(Fi,"parseCostContext");s(Qu,"toRepoRelative");s(xq,"underPrefix");s(Oy,"prefixesOverlap");s(A0,"sortedAnchors");s(Ny,"anchorFor");s(Eq,"bestAnchorOverlapping");s(Iy,"inWindow");s(R0,"assignTurn");s(Dy,"sliceSession")});import{mkdirSync as Tq,readFileSync as Aq,renameSync as Rq,writeFileSync as Cq}from"node:fs";import{dirname as Iq,isAbsolute as ed,sep as My}from"node:path";function Oq(e){let t=e.split(My).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function Nq(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function td(e){let t=new Map,n=s(d=>{let p=t.get(d);if(p!==void 0)return p;let f=e.keyOfRoot(d);return t.set(d,f),f},"keyOf"),r=new Map,o=s(d=>{let p=r.get(d);if(p!==void 0)return p;let f=e.gitRoot(d);return r.set(d,f),f},"gitRoot"),i=new Map,a=[...(e.known??new Map).entries()].filter(([d])=>ed(d)).sort((d,p)=>p[0].length-d[0].length),l=new Map,c=s(d=>{if(!e.isDir)return null;let p=l.get(d);if(p!==void 0)return p;let f=u(d);return l.set(d,f),f},"byConvention"),u=s(d=>{if(!e.isDir)return null;let p=d.split("/");for(let f=2;f<p.length+1;f++){let m=p.slice(0,f).join("/");if(!m||e.isDir(m))continue;let h=p.slice(0,f-1).join("/")||"/",g=p[f-1];for(let _=g.lastIndexOf("-");_>0;_=g.lastIndexOf("-",_-1)){let b=`${h==="/"?"":h}/${g.slice(0,_)}`;if(e.isDir(b)&&o(b)===b)return{root:m,key:n(b)}}return null}return null},"conventionRoot");return{of(d){if(!ed(d))return null;let p=d.split(My).join("/"),f=Oq(p),m=o(f);if(m){let h=n(m);return i.set(m,h),{root:m,key:h}}for(let[h,g]of a)if(!(!Nq(p,h)||p===h)&&!(e.isDir&&e.isDir(h)))return{root:h,key:g};return c(f)},seenLive(){return[...i.entries()].map(([d,p])=>({root:d,key:p}))}}}function nd(e,t){let n=new Map;for(let a of e){let l=new Map;for(let c of a.edited_paths){let u=t.of(c);!u||!u.key||l.set(u.key,Math.max(l.get(u.key)??0,u.root.length))}for(let[c,u]of l){let d=n.get(c)??{turns:0,depth:0};d.turns+=1,d.depth=Math.max(d.depth,u),n.set(c,d)}}let r=null,o=0,i=0;for(let[a,l]of n)(l.turns>o||l.turns===o&&(l.depth>i||l.depth===i&&r!==null&&a<r))&&(r=a,o=l.turns,i=l.depth);return r}function rd(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:Qu(n.split(My).join("/"),r.root)}}function O0(e){try{let t=JSON.parse(Aq(e,"utf8"));if(t&&t.v===1&&t.checkouts&&typeof t.checkouts=="object")return{v:1,checkouts:t.checkouts}}catch{}return{v:1,checkouts:{}}}function $a(e){let t=new Map,n=O0(e);for(let[r,o]of Object.entries(n.checkouts)){if(!ed(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&I0.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}function La(e,t,n=Date.now()){try{let r=O0(e),o=new Date(n).toISOString(),i=!1;for(let l of t){if(!ed(l.root))continue;let c=l.key&&I0.test(l.key)?l.key:null,u=r.checkouts[l.root],d=Date.parse(u?.seen_at??"");(!u||u.project_key!==c||!Number.isFinite(d)||n-d>Dq)&&(r.checkouts[l.root]={project_key:c,seen_at:o},i=!0)}for(let[l,c]of Object.entries(r.checkouts)){let u=Date.parse(c?.seen_at??"");(!Number.isFinite(u)||n-u>C0)&&(delete r.checkouts[l],i=!0)}if(!i)return;Tq(Iq(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;Cq(a,JSON.stringify(r),{mode:384}),Rq(a,e)}catch{}}var C0,Dq,I0,N0=w(()=>{"use strict";Py();s(Oq,"dirOf");s(Nq,"within");s(td,"createCheckoutResolver");s(nd,"dominantProjectKey");s(rd,"relativizerFor");C0=90*24*60*60*1e3,Dq=60*60*1e3,I0=/^[a-f0-9]{64}$/;s(O0,"readMemory");s($a,"loadCheckoutMemory");s(La,"rememberCheckouts")});import{createReadStream as Pq,existsSync as Mq}from"node:fs";import{createInterface as $q}from"node:readline";import{homedir as Lq}from"node:os";import{isAbsolute as Bfe,join as jq}from"node:path";function D0(e){let t=$y(e.cached_input_tokens),n=$y(e.input_tokens);return{input_tokens:Math.max(0,n-t),cache_read_tokens:t,output_tokens:$y(e.output_tokens),cache_creation_tokens:0,cache_creation_1h_tokens:0}}function Hq(e){if(typeof e!="string"||e.length===0)return[];let t=[];Ly.lastIndex=0;for(let n=Ly.exec(e);n!==null;n=Ly.exec(e)){let r=n[1]?.trim();r&&!t.includes(r)&&t.push(r)}return t}async function ja(e){if(!e||!Mq(e))return{turns:[],skipped:0};let t=[],n=0,r=null,o=null,i=[];return await new Promise(a=>{let l=$q({input:Pq(e,{encoding:"utf-8"})});l.on("line",u=>{let d=u.trim();if(!d)return;let p;try{p=JSON.parse(d)}catch{return}let f=p.payload??{};if(p.type==="session_meta"||p.type==="turn_context"){typeof f.cwd=="string"&&f.cwd&&(o=f.cwd),typeof f.model=="string"&&f.model&&(r=f.model);return}if(f.name==="apply_patch"){for(let _ of Hq(f.input))i.includes(_)||i.push(_);return}if(f.type!=="token_count")return;let m=f.info?.last_token_usage;if(!m){n++;return}let h=D0(m);if(h.input_tokens+h.output_tokens+h.cache_read_tokens===0){n++;return}let g=p.timestamp?Date.parse(p.timestamp):Number.NaN;t.push({ts:Number.isFinite(g)?g:0,model:r??"<unknown>",synthetic:!1,...h,sidechain:!1,stream:"main",edited_paths:i,cwd:o}),i=[]});let c=s(()=>a({turns:t,skipped:n}),"done");l.on("close",c),l.on("error",c)})}var Fq,$y,Ly,jy=w(()=>{"use strict";Fq=jq(Lq(),".codex","sessions"),$y=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,"num");s(D0,"mapCodexUsage");Ly=/^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm;s(Hq,"codexEditedPaths");s(ja,"collectCodexTurns")});function M0(e){let t={user_turns:0,assistant_turns:0,tool_calls:0,session_id:null,lines_seen:e.length,maind_tool_calls:{},coordination_ids:[]};for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=r.payload??{},i=typeof o.type=="string"?o.type:"";if(r.type==="session_meta"&&!t.session_id){let a=typeof o.session_id=="string"&&o.session_id?o.session_id:o.id;typeof a=="string"&&a&&(t.session_id=a)}r.type==="event_msg"&&(i==="user_message"?t.user_turns++:i==="agent_message"?t.assistant_turns++:i==="mcp_tool_call_end"&&Kq(t,o.invocation)),r.type==="response_item"&&Gq.has(i)&&t.tool_calls++}return t}function Kq(e,t){if(!t||typeof t!="object")return;let n=t;if(n.server!==Bq||typeof n.tool!="string"||!n.tool)return;e.maind_tool_calls[n.tool]=(e.maind_tool_calls[n.tool]??0)+1;let r=n.arguments;if(!r||typeof r!="object")return;let o=r.session_id;if(typeof o!="string"||!Uq.test(o.trim()))return;let i=o.trim().toLowerCase();e.coordination_ids.includes(i)||e.coordination_ids.push(i)}async function Fy(e,t={}){let n=t.turns??(await ja(e)).turns,r=[],{readFile:o}=await import("node:fs/promises"),i;try{i=await o(e,"utf-8")}catch{return null}for(let u of i.split(`
855
855
  `)){let d=u.trim();if(d)try{r.push(JSON.parse(d))}catch{}}let a=M0(r);if(!a.session_id)return null;let l=s(u=>n.reduce((d,p)=>d+(typeof p[u]=="number"?p[u]:0),0),"sum"),c=new Map;for(let u of n){let d=c.get(u.model)??{first:u.ts,last:u.ts,turns:0,output_tokens:0};d.first=Math.min(d.first||u.ts,u.ts||d.first),d.last=Math.max(d.last,u.ts),d.turns++,d.output_tokens+=u.output_tokens,c.set(u.model,d)}return{session_id:a.session_id,user_turns:a.user_turns,assistant_turns:a.assistant_turns,tool_calls:a.tool_calls,agent_questions:0,input_tokens:l("input_tokens"),output_tokens:l("output_tokens"),cache_read_tokens:l("cache_read_tokens"),cache_creation_tokens:l("cache_creation_tokens"),user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,momentum_series:[],effort_at_end:null,lines_seen:a.lines_seen,model_mix:[...c.entries()].map(([u,d])=>({model:u,sidechain:!1,turns:d.turns,output_tokens:d.output_tokens,first_ts:d.first,last_ts:d.last})),ai_title:null,session_slug:null,analyzer_version:P0,maind_tool_calls:a.maind_tool_calls,maind_connected:Object.keys(a.maind_tool_calls).length>0?"connected":"unknown",client:"codex",coordination_ids:a.coordination_ids}}var P0,Uq,Bq,Gq,$0=w(()=>{"use strict";jy();P0="2026-10-11",Uq=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bq="maind",Gq=new Set(["function_call","custom_tool_call","web_search_call"]);s(M0,"countCodexRecords");s(Kq,"countMaindCall");s(Fy,"analyzeCodexSession")});var Hy=w(()=>{"use strict"});var L0=w(()=>{"use strict";Hy()});import{createReadStream as zq,existsSync as Jq}from"node:fs";import{createInterface as Yq}from"node:readline";function j0(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function Qq(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
856
856
  `)}function U0(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function ez(e){let t=e.message?.role;if(t==="assistant")return{holder:j0(e.message?.content).some(l=>l.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=j0(e.message?.content),r=Qq(n);return r.includes(Xq)?{holder:"human",genuine:!1}:n.some(i=>i.type==="tool_result"&&i.is_error===!0&&typeof i.content=="string"&&i.content.includes(Zq))?{holder:"agent",genuine:!1}:n.some(i=>i.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Uy(e){let t=U0("");if(!e||!Jq(e))return t;let n=null,r=0,o=0,i=null,a="human",l=[];return await new Promise(c=>{let u=zq(e,{encoding:"utf-8"}),d=Yq({input:u}),p=s(f=>{let m=f.trim();if(!m)return;let h;try{h=JSON.parse(m)}catch{return}if(!t.session_id){let b=h.sessionId??h.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(h.isSidechain===!0)return;let g=typeof h.timestamp=="string"?Date.parse(h.timestamp):NaN;if(!Number.isFinite(g)||i!==null&&g<i)return;let _=ez(h);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=g),r=g,i!==null){let b=g-i;a==="agent"?o+=b:b>=F0*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),l.length<H0&&l.push({offset_seconds:Math.round((i-n)/1e3),duration_seconds:Math.round(b/1e3)}))}i=g,a=_.holder}},"processLine");d.on("line",f=>{try{p(f)}catch{}}),d.on("close",()=>c()),d.on("error",()=>c()),u.on("error",()=>c())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(o/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=l,t.pauses_truncated=t.pause_count>l.length),t}var Xq,Zq,F0,H0,B0=w(()=>{"use strict";Xq="[Request interrupted by user",Zq="The user doesn't want to proceed with this tool use",F0=60,H0=200;s(j0,"asBlocks");s(Qq,"textOf");s(U0,"emptySpan");s(ez,"classify");s(Uy,"analyzeSpan")});import{createReadStream as tz,existsSync as nz}from"node:fs";import{createInterface as rz}from"node:readline";function iz(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function od(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function sz(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
857
857
  `)}return""}async function By(e,t={}){if(!e||!nz(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:vy(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),o=t.initialEffort??null,i=t.initialModes?{...t.initialModes}:vy(),a=t.start??0;return await new Promise(l=>{let c=tz(e,{encoding:"utf-8",start:t.start??0}),u=rz({input:c});u.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{return}let h=m.sessionId??m.session_id??"",g=m.timestamp?Date.parse(m.timestamp):Date.now(),_=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:h,ts:g,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=oz[m.attachment.type];b&&(i[iz(b.mode)]=b.active,n.push({kind:"mode",session_id:h,ts:g,mode:b.mode,active:b.active}));return}if(_==="user"){let b=sz(m.message?.content),k=Pa(b);k&&(o=k);let v={session_id:h,ts:g,text:b,effort_directive:k};n.push({kind:"user",...v});return}if(_==="assistant"){let b=m.message?.usage,k=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,v=typeof m.requestId=="string"&&m.requestId?m.requestId:null,S=k??v,x=S!==null&&r.has(S);S!==null&&!x&&r.add(S);let T={session_id:h,ts:g,model:m.message?.model??null,input_tokens:x?0:od(b?.input_tokens),output_tokens:x?0:od(b?.output_tokens),cache_read_input_tokens:x?0:od(b?.cache_read_input_tokens),cache_creation_input_tokens:x?0:od(b?.cache_creation_input_tokens),effort:o,isSidechain:m.isSidechain===!0,...i.ultracode?{ultracode:!0}:{},...i.planMode?{planMode:!0}:{},...i.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...T})}});let d=s(()=>({events:n,bytesRead:a,effortAtEnd:o,modesAtEnd:{...i},seenMessagesAtEnd:new Set(r)}),"finalResult");u.on("close",()=>l(d())),u.on("error",()=>l(d())),c.on("error",()=>l(d()))})}var oz,G0=w(()=>{"use strict";Wu();Sy();oz={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};s(iz,"modeFlagKey");s(od,"num");s(sz,"extractUserText");s(By,"streamTranscript")});var K0=w(()=>{"use strict"});import{homedir as az}from"node:os";import{join as lz}from"node:path";function Ky(e){return e.replace(/[/.]/g,"-")}var cz,Gy,W0=w(()=>{"use strict";cz=az(),Gy=lz(cz,".claude","projects");s(Ky,"projectPathFromCwd")});var Eo=w(()=>{"use strict";Sy();c0();u0();k0();Vu();w0();zu();N0();jy();$0();Py();Hy();L0();B0();G0();Wu();K0();W0()});import{mkdir as uz,readFile as dz,writeFile as pz,rename as fz}from"node:fs/promises";import{existsSync as q0}from"node:fs";import{homedir as mz}from"node:os";import{join as z0}from"node:path";function V0(){return{config:null,sessions:{},pending_metrics:[]}}async function ue(){if(!q0(id))return V0();try{let e=await dz(id,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
@@ -907,13 +907,13 @@ ${g}`:g}function tY(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n
907
907
  `).length,sha256:DO(cn)},m4,{lines:57,sha256:"72f5d6423e98eb01b2854b44dff290f2d8be1af1c8995f059dba5118530aafce"},{lines:56,sha256:"bf77aeeed9e96b8d0bfcba1feee0592256e2d49d64b53977bbd8f5b8323e5387"},{lines:21,sha256:"afdaf4a151cfd6fc9258392d86593e0604dae7518ffa8918cfc92bab9d5fd41b"}]);s(g4,"dedupe");s(Z_,"splitLines");Cd=s(e=>e.text.trim()==="","isBlank");s(y4,"scanRepoFile");s(_4,"cutBlocks");b4={preamble:"maind preamble",conventions:"conventions block","team-conventions":"team conventions block (install --team)"};s(PO,"planRepoFile");s(No,"hasMigratableBlocks");s(Id,"summarizeRepoBlocks")});import{parse as k4}from"jsonc-parser";function Q_(e,t){let n=e.split(/[.+-]/).slice(0,3).map(o=>Number.parseInt(o,10)||0),r=t.split(/[.+-]/).slice(0,3).map(o=>Number.parseInt(o,10)||0);for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function tb(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=Nt(e.raw);if("value"in a){let d=On(a.value,["mcp_servers","maind"]);if(!ne(d)||typeof d.command!="string")return null;let p=Array.isArray(d.args)?d.args.filter(f=>typeof f=="string"):[];return{command:d.command,args:p}}let l=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!l)return null;let c=/^\s*command\s*=\s*"([^"]*)"/m.exec(l[1]),u=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(l[1]);return c?{command:c[1],args:u?[...u[1].matchAll(/"([^"]*)"/g)].map(d=>d[1]):[]}:null}let t=[],n=k4(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,o=r.servers?.maind??r.mcpServers?.maind,i=o?.transport??o;return!i||typeof i.command!="string"?null:{command:i.command,args:Array.isArray(i.args)?i.args.filter(a=>typeof a=="string"):[]}}function Yi(e,t){let n=`npm i -g ${$n}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Od(e){let t=[],n=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${$n}`),r=[e.runningVersion,...e.nodeTrees.map(g=>g.bridgeVersion).filter(g=>g!==null)],o=e.latestVersion??r.sort(Q_).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=e.nodeTrees.filter(g=>g.bridgeVersion!==null);if(e.nodeTrees.length>0){let g=e.pathWinner?.node??null,_=e.nodeTrees.find(k=>k.node===g);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):_&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${_.node} tree (${_.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let k=e.nodeTrees.find(v=>v.node===e.nvmDefault);k&&k.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${k.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Yi(o,k.node)})}if(new Set(i.map(k=>k.bridgeVersion)).size>1)for(let k of i.filter(v=>Q_(v.bridgeVersion,o)<0))t.push({check:"node-trees",level:"warn",message:`${k.node} carries bridge ${k.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Yi(o,k.node)})}let a=!1,l=new Map,c=s((g,_)=>{let b=l.get(g)??{version:e.installVersionOf(g),clients:[]};b.clients.push(_),l.set(g,b)},"noteInstall");for(let g of e.clientConfigs){let _=tb(g);if(_===null)continue;if(g.present===!1){t.push({check:"client-config",level:"warn",message:`${g.label}: ${g.path} names maind, but the client is not installed \u2014 nothing reads this file (a leftover of an earlier install).`,fix:"maind-mcp-bridge doctor --remove-phantoms"});continue}if(a=!0,/(^|\/)npx(\.cmd)?$/.test(_.command)&&_.args.some(v=>v.includes($n))){t.push({check:"client-config",level:"warn",message:`${g.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${Yi(o)}, then set "command": "maind-mcp-bridge" (no args) in ${g.path}`});continue}let k=/(^|[\\/])node(\.exe)?$/.test(_.command);if(k&&_.args.length>0){let v=_.args[0];if(!e.fileExists(v)){t.push({check:"client-config",level:"error",message:`${g.label} runs ${v}, which does not exist.`,fix:`re-run \`npx -y ${$n}@${o} install\` to rewrite the entry`});continue}c(v,g.label)}else if(_.command.includes("/")||_.command.includes("\\")){if(!e.fileExists(_.command)){t.push({check:"client-config",level:"error",message:`${g.label} points at ${_.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${g.path} (after ${Yi(o)})`});continue}}else if(_.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${g.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:Yi(o,e.nvmDefault)});continue}k||(_.command.includes("/")||_.command.includes("\\")?c(_.command,g.label):_.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,g.label)),t.push({check:"client-config",level:"ok",message:`${g.label}: ${[_.command,..._.args].join(" ")}`})}if(!a&&e.plugin?.enabled!==!0&&t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${$n} install`}),e.latestVersion!==null)for(let[g,_]of l){let b=_.clients.join(", ");if(_.version===null)t.push({check:"version",level:"info",message:`${b}: cannot tell which bridge version ${g} is.`});else if(Q_(_.version,e.latestVersion)<0){let k=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(g)?.[1]??null;t.push({check:"version",level:"warn",message:`${b} run bridge ${_.version} (${g}); published is ${e.latestVersion}. An installed bridge never updates itself. After the update, run \`maind-mcp-bridge install --hooks-only\` for hooks the new version brings (asks consent per hook).`,fix:k?Yi(e.latestVersion,k):`npx -y ${$n}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${b} run bridge ${_.version} (published: ${e.latestVersion}).`})}for(let{dir:g,maind:_}of e.npxStaleDirs)t.push({check:"npx-cache",level:_?"error":"info",message:_?`a half-built better-sqlite3 was left in ${g} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${g} (another tool's npx entry, not maind's).`,fix:`rm -rf '${g.replace(/'/g,"'\\''")}'`});let u=e.envApiKey??e.apiKey;(e.deviceId===null||!MO.test(e.deviceId))&&t.push({check:"credentials",level:"error",message:"no valid device id \u2014 the server binds keys to a device, so every call ends in 401 invalid_or_device_required.",fix:"maind-mcp-bridge --reauth"}),u===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):v4.test(u)?t.push({check:"credentials",level:e.deviceId!==null&&MO.test(e.deviceId)?"ok":"info",message:`key ${u.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=e.connection;d===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):d.outcome==="ok"||d.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):t.push({check:"connection",level:"error",message:d.outcome==="auth_failed"?`the server rejected the last connection (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"});let p=e.plugin?.enabled===!0;if(e.claudeSettings!==null){let g=ct(e.claudeSettings,{fileExists:s(k=>e.fileExists(k),"fileExists")}),_=e.pathWinner?e.installVersionOf(e.pathWinner.path):null,b=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${$n}`);for(let k of g){if(k.status==="missing"){if(p||k.subcommand===ce)continue;let x=(e.declinedHooks??[]).includes(k.subcommand);t.push(x?{check:"hooks",level:"info",message:`${k.event}/${k.subcommand} was declined at install and stays off \u2014 \`install --hooks-only\` asks again.`}:{check:"hooks",level:"warn",message:`${k.detail} Updating the bridge replaces the binary and never adds a hook entry (install is append-only).`,fix:`${b} install --hooks-only (adds what is missing, asks consent per hook)`});continue}if(k.status==="superseded")continue;if(k.status!=="ok"){t.push({check:"hooks",level:k.status==="broken"?"error":"warn",message:k.detail});continue}let v=k.command?/(\S+\/build\/index\.js)/.exec(k.command)?.[1]??null:null,S=v?e.installVersionOf(v):null;S!==null&&_!==null&&S!==_&&t.push({check:"hooks",level:"warn",message:`${k.event}/${k.subcommand} runs bridge ${S}, the MCP server runs ${_} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${k.subcommand}`})}t.some(k=>k.check==="hooks"&&k.level!=="info")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}if(p){let g=(e.declinedHooks??[]).includes(ce),_=e.guardMode??"off",b=g&&e.claudeSettings!==null&&sl(e.claudeSettings,{guardMode:_,fileExists:s(x=>e.fileExists(x),"fileExists")}).channel==="guard";t.push(g?b?{check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${_}): ${ce} was declined at install, and the maind plugin keeps it off too.`}:{check:"session-start",level:"info",message:`no session-start briefing \u2014 ${ce} was declined at install, and the maind plugin keeps it off too, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`}:{check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start from the maind plugin (${ce}).`});let k=e.plugin?.file?` (${e.plugin.file})`:"",v=e.clientConfigs.find(x=>x.key==="claude-code-user");v!==void 0&&Y_(v.raw).length>0&&t.push({check:"claude-plugin",level:"warn",message:`the maind plugin is enabled${k} and brings its own MCP server, and ${v.path} still registers a \`maind\` server \u2014 Claude Code starts both, so every maind tool is listed twice.`,fix:`${n} doctor --remove-duplicate-mcp (lists it; --yes removes exactly that entry \u2014 with Claude Code closed)`});let S=e.claudeSettings===null?[]:ct(e.claudeSettings,{fileExists:s(x=>e.fileExists(x),"fileExists")}).filter(x=>x.status!=="missing"&&x.status!=="broken");S.length>0&&t.push({check:"claude-plugin",level:"info",message:`the maind plugin is enabled${k}, and ~/.claude/settings.json still wires the bridge's own hooks (${S.map(x=>x.subcommand).join(", ")}) \u2014 nothing runs twice (the plugin's copy stands down for them), but these run from settings.json, pinned to that install, instead of updating with the plugin.`,fix:`${n} doctor --remove-duplicate-hooks (lists them; --yes removes exactly those entries from settings.json)`})}if(e.claudeSettings!==null&&!p){let g=e.guardMode??"off",_=sl(e.claudeSettings,{guardMode:g,fileExists:s(S=>e.fileExists(S),"fileExists")}),k=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${$n}`)} install --hooks-only`,v=(e.declinedHooks??[]).includes(ce);_.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${ce} hook).`}):_.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${ce} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):_.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${g}); without the core ${ce} hook it stops when the guard is switched off.`,fix:k}):v?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${ce} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:k}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${ce}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:k})}if(e.claudeSettings!==null){let g=ct(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")},[w4])[0];if(g.status==="superseded"){let _=e.foreignHookHosts??[],b=_.includes("cursor"),k=(e.declinedHooks??[]).includes(Nn),v=e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${$n}`),S=g.remedy==="run-install"?`${v} install --hooks-only`:`replace that command in ~/.claude/settings.json with: ${v} ${Nn}`,x=b?`Cursor, installed here, imports it from ~/.claude/settings.json and takes only JSON at session start \u2014 it gets plain text it cannot parse${_.includes("devin")?"; Devin Local gets text whose handling it does not document":""}`:_.includes("devin")?"Devin Local, installed here, runs it too and documents only JSON context for hooks":"it is fine in Claude Code, but Cursor and Devin Local, which import the same hooks, would get plain text";t.push({check:"hook-hosts",level:b&&!k?"warn":"info",message:`the SessionStart reminder hook still runs \`${g.command}\` \u2014 ${x}. ${Nn} prints the same text in Claude Code and the right form, or nothing, everywhere else.`,fix:S})}}let f=e.repoBlocks??null,m=f?.plans.find(g=>g.keeps.some(_=>_.startsWith("team conventions block")))??null;f!==null&&No(f.plans)&&t.push({check:"repo-blocks",level:"info",message:`${f.root} still carries the maind blocks an earlier install wrote into the repository \u2014 ${Id(f.plans)}. The bridge no longer writes them (ADR-364): hooks and user-level rule files carry the same content. They stay until you remove them.`,fix:`${n} doctor --migrate-repo-blocks (lists them and changes nothing; --yes removes exactly the listed blocks)`}),m!==null&&t.push({check:"repo-blocks",level:"ok",message:`${m.rel} carries the team conventions block (install --team); the bridge keeps it current.`}),f!==null&&f.inRepo&&m===null&&(e.foreignHookHosts??[]).includes("cursor")&&t.push({check:"team-option",level:"info",message:`Cursor is installed here, and its sessionStart hook can drop the briefing in a race Cursor confirms. For teams that work mostly in Cursor, the team option puts the conventions into ${f.root}'s AGENTS.md, which Cursor reads reliably.`,fix:`${n} install --team (writes the AGENTS.md conventions block and the project .mcp.json)`});for(let g of e.channels??[]){let _=g.hooks&&g.hooks.gaps.length>0?` (not available there: ${g.hooks.gaps.join(", ")})`:"";g.state==="ok"&&g.hooks&&g.hooks.missing.length>0?t.push({check:"channels",level:"info",message:`${g.label}: ${g.hooks.wired.length} of ${g.hooks.wired.length+g.hooks.missing.length} wired \u2014 not yet: ${g.hooks.missing.join(", ")}${_}.`,fix:`${n} install --hooks-only (asks consent per hook)`}):g.state==="ok"?t.push({check:"channels",level:"ok",message:`${g.label}: ${g.path}${_}`}):g.state==="foreign"?t.push({check:"channels",level:"info",message:`${g.label}: ${g.path} is not the bridge's (no maind marker) \u2014 left as it is, so ${g.client} gets no conventions from MAIND there.`}):t.push({check:"channels",level:"info",message:`${g.label} is not set up \u2014 ${g.client} sessions get the project conventions only from the MCP instructions${f!==null&&No(f.plans)?" and the repository's old maind blocks":""}.`,fix:`${n} install --hooks-only (asks consent per hook and file)`})}let h=e.context??null;if(h!==null&&e.claudeSettings!==null){let g=ct(e.claudeSettings,{fileExists:s(_=>e.fileExists(_),"fileExists")}).filter(_=>(_.subcommand==="on-prompt-context"||_.subcommand==="on-read-context")&&_.status!=="missing").map(_=>_.subcommand);if(g.length>0){let _=t.length;h.sqlite.ok?h.repoRoot!==null&&!h.indexPresent&&t.push({check:"context",level:"info",message:`${h.repoRoot} has no code index \u2014 on-read-context stays silent there, and on-prompt-context can only match conventions.`,fix:"ask your agent to run codebase_index once (or run `maind index` in the repo); the Stop hook keeps it fresh after that"}):t.push({check:"context",level:"warn",message:`${g.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${h.sqlite.reason}). They stay silent.`,fix:"update Node to >= 22.16 (builtin SQLite), or run `npm rebuild better-sqlite3` in the bridge's install prefix"}),g.includes("on-prompt-context")&&h.repoRoot!==null&&!h.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${h.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===_&&t.push({check:"context",level:"ok",message:`${g.join(" and ")}: code index and cached conventions present${h.repoRoot?` for ${h.repoRoot}`:""}.`})}}return t}function $O(e){let t=e.filter(o=>o.level==="error"&&eb.includes(o.check)).sort((o,i)=>eb.indexOf(o.check)-eb.indexOf(i.check)),n=t[0];if(n===void 0)return S4(e);let r=t.length>1?` ${t.length-1} more finding(s).`:"";return`[maind] setup problem \u2014 ${n.message}`+(n.fix?` Fix: ${n.fix}.`:"")+r+" All findings with fixes: `maind-mcp-bridge doctor` (or `npx -y @maind-dev/mcp-bridge doctor`)."}function S4(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?x4(e):`[maind] setup gap \u2014 ${t.message} Call get_session_briefing now to load them.`+(t.fix?` To add the hook, run in a terminal (append-only, asks consent per hook): ${t.fix}`:"")}function x4(e){let t=e.find(n=>n.check==="hook-hosts"&&n.level==="warn");return t===void 0?E4(e):`[maind] setup gap \u2014 ${t.message}`+(t.fix?` To switch to it, run in a terminal (asks consent, replaces only that entry): ${t.fix}`:"")}function E4(e){let t=e.find(n=>n.check==="claude-plugin"&&n.level==="warn");return t===void 0?null:`[maind] setup note \u2014 ${t.message}`+(t.fix?` To fix, run in a terminal: ${t.fix}`:"")}function LO(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,l)=>n[a.level]-n[l.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),o=e.filter(a=>a.level==="error").length,i=e.filter(a=>a.level==="warn").length;return r.push("",o+i===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${o} error(s), ${i} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
908
908
  `)+`
909
909
  `}var $n,w4,v4,MO,eb,Nd=w(()=>{"use strict";Rd();Ia();Pu();X_();al();Le();$n="@maind-dev/mcp-bridge",w4=$e.find(e=>e.subcommand===Nn),v4=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,MO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Q_,"compareVersions");s(tb,"maindEntry");s(Yi,"installFix");s(Od,"diagnose");eb=["connection","client-config","npx-cache","hooks"];s($O,"sessionStartLine");s(S4,"briefingGapLine");s(x4,"hookHostsGapLine");s(E4,"pluginDuplicateLine");s(LO,"renderFindings")});function nb(e){return e==="on"?!0:e==="off"?!1:null}function Se(e=process.env,t=re()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0,difficulty:nb(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:nb(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1,consult:nb(e.MAIND_GUARD_CONSULT)??t?.guard_consult!==!1}}async function Do(e,t=Re()){let n={};try{let o=await W(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 G(t,JSON.stringify(r,null,2)+`
910
- `,384)}var Zt=w(()=>{"use strict";Ce();le();s(nb,"envSwitch");s(Se,"resolveGuardConfig");s(Do,"writeGuardConfig")});var Dd=w(()=>{"use strict";Dt()});function FO(e){return[e&&A4.has(e)?e:"claude-code"]}function HO(e){return FO(e)[0]??"claude-code"}async function Xi(e){let t=e.stack??null;return Qt("get_session_briefing",{tools:FO(e.clientFamily),...t&&t.languages.length>0?{languages:t.languages}:{},...t&&t.platforms.length>0?{platforms:t.platforms}:{}},e)}async function Qt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??ll,o=new AbortController,i=setTimeout(()=>o.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey),n.nestedProjectKeys&&n.nestedProjectKeys.length>0&&(a["x-maind-nested-project-keys"]=n.nestedProjectKeys.join(","));let l=n.stack?ho(n.stack):[];l.length>0&&(a["x-maind-stack"]=l.join(","));let c=await fetch(r,{method:"POST",headers:a,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:T4,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),u=c.headers.get("mcp-session-id"),d=(c.headers.get("content-type")??"").startsWith("text/event-stream")?await jO(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let b=null;try{let k=JSON.parse(d);typeof k.result?.instructions=="string"&&(b=k.result.instructions)}catch{b=null}n.onInitialize(b)}if(!c.ok||!u)return null;let p={...a,"mcp-session-id":u};await fetch(r,{method:"POST",headers:p,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(b=>b.text().catch(()=>"")).catch(()=>"");let f=await fetch(r,{method:"POST",headers:p,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!f.ok)return null;let h=(f.headers.get("content-type")??"").startsWith("text/event-stream")?await jO(f):await f.text();if(h.trim().length===0)return null;let g=JSON.parse(h);if(g.error||g.result?.isError)return null;let _=g.result?.content?.find(b=>b.type==="text"&&typeof b.text=="string")?.text;return typeof _=="string"&&_.trim().length>0?_:null}catch{return null}finally{clearTimeout(i)}}async function jO(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i="",a=s(()=>{if(o.length===0)return;let l=o.join(`
910
+ `,384)}var Zt=w(()=>{"use strict";Ce();le();s(nb,"envSwitch");s(Se,"resolveGuardConfig");s(Do,"writeGuardConfig")});var Dd=w(()=>{"use strict";Dt()});function FO(e){return[e&&A4.has(e)?e:"claude-code"]}function HO(e){return FO(e)[0]??"claude-code"}async function Xi(e){let t=e.stack??null;return Qt("get_session_briefing",{tools:FO(e.clientFamily),...t&&t.languages.length>0?{languages:t.languages}:{},...t&&t.platforms.length>0?{platforms:t.platforms}:{}},e)}async function Qt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??ll,o=new AbortController,i=setTimeout(()=>o.abort(),n.timeoutMs??3e3),a=null;try{let l={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(l["x-maind-device-id"]=n.deviceId),n.projectKey&&(l["x-maind-project-key"]=n.projectKey),n.nestedProjectKeys&&n.nestedProjectKeys.length>0&&(l["x-maind-nested-project-keys"]=n.nestedProjectKeys.join(","));let c=n.stack?ho(n.stack):[];c.length>0&&(l["x-maind-stack"]=c.join(","));let u=await fetch(r,{method:"POST",headers:l,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:T4,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),d=u.headers.get("mcp-session-id"),p=(u.headers.get("content-type")??"").startsWith("text/event-stream")?await jO(u).catch(()=>""):await u.text().catch(()=>"");if(n.onInitialize){let k=null;try{let v=JSON.parse(p);typeof v.result?.instructions=="string"&&(k=v.result.instructions)}catch{k=null}n.onInitialize(k)}if(!u.ok||!d)return null;let f={...l,"mcp-session-id":d};a=f,await fetch(r,{method:"POST",headers:f,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(k=>k.text().catch(()=>"")).catch(()=>"");let m=await fetch(r,{method:"POST",headers:f,signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!m.ok)return null;let g=(m.headers.get("content-type")??"").startsWith("text/event-stream")?await jO(m):await m.text();if(g.trim().length===0)return null;let _=JSON.parse(g);if(_.error||_.result?.isError)return null;let b=_.result?.content?.find(k=>k.type==="text"&&typeof k.text=="string")?.text;return typeof b=="string"&&b.trim().length>0?b:null}catch{return null}finally{clearTimeout(i),a!==null&&await C4(r,a)}}async function C4(e,t,n=R4){try{await(await fetch(e,{method:"DELETE",headers:t,signal:AbortSignal.timeout(n)})).text().catch(()=>"")}catch{}}async function jO(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i="",a=s(()=>{if(o.length===0)return;let l=o.join(`
911
911
  `).trim();o=[],l.length>0&&(i=l)},"flush");for(;;){let{value:l,done:c}=await t.read();if(c)break;r+=n.decode(l,{stream:!0});let u;for(;(u=r.indexOf(`
912
- `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}return a(),i}var ll,T4,A4,Ln=w(()=>{"use strict";Me();ll="https://mcp.maind.dev/mcp",T4="2025-06-18",A4=new Set(["claude-code","codex","copilot","cursor","windsurf","cline","continue","claude-desktop","gemini-cli"]);s(FO,"briefingToolsFor");s(HO,"briefingCacheFamilyFor");s(Xi,"fetchSessionBriefing");s(Qt,"fetchToolText");s(jO,"readSseMessage")});import{mkdirSync as R4,readFileSync as C4,renameSync as I4,writeFileSync as O4}from"node:fs";import{dirname as N4,join as D4}from"node:path";function rb(e){if(typeof e!="string")return null;let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e.trim());return t===null?null:[Number(t[1]),Number(t[2]),Number(t[3])]}function M4(e,t){let n=rb(e),r=rb(t);if(n===null||r===null)return!1;for(let o=0;o<3;o++){if(n[o]<r[o])return!0;if(n[o]>r[o])return!1}return!1}function BO(e){if(typeof e!="string")return null;let t=e.indexOf("{");if(t<0)return null;try{let r=JSON.parse(e.slice(t)).bridge_currency?.published;return typeof r=="string"&&rb(r)!==null?r.trim():null}catch{return null}}function $4(e,t){let n=(e??"").replace(/\\/g,"/");return n.split("/").includes("_npx")?`Your agent starts the bridge through npx; restarting it picks the new version up (or pin one: \`npm i -g ${UO}@${t}\`).`:/\/maind\/bridge\/node_modules\//.test(n)?"Re-run the one-click setup from the MAIND dashboard; it installs the current bridge into its own prefix.":`Update: \`npm i -g ${UO}@${t}\`.`}function L4(e){return e.published===null||!M4(e.running,e.published)?null:`[maind] bridge ${e.running} is running; npm serves ${e.published}. ${$4(e.entryPath,e.published)} Then restart the agent (a running bridge keeps its version), and run \`maind-mcp-bridge install --hooks-only\` for hooks the new version brings \u2014 the update wires none of them (asks consent per hook). This line comes once per release; \`maind-mcp-bridge doctor\` says it any time.`}function j4(e){try{let t=JSON.parse(C4(e,"utf8"));if(t&&typeof t.told=="object"&&t.told!==null){let n={};for(let[r,o]of Object.entries(t.told))o&&typeof o=="object"&&typeof o.at=="string"&&(n[r]={at:o.at,running:String(o.running??"")});return{version:1,told:n}}}catch{}return{version:1,told:{}}}function F4(e,t){R4(N4(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;O4(n,JSON.stringify(t,null,2),{mode:384}),I4(n,e)}function GO(e,t={}){let n=L4(e);if(n===null||e.published===null)return null;let r=t.stateFile??P4,o=j4(r);if(o.told[e.published]!==void 0)return null;o.told[e.published]={at:new Date(t.nowMs??Date.now()).toISOString(),running:e.running};try{F4(r,o)}catch{}return n}var P4,UO,KO=w(()=>{"use strict";Je();P4=D4(he,"bridge-currency-notice.json"),UO="@maind-dev/mcp-bridge";s(rb,"versionTriple");s(M4,"isBehind");s(BO,"publishedBridgeFromBriefing");s($4,"bridgeUpdateStep");s(L4,"bridgeCurrencyNoticeText");s(j4,"readState");s(F4,"writeState");s(GO,"bridgeCurrencyNotice")});var QO={};Q(QO,{BRIEFING_CACHE_FILE:()=>Pd,CACHE_TTL_MS:()=>zO,UNAVAILABLE_LINE:()=>XO,briefingCacheFileFor:()=>Md,briefingFamilyFor:()=>$d,carriesBriefing:()=>YO,conventionsIncomplete:()=>JO,deliverSessionBriefing:()=>Ld,formatInjection:()=>ZO,resolveBriefingInjection:()=>Zi,runGuardInject:()=>q4,runsUnderCursor:()=>II});import{existsSync as H4}from"node:fs";import{mkdir as U4,readFile as B4,rename as G4,writeFile as K4}from"node:fs/promises";import{homedir as WO}from"node:os";import{dirname as W4,join as qO}from"node:path";function Md(e){return!e||e==="claude-code"||!/^[a-z][a-z0-9-]{0,31}$/.test(e)?Pd:qO(he,`briefing-cache.${e}.json`)}function JO(e){return e!==null&&e.includes(pm)}async function Zi(e,t,n={}){let r=n.nowMs??Date.now(),o=n.client??"claude-code",i=n.cacheFile??Md(o),a=n.fetcher??Xi,l=n.stack??null,c=l?ho(l).join(","):"",u=[...n.nestedProjectKeys??[]].sort(),d=u.join(","),p=tr(t),f=await X4(i),m=f!==null&&f.format===VO&&f.key_fp===p&&(f.client??"claude-code")===o?f:null,h=m!==null&&m.project_key===e,g=m!==null&&h&&!m.incomplete&&(m.stack??"")===c&&(m.nested_keys??"")===d&&r-Date.parse(m.fetched_at)<zO,_=s(v=>({...v.conventions?{conventions:v.conventions}:{},...v.published_bridge?{publishedBridge:v.published_bridge}:{}}),"withConventions");if(g)return{text:m.text,via:"cache",..._(m)};let b=null,k=await a({onInitialize:s(v=>{b=Ki(v)},"onInitialize"),apiKey:t,deviceId:Q4(),projectKey:e,...u.length>0?{nestedProjectKeys:u}:{},bridgeVersion:K,timeoutMs:V4,stack:l,clientFamily:o});if(k!==null){let v=b,S=JO(v);if(S&&m!==null&&h&&!m.incomplete)return{text:m.text,via:"stale-cache",..._(m),projectKey:e,staleReason:"incomplete"};let x=BO(k);return await Z4(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:k,format:VO,key_fp:p,stack:c,...d?{nested_keys:d}:{},client:o,...S?{incomplete:!0}:{},...v?{conventions:v}:{},...x?{published_bridge:x}:{}}),{text:k,via:"fetch",...v?{conventions:v}:{},...x?{publishedBridge:x}:{}}}return m!==null?h?{text:m.text,via:"stale-cache",..._(m),projectKey:e,staleReason:"unreachable"}:{text:m.text,via:"stale-cache",projectKey:m.project_key,staleReason:"unreachable",conventionsWithheld:!0,...m.published_bridge?{publishedBridge:m.published_bridge}:{}}:{text:null,via:"none"}}async function q4(){try{if(Se().mode==="off")return 0;let t=await je();return AO(RO(WO(),Y4(t)))||_t(bt(WO(),process.env,process.platform)).enabled&&!(re()?.declined_hooks??[]).includes(ce)?0:await Ld("guard",t)}catch{return 0}}function YO(e){return e==="resume"||e==="fork"}function $d(e){return e==="gemini"?"gemini-cli":e==="codex"||e==="copilot"?e:"claude-code"}function z4(e,t){let n=Vi(e,t);if(n===null)return Z();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:Ke(n)}function J4(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Ld(e,t,n={}){let r=n.env??process.env,o=Pn(t,r,n.readConfig??re,n.hostHint??null);if(!me(o,{kind:"text",event:"SessionStart"}))return 0;let i=n.write??J4,a=n.collect,l=s(async L=>{if(a!==void 0)return a(L);let R=Co(o,{kind:"text",event:"SessionStart",text:L});R!==null&&await i(R)},"write"),c=Ro(o.host)?{host:o.host}:{},u=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(u===null)return 0;await GI();let d=typeof t.source=="string"?t.source:"startup";if(YO(d)){let L=await Xt(u);return await dt(u,{...L,carryover:!0}),0}let p=(n.apiKey??ee)();if(p===null)return 0;let f=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),m=(n.projectKey??(()=>z4(o,r)))(),h=$d(o.host),g={...n.inject,client:n.inject?.client??h},_=Vi(o,r)??f,b=(n.stackFor??Rn)(_),k=(n.nestedKeysFor??_d)(_,m),v=await Zi(m,p,{...g,stack:b,nestedProjectKeys:k}),S=await Xt(u);if(v.text===null)return await dt(u,{...S,inject_failed:!0}),await oe({event:"inject_fail",session_id:u,cwd:f,project_key:m??void 0,...e==="core"?{detail:"core"}:{},...c}),await l(XO),0;let x=(n.currencyNotice??GO)({running:K,published:v.publishedBridge??null,entryPath:se()}),T=ZO(v.text,v.via,v.conventions??null,e,{...v.staleReason?{reason:v.staleReason}:{},...v.conventionsWithheld?{conventionsWithheld:!0}:{}},x);await l(T.text),await dt(u,{...S,injected:!0});let A=T.complete?v.via:`${v.via}+budget`;return await oe({event:"inject_ok",session_id:u,cwd:f,project_key:m??void 0,detail:e==="core"?`core:${A}`:A,...c}),0}function Y4(e){let t=process.env.CLAUDE_PROJECT_DIR;return typeof t=="string"&&t.trim().length>0?t.trim():typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:null}function ZO(e,t,n=null,r="guard",o={},i=null){let a=t!=="stale-cache"?"":o.reason==="incomplete"?" \u2014 served from local cache: the server answered without your org's conventions":o.conventionsWithheld?" \u2014 served from local cache, server unreachable; the copy was made for another repository, so its project conventions are withheld (call get_conventions once the maind tools respond)":" \u2014 served from local cache, server unreachable",l=`Session briefing${n?" + project conventions":""}`,c=(r==="core"?`[maind] ${l}, delivered by the bridge's session-start hook (ADR-359)${a} \u2014 `:`[maind guard] ${l}, injected deterministically (ADR-284)${a} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return Wi(i?`${c}
912
+ `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}return a(),i}var ll,T4,A4,R4,Ln=w(()=>{"use strict";Me();ll="https://mcp.maind.dev/mcp",T4="2025-06-18",A4=new Set(["claude-code","codex","copilot","cursor","windsurf","cline","continue","claude-desktop","gemini-cli"]);s(FO,"briefingToolsFor");s(HO,"briefingCacheFamilyFor");s(Xi,"fetchSessionBriefing");s(Qt,"fetchToolText");R4=500;s(C4,"endMcpSession");s(jO,"readSseMessage")});import{mkdirSync as I4,readFileSync as O4,renameSync as N4,writeFileSync as D4}from"node:fs";import{dirname as P4,join as M4}from"node:path";function rb(e){if(typeof e!="string")return null;let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e.trim());return t===null?null:[Number(t[1]),Number(t[2]),Number(t[3])]}function L4(e,t){let n=rb(e),r=rb(t);if(n===null||r===null)return!1;for(let o=0;o<3;o++){if(n[o]<r[o])return!0;if(n[o]>r[o])return!1}return!1}function BO(e){if(typeof e!="string")return null;let t=e.indexOf("{");if(t<0)return null;try{let r=JSON.parse(e.slice(t)).bridge_currency?.published;return typeof r=="string"&&rb(r)!==null?r.trim():null}catch{return null}}function j4(e,t){let n=(e??"").replace(/\\/g,"/");return n.split("/").includes("_npx")?`Your agent starts the bridge through npx; restarting it picks the new version up (or pin one: \`npm i -g ${UO}@${t}\`).`:/\/maind\/bridge\/node_modules\//.test(n)?"Re-run the one-click setup from the MAIND dashboard; it installs the current bridge into its own prefix.":`Update: \`npm i -g ${UO}@${t}\`.`}function F4(e){return e.published===null||!L4(e.running,e.published)?null:`[maind] bridge ${e.running} is running; npm serves ${e.published}. ${j4(e.entryPath,e.published)} Then restart the agent (a running bridge keeps its version), and run \`maind-mcp-bridge install --hooks-only\` for hooks the new version brings \u2014 the update wires none of them (asks consent per hook). This line comes once per release; \`maind-mcp-bridge doctor\` says it any time.`}function H4(e){try{let t=JSON.parse(O4(e,"utf8"));if(t&&typeof t.told=="object"&&t.told!==null){let n={};for(let[r,o]of Object.entries(t.told))o&&typeof o=="object"&&typeof o.at=="string"&&(n[r]={at:o.at,running:String(o.running??"")});return{version:1,told:n}}}catch{}return{version:1,told:{}}}function U4(e,t){I4(P4(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;D4(n,JSON.stringify(t,null,2),{mode:384}),N4(n,e)}function GO(e,t={}){let n=F4(e);if(n===null||e.published===null)return null;let r=t.stateFile??$4,o=H4(r);if(o.told[e.published]!==void 0)return null;o.told[e.published]={at:new Date(t.nowMs??Date.now()).toISOString(),running:e.running};try{U4(r,o)}catch{}return n}var $4,UO,KO=w(()=>{"use strict";Je();$4=M4(he,"bridge-currency-notice.json"),UO="@maind-dev/mcp-bridge";s(rb,"versionTriple");s(L4,"isBehind");s(BO,"publishedBridgeFromBriefing");s(j4,"bridgeUpdateStep");s(F4,"bridgeCurrencyNoticeText");s(H4,"readState");s(U4,"writeState");s(GO,"bridgeCurrencyNotice")});var QO={};Q(QO,{BRIEFING_CACHE_FILE:()=>Pd,CACHE_TTL_MS:()=>zO,UNAVAILABLE_LINE:()=>XO,briefingCacheFileFor:()=>Md,briefingFamilyFor:()=>$d,carriesBriefing:()=>YO,conventionsIncomplete:()=>JO,deliverSessionBriefing:()=>Ld,formatInjection:()=>ZO,resolveBriefingInjection:()=>Zi,runGuardInject:()=>J4,runsUnderCursor:()=>II});import{existsSync as B4}from"node:fs";import{mkdir as G4,readFile as K4,rename as W4,writeFile as V4}from"node:fs/promises";import{homedir as WO}from"node:os";import{dirname as q4,join as qO}from"node:path";function Md(e){return!e||e==="claude-code"||!/^[a-z][a-z0-9-]{0,31}$/.test(e)?Pd:qO(he,`briefing-cache.${e}.json`)}function JO(e){return e!==null&&e.includes(pm)}async function Zi(e,t,n={}){let r=n.nowMs??Date.now(),o=n.client??"claude-code",i=n.cacheFile??Md(o),a=n.fetcher??Xi,l=n.stack??null,c=l?ho(l).join(","):"",u=[...n.nestedProjectKeys??[]].sort(),d=u.join(","),p=tr(t),f=await Q4(i),m=f!==null&&f.format===VO&&f.key_fp===p&&(f.client??"claude-code")===o?f:null,h=m!==null&&m.project_key===e,g=m!==null&&h&&!m.incomplete&&(m.stack??"")===c&&(m.nested_keys??"")===d&&r-Date.parse(m.fetched_at)<zO,_=s(v=>({...v.conventions?{conventions:v.conventions}:{},...v.published_bridge?{publishedBridge:v.published_bridge}:{}}),"withConventions");if(g)return{text:m.text,via:"cache",..._(m)};let b=null,k=await a({onInitialize:s(v=>{b=Ki(v)},"onInitialize"),apiKey:t,deviceId:tX(),projectKey:e,...u.length>0?{nestedProjectKeys:u}:{},bridgeVersion:K,timeoutMs:z4,stack:l,clientFamily:o});if(k!==null){let v=b,S=JO(v);if(S&&m!==null&&h&&!m.incomplete)return{text:m.text,via:"stale-cache",..._(m),projectKey:e,staleReason:"incomplete"};let x=BO(k);return await eX(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:k,format:VO,key_fp:p,stack:c,...d?{nested_keys:d}:{},client:o,...S?{incomplete:!0}:{},...v?{conventions:v}:{},...x?{published_bridge:x}:{}}),{text:k,via:"fetch",...v?{conventions:v}:{},...x?{publishedBridge:x}:{}}}return m!==null?h?{text:m.text,via:"stale-cache",..._(m),projectKey:e,staleReason:"unreachable"}:{text:m.text,via:"stale-cache",projectKey:m.project_key,staleReason:"unreachable",conventionsWithheld:!0,...m.published_bridge?{publishedBridge:m.published_bridge}:{}}:{text:null,via:"none"}}async function J4(){try{if(Se().mode==="off")return 0;let t=await je();return AO(RO(WO(),Z4(t)))||_t(bt(WO(),process.env,process.platform)).enabled&&!(re()?.declined_hooks??[]).includes(ce)?0:await Ld("guard",t)}catch{return 0}}function YO(e){return e==="resume"||e==="fork"}function $d(e){return e==="gemini"?"gemini-cli":e==="codex"||e==="copilot"?e:"claude-code"}function Y4(e,t){let n=Vi(e,t);if(n===null)return Z();let r=t.MAIND_PROJECT_KEY?.trim().toLowerCase();return r&&/^[a-f0-9]{64}$/.test(r)?r:Ke(n)}function X4(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Ld(e,t,n={}){let r=n.env??process.env,o=Pn(t,r,n.readConfig??re,n.hostHint??null);if(!me(o,{kind:"text",event:"SessionStart"}))return 0;let i=n.write??X4,a=n.collect,l=s(async L=>{if(a!==void 0)return a(L);let R=Co(o,{kind:"text",event:"SessionStart",text:L});R!==null&&await i(R)},"write"),c=Ro(o.host)?{host:o.host}:{},u=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(u===null)return 0;await GI();let d=typeof t.source=="string"?t.source:"startup";if(YO(d)){let L=await Xt(u);return await dt(u,{...L,carryover:!0}),0}let p=(n.apiKey??ee)();if(p===null)return 0;let f=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),m=(n.projectKey??(()=>Y4(o,r)))(),h=$d(o.host),g={...n.inject,client:n.inject?.client??h},_=Vi(o,r)??f,b=(n.stackFor??Rn)(_),k=(n.nestedKeysFor??_d)(_,m),v=await Zi(m,p,{...g,stack:b,nestedProjectKeys:k}),S=await Xt(u);if(v.text===null)return await dt(u,{...S,inject_failed:!0}),await oe({event:"inject_fail",session_id:u,cwd:f,project_key:m??void 0,...e==="core"?{detail:"core"}:{},...c}),await l(XO),0;let x=(n.currencyNotice??GO)({running:K,published:v.publishedBridge??null,entryPath:se()}),T=ZO(v.text,v.via,v.conventions??null,e,{...v.staleReason?{reason:v.staleReason}:{},...v.conventionsWithheld?{conventionsWithheld:!0}:{}},x);await l(T.text),await dt(u,{...S,injected:!0});let A=T.complete?v.via:`${v.via}+budget`;return await oe({event:"inject_ok",session_id:u,cwd:f,project_key:m??void 0,detail:e==="core"?`core:${A}`:A,...c}),0}function Z4(e){let t=process.env.CLAUDE_PROJECT_DIR;return typeof t=="string"&&t.trim().length>0?t.trim():typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:null}function ZO(e,t,n=null,r="guard",o={},i=null){let a=t!=="stale-cache"?"":o.reason==="incomplete"?" \u2014 served from local cache: the server answered without your org's conventions":o.conventionsWithheld?" \u2014 served from local cache, server unreachable; the copy was made for another repository, so its project conventions are withheld (call get_conventions once the maind tools respond)":" \u2014 served from local cache, server unreachable",l=`Session briefing${n?" + project conventions":""}`,c=(r==="core"?`[maind] ${l}, delivered by the bridge's session-start hook (ADR-359)${a} \u2014 `:`[maind guard] ${l}, injected deterministically (ADR-284)${a} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return Wi(i?`${c}
913
913
 
914
- ${i}`:c,n,e)}async function X4(e){try{if(!H4(e))return null;let t=JSON.parse(await B4(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text,...typeof t.format=="number"?{format:t.format}:{},...typeof t.conventions=="string"&&t.conventions.length>0?{conventions:t.conventions}:{},...typeof t.key_fp=="string"?{key_fp:t.key_fp}:{},...typeof t.stack=="string"?{stack:t.stack}:{},...typeof t.nested_keys=="string"?{nested_keys:t.nested_keys}:{},...typeof t.client=="string"?{client:t.client}:{},...t.incomplete===!0?{incomplete:!0}:{},...typeof t.published_bridge=="string"?{published_bridge:t.published_bridge}:{}}}catch{return null}}async function Z4(e,t){try{await U4(W4(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await K4(n,JSON.stringify(t,null,2),{mode:384}),await G4(n,e)}catch{}}function Q4(){try{return ke()}catch{return null}}var Pd,zO,VO,V4,XO,Po=w(()=>{"use strict";Ce();we();tt();Ie();Rd();Ui();Le();de();Xe();Wt();Et();Me();Za();Zt();Dd();pn();Je();Ln();KO();Ze();Pd=qO(he,"briefing-cache.json");s(Md,"briefingCacheFileFor");zO=5*60*1e3,VO=3,V4=3e3;s(JO,"conventionsIncomplete");s(Zi,"resolveBriefingInjection");s(q4,"runGuardInject");s(YO,"carriesBriefing");s($d,"briefingFamilyFor");s(z4,"sessionProjectKey");s(J4,"writeStdout");s(Ld,"deliverSessionBriefing");XO=`[maind] Session briefing unavailable \u2014 the maind server could not be reached and there is no local copy yet. Call get_session_briefing once the maind tools respond.
915
- `;s(Y4,"projectDirOf");s(ZO,"formatInjection");s(X4,"readCache");s(Z4,"writeCache");s(Q4,"safeDeviceId")});function jd(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function vr(e){return e+1}function Fd(e){return(e.text.split(`
916
- `,1)[0]??"").trim().slice(0,200)}function eX(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function tX(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let o=eX(r.childForFieldName("function"));o&&n.add(o)}return[...n]}function ob(e,t,n,r){for(let o of tX(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:o})}function cl(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let o=n;for(;o?.type==="member_expression";)o=o.childForFieldName("object");return o?.type==="this"?{name:t,receiver:"this.*"}:o?.type==="identifier"?{name:t,receiver:`${o.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function wr(e){if(!e)return null;let t=e.type==="type_annotation"?e.namedChildren[0]??null:e;if(!t)return null;switch(t.type){case"type_identifier":return t.text;case"nested_type_identifier":return t.text.replace(/\s+/g,"");case"generic_type":return wr(t.childForFieldName("name"));case"parenthesized_type":return wr(t.namedChildren[0]??null);case"union_type":{let n=t.namedChildren.filter(r=>!(r.type==="literal_type"&&/^(null|undefined)$/.test(r.text))&&!(r.type==="predefined_type"&&/^(null|undefined|void)$/.test(r.text)));return n.length===1?wr(n[0]):"#"}default:return"#"}}function rX(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function ib(e){if(e?.type!=="new_expression")return null;let t=e.childForFieldName("constructor");return t?.type==="identifier"||t?.type==="member_expression"?t.text:null}function ul(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let o=n.childForFieldName("value"),i=wr(n.childForFieldName("type"))??ib(o)??(rX(o)?"#":null);i&&t.set(r.text,i)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let o=wr(n.childForFieldName("type"));o&&t.set(r.text,o)}return t}function Sr(e,t,n,r,o={locals:ul(n)}){let i=new Set,a=s(c=>{if(!c)return;let u=`${c.receiver??""}\0${c.name}`;if(i.has(u))return;i.add(u);let d=c.receiver,p=d===null||d==="this"||d==="?"||d.endsWith(".*")?null:d.startsWith("this.")?o.thisFields?.get(d.slice(5))??null:o.locals.get(d)??null;e.refs.push({fromKey:t,kind:"calls",targetName:c.name,receiver:d,receiverType:p})},"add"),l=r?["call_expression","new_expression",...nX]:["call_expression","new_expression"];for(let c of n.descendantsOfType(l))if(c.type==="call_expression")a(cl(c.childForFieldName("function")));else if(c.type==="new_expression")a(cl(c.childForFieldName("constructor")));else{let u=c.childForFieldName("name");if(u?.type==="identifier"&&!/^[A-Z]/.test(u.text))continue;a(cl(u))}}var nX,Hd=w(()=>{"use strict";s(jd,"newResult");s(vr,"line1");s(Fd,"signatureOf");s(eX,"calleeName");s(tX,"collectCallTargets");s(ob,"addCallRefs");s(cl,"calleeRef");nX=["jsx_opening_element","jsx_self_closing_element"];s(wr,"typeNameOf");s(rX,"isMethodCallResult");s(ib,"newTypeOf");s(ul,"collectTypeHints");s(Sr,"addTsRefs")});function tN(e,t){let n=jd();for(let r of e.namedChildren)oX(r,t,n);return n}function nN(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function oX(e,t,n){let r=nN(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??sX(r);i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i});return}case"function_definition":{let o=r.childForFieldName("name")?.text;if(!o)return;let i=Ud(r,t,o,o,"function");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&ob(n,i.nodeKey,a,eN);return}case"class_definition":iX(r,t,n);return;case"expression_statement":{let i=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(i&&i.type==="identifier"){let a=Ud(r,t,i.text,i.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function iX(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let o=Ud(e,t,r,r,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let i=e.childForFieldName("superclasses");if(i){for(let l of i.namedChildren)if(l.type==="identifier")n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:l.text});else if(l.type==="attribute"){let c=l.childForFieldName("attribute")?.text;c&&n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:c})}}let a=e.childForFieldName("body");if(a)for(let l of a.namedChildren){let c=nN(l);if(c.type!=="function_definition")continue;let u=c.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,p=Ud(c,t,u,d,"method");n.nodes.push(p),n.edges.push({srcKey:o.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=c.childForFieldName("body");f&&ob(n,p.nodeKey,f,eN)}}function Ud(e,t,n,r,o){return{nodeKey:an(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vr(e.startPosition.row),endLine:vr(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Fd(e),doc:null}}function sX(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var eN,rN=w(()=>{"use strict";eo();Hd();eN="call";s(tN,"extractPython");s(nN,"unwrapDecorated");s(oX,"handleTopLevel");s(iX,"addClass");s(Ud,"makeNode");s(sX,"firstDottedName")});function iN(e,t){let n=jd(),r=t.language!=="typescript";for(let o of e.namedChildren)lX(o,t,n,r);return dX(e,t,n),n}function aX(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function lX(e,t,n,r){if(e.type==="export_statement"&&cX(e,t,n,r))return;let o=aX(e),i=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(o.type){case"import_statement":uX(o,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=oN(o,t,n,"function",r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=fX(o,t,n,r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":sb(o,t,n,"interface");return;case"type_alias_declaration":sb(o,t,n,"type_alias");return;case"enum_declaration":sb(o,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of o.namedChildren){if(a.type!=="variable_declarator")continue;let l=a.childForFieldName("name"),c=a.childForFieldName("value");if(!l||l.type!=="identifier"){c&&Sr(n,t.moduleKey,c,r);continue}let u=c?.type==="arrow_function"||c?.type==="function_expression"||c?.type==="function";oN(a,t,n,u?"function":"variable",r,l,c)}return}default:Sr(n,t.moduleKey,o,r);return}}function cX(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let o=lb(e.childForFieldName("source")),i=e.namedChildren.find(c=>c.type==="export_clause"),a=e.namedChildren.find(c=>c.type==="namespace_export");if(o!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:o}),i)for(let c of i.namedChildren.filter(u=>u.type==="export_specifier")){let u=c.childForFieldName("name")?.text;if(!u)continue;let d=c.childForFieldName("alias")?.text??u;n.exports.push({exportedName:d,specifier:o,importedName:u})}else if(a){let c=a.namedChildren.find(u=>u.type==="identifier")?.text;c&&n.exports.push({exportedName:c,specifier:o,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:o});return!0}if(i){for(let c of i.namedChildren.filter(u=>u.type==="export_specifier")){let u=c.childForFieldName("name")?.text;if(!u)continue;let d=c.childForFieldName("alias")?.text??u;d!==u&&n.exports.push({exportedName:d,localName:u})}return!0}let l=e.childForFieldName("value");return l?(l.type==="identifier"?n.exports.push({exportedName:"default",localName:l.text}):Sr(n,t.moduleKey,l,r),!0):!1}function uX(e,t,n){let r=lb(e.childForFieldName("source"));if(r===null)return;let o=e.namedChildren.find(l=>l.type==="import_clause"),i=[],a=s((l,c)=>{i.push({fromModuleKey:t.moduleKey,specifier:r,importedName:l,localName:c})},"bind");for(let l of o?.namedChildren??[])if(l.type==="identifier")a("default",l.text);else if(l.type==="namespace_import"){let c=l.namedChildren.find(u=>u.type==="identifier")?.text;c&&a("*",c)}else if(l.type==="named_imports")for(let c of l.namedChildren.filter(u=>u.type==="import_specifier")){let u=c.childForFieldName("name")?.text;u&&a(u,c.childForFieldName("alias")?.text??u)}i.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...i)}function dX(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let o=r.childForFieldName("arguments")?.namedChildren[0]??null,i=o?.type==="string"?lb(o):null;if(i===null)continue;let l=pX(r)?.childForFieldName("name");if(l?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:i,importedName:"*",localName:l.text});else if(l?.type==="object_pattern"){for(let c of l.namedChildren)if(c.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:i,importedName:c.text,localName:c.text});else if(c.type==="pair_pattern"){let u=c.childForFieldName("key")?.text,d=c.childForFieldName("value");u&&d?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i,importedName:u,localName:d.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:i})}}function pX(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function oN(e,t,n,r,o,i,a){let c=(i??e.childForFieldName("name"))?.text;if(!c)return null;let u=Bd(e,t,c,c,r);if(n.nodes.push(u),n.edges.push({srcKey:t.moduleKey,dstKey:u.nodeKey,kind:"contains"}),r==="function"){let d=a??e.childForFieldName("body")??e;Sr(n,u.nodeKey,d,o,{locals:ul(e)})}else a&&Sr(n,u.nodeKey,a,o);return u}function sb(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return;let i=Bd(e,t,o,o,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function fX(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return null;let i=Bd(e,t,o,o,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=e.namedChildren.find(u=>u.type==="class_heritage");for(let u of a?.namedChildren??[]){let d=u.type==="implements_clause"?u.namedChildren.map(p=>({kind:"implements",ref:ab(p)})):[{kind:"extends",ref:ab(u.type==="extends_clause"?u.childForFieldName("value"):u)}];for(let{kind:p,ref:f}of d)f&&n.refs.push({fromKey:i.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let l=e.childForFieldName("body");if(!l)return i;let c=mX(l);for(let u of l.namedChildren){if(u.type==="public_field_definition"||u.type==="field_definition"){let h=u.childForFieldName("value");h&&Sr(n,i.nodeKey,h,r,{locals:ul(h),thisFields:c});continue}if(u.type!=="method_definition")continue;let d=u.childForFieldName("name")?.text;if(!d)continue;let p=`${o}.${d}`,f=Bd(u,t,d,p,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=u.childForFieldName("body");m&&Sr(n,f.nodeKey,m,r,{locals:ul(u),thisFields:c})}return i}function mX(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),o=wr(n.childForFieldName("type"))??ib(n.childForFieldName("value"));r&&o&&t.set(r.text,o)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(a=>a.type==="accessibility_modifier"||a.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let o=r.childForFieldName("pattern"),i=wr(r.childForFieldName("type"));o?.type==="identifier"&&i&&t.set(o.text,i)}return t}function Bd(e,t,n,r,o){return{nodeKey:an(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vr(e.startPosition.row),endLine:vr(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Fd(e),doc:null}}function ab(e){if(!e)return null;switch(e.type){case"generic_type":return ab(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return cl(e);default:return null}}function lb(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var sN=w(()=>{"use strict";eo();Hd();s(iN,"extractTypescript");s(aX,"unwrapExport");s(lX,"handleTopLevel");s(cX,"handleExportForm");s(uX,"addImport");s(dX,"collectDynamicImports");s(pX,"enclosingDeclarator");s(oN,"addFunctionLike");s(sb,"addSimpleNamed");s(fX,"addClass");s(mX,"classFieldTypes");s(Bd,"makeNode");s(ab,"heritageRef");s(lb,"stringValue")});import{createRequire as hX}from"node:module";import{join as gX}from"node:path";function cN(e,t){return t?gX(t,aN[e]):hX(import.meta.url).resolve(`tree-sitter-wasms/out/${aN[e]}`)}var aN,lN,uN=w(()=>{"use strict";aN={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},lN="tree-sitter.wasm";s(cN,"grammarPath")});import{join as yX}from"node:path";import cb from"web-tree-sitter";var _X,Gd,dN=w(()=>{"use strict";eo();vc();rN();sN();Hd();uN();_X=["typescript","tsx","javascript","python"],Gd=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await cb.init(this.assetDir?{locateFile:s(t=>yX(this.assetDir,t||lN),"locateFile")}:void 0),this.parser=new cb,this.initialized=!0)}supports(t){return _X.includes(t)}async parse(t,n,r){await this.init();let o=this.parser;o.setLanguage(await this.grammar(r));let i=o.parse(n);if(!i)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=i.rootNode,l=sn(t),c={nodeKey:l,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:vr(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:l},d=r==="python"?tN(a,u):iN(a,u);return i.delete(),{filePath:t,language:r,nodes:[c,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports,exports:d.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await cb.Language.load(cN(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as bX}from"node:module";function pN(){return Kd("node:sqlite")}function Qi(){if(dl)return dl;try{let{DatabaseSync:e}=pN(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),dl={ok:!0}}finally{t.close()}}catch(e){dl={ok:!1,reason:e instanceof Error?e.message:String(e)}}return dl}function kX(e){let{DatabaseSync:t}=pN(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(o){try{n.exec("ROLLBACK")}catch{}throw o}},"transaction")}}function wX(e){let t=Kd("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function fN(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Wd(e){let t=fN(),n=s(()=>{let{DatabaseSync:o}=Kd("node:sqlite"),i=new o(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>i.exec(a),"exec"),close:s(()=>i.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let o=Kd("better-sqlite3"),i=new o(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>{i.exec(a)},"exec"),close:s(()=>{i.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(o){try{return r()}catch(i){let a=s(l=>l instanceof Error?l.message:String(l),"reason");throw new Error(`no usable SQLite backend for a read-only open: node:sqlite (${a(o)}); better-sqlite3 (${a(i)})`)}}}function Vd(e){let t=fN(),n=s(o=>{let i=o==="node:sqlite"?kX(e):wX(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:o}},"openAs");if(t==="builtin"){let o=Qi();if(!o.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${o.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=Qi();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${i})`)}}var Kd,dl,qd=w(()=>{"use strict";Kd=bX(import.meta.url);s(pN,"loadBuiltin");dl=null;s(Qi,"probeBuiltinSqlite");s(kX,"openBuiltin");s(wX,"openBetter");s(fN,"backendOverride");s(Wd,"openSqliteReadOnly");s(Vd,"openSqliteDatabase")});function wN(e,t){return{refs:t.refs.map(n=>[e,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:t.imports.map(n=>[e,n.specifier,n.importedName??null,n.localName??null]),exports:t.exports.map(n=>[e,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function vN(e,t,n,r){let o=new Map;for(let a of e)o.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let i=s(a=>o.get(String(a.file_path)),"entry");for(let a of t)i(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Mo(a.receiver),receiverType:Mo(a.receiver_type)});for(let a of n){let l=i(a);if(!l)continue;let c={fromModuleKey:sn(l.filePath),specifier:String(a.specifier),importedName:Mo(a.imported_name),localName:Mo(a.local_name)};l.imports.push(c)}for(let a of r){let l={exportedName:String(a.exported_name),localName:Mo(a.local_name),specifier:Mo(a.specifier),importedName:Mo(a.imported_name)};i(a)?.exports.push(l)}return[...o.values()]}var mN,hN,gN,yN,_N,bN,kN,Mo,SN=w(()=>{"use strict";eo();mN=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],hN="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",gN="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",yN="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",_N="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",bN="SELECT file_path, specifier, imported_name, local_name FROM file_imports",kN="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(wN,"factRows");Mo=s(e=>e==null?null:String(e),"str");s(vN,"assembleFacts")});function zd(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var xN,pl,EN=w(()=>{"use strict";qd();bi();SN();og();s(zd,"toNodeRow");xN=400,pl=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Vd(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(eg)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,o){this.db.transaction(()=>{this.deleteFileGraph(t.path);let a=this.insertNodeStmt(),l=this.insertFtsStmt();for(let c of n)a.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),l.run(c.nodeKey,r.get(c.nodeKey)??c.name);if(o){let c=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let m of o.contains)c.run(m.srcKey,m.dstKey,m.kind);let u=wN(t.path,o),d=this.db.prepare(hN);for(let m of u.refs)d.run(...m);let p=this.db.prepare(gN);for(let m of u.imports)p.run(...m);let f=this.db.prepare(yN);for(let m of u.exports)f.run(...m)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return vN(t,this.db.prepare(_N).all(),this.db.prepare(bN).all(),this.db.prepare(kN).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of t)r.run(o.srcKey,o.dstKey,o.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let o=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)o.run(a);let i=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)i.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?zd(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(zd)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(zd)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(zd)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let o of t){let i=Buffer.from(o.vec.buffer,o.vec.byteOffset,o.vec.byteLength);n.run(o.nodeKey,o.dim,i,o.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let o=IA(t);if(!o)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
914
+ ${i}`:c,n,e)}async function Q4(e){try{if(!B4(e))return null;let t=JSON.parse(await K4(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text,...typeof t.format=="number"?{format:t.format}:{},...typeof t.conventions=="string"&&t.conventions.length>0?{conventions:t.conventions}:{},...typeof t.key_fp=="string"?{key_fp:t.key_fp}:{},...typeof t.stack=="string"?{stack:t.stack}:{},...typeof t.nested_keys=="string"?{nested_keys:t.nested_keys}:{},...typeof t.client=="string"?{client:t.client}:{},...t.incomplete===!0?{incomplete:!0}:{},...typeof t.published_bridge=="string"?{published_bridge:t.published_bridge}:{}}}catch{return null}}async function eX(e,t){try{await G4(q4(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await V4(n,JSON.stringify(t,null,2),{mode:384}),await W4(n,e)}catch{}}function tX(){try{return ke()}catch{return null}}var Pd,zO,VO,z4,XO,Po=w(()=>{"use strict";Ce();we();tt();Ie();Rd();Ui();Le();de();Xe();Wt();Et();Me();Za();Zt();Dd();pn();Je();Ln();KO();Ze();Pd=qO(he,"briefing-cache.json");s(Md,"briefingCacheFileFor");zO=5*60*1e3,VO=3,z4=3e3;s(JO,"conventionsIncomplete");s(Zi,"resolveBriefingInjection");s(J4,"runGuardInject");s(YO,"carriesBriefing");s($d,"briefingFamilyFor");s(Y4,"sessionProjectKey");s(X4,"writeStdout");s(Ld,"deliverSessionBriefing");XO=`[maind] Session briefing unavailable \u2014 the maind server could not be reached and there is no local copy yet. Call get_session_briefing once the maind tools respond.
915
+ `;s(Z4,"projectDirOf");s(ZO,"formatInjection");s(Q4,"readCache");s(eX,"writeCache");s(tX,"safeDeviceId")});function jd(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function vr(e){return e+1}function Fd(e){return(e.text.split(`
916
+ `,1)[0]??"").trim().slice(0,200)}function nX(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function rX(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let o=nX(r.childForFieldName("function"));o&&n.add(o)}return[...n]}function ob(e,t,n,r){for(let o of rX(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:o})}function cl(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let o=n;for(;o?.type==="member_expression";)o=o.childForFieldName("object");return o?.type==="this"?{name:t,receiver:"this.*"}:o?.type==="identifier"?{name:t,receiver:`${o.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function wr(e){if(!e)return null;let t=e.type==="type_annotation"?e.namedChildren[0]??null:e;if(!t)return null;switch(t.type){case"type_identifier":return t.text;case"nested_type_identifier":return t.text.replace(/\s+/g,"");case"generic_type":return wr(t.childForFieldName("name"));case"parenthesized_type":return wr(t.namedChildren[0]??null);case"union_type":{let n=t.namedChildren.filter(r=>!(r.type==="literal_type"&&/^(null|undefined)$/.test(r.text))&&!(r.type==="predefined_type"&&/^(null|undefined|void)$/.test(r.text)));return n.length===1?wr(n[0]):"#"}default:return"#"}}function iX(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function ib(e){if(e?.type!=="new_expression")return null;let t=e.childForFieldName("constructor");return t?.type==="identifier"||t?.type==="member_expression"?t.text:null}function ul(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let o=n.childForFieldName("value"),i=wr(n.childForFieldName("type"))??ib(o)??(iX(o)?"#":null);i&&t.set(r.text,i)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let o=wr(n.childForFieldName("type"));o&&t.set(r.text,o)}return t}function Sr(e,t,n,r,o={locals:ul(n)}){let i=new Set,a=s(c=>{if(!c)return;let u=`${c.receiver??""}\0${c.name}`;if(i.has(u))return;i.add(u);let d=c.receiver,p=d===null||d==="this"||d==="?"||d.endsWith(".*")?null:d.startsWith("this.")?o.thisFields?.get(d.slice(5))??null:o.locals.get(d)??null;e.refs.push({fromKey:t,kind:"calls",targetName:c.name,receiver:d,receiverType:p})},"add"),l=r?["call_expression","new_expression",...oX]:["call_expression","new_expression"];for(let c of n.descendantsOfType(l))if(c.type==="call_expression")a(cl(c.childForFieldName("function")));else if(c.type==="new_expression")a(cl(c.childForFieldName("constructor")));else{let u=c.childForFieldName("name");if(u?.type==="identifier"&&!/^[A-Z]/.test(u.text))continue;a(cl(u))}}var oX,Hd=w(()=>{"use strict";s(jd,"newResult");s(vr,"line1");s(Fd,"signatureOf");s(nX,"calleeName");s(rX,"collectCallTargets");s(ob,"addCallRefs");s(cl,"calleeRef");oX=["jsx_opening_element","jsx_self_closing_element"];s(wr,"typeNameOf");s(iX,"isMethodCallResult");s(ib,"newTypeOf");s(ul,"collectTypeHints");s(Sr,"addTsRefs")});function tN(e,t){let n=jd();for(let r of e.namedChildren)sX(r,t,n);return n}function nN(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function sX(e,t,n){let r=nN(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??lX(r);i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i});return}case"function_definition":{let o=r.childForFieldName("name")?.text;if(!o)return;let i=Ud(r,t,o,o,"function");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&ob(n,i.nodeKey,a,eN);return}case"class_definition":aX(r,t,n);return;case"expression_statement":{let i=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(i&&i.type==="identifier"){let a=Ud(r,t,i.text,i.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function aX(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let o=Ud(e,t,r,r,"class");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let i=e.childForFieldName("superclasses");if(i){for(let l of i.namedChildren)if(l.type==="identifier")n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:l.text});else if(l.type==="attribute"){let c=l.childForFieldName("attribute")?.text;c&&n.refs.push({fromKey:o.nodeKey,kind:"extends",targetName:c})}}let a=e.childForFieldName("body");if(a)for(let l of a.namedChildren){let c=nN(l);if(c.type!=="function_definition")continue;let u=c.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,p=Ud(c,t,u,d,"method");n.nodes.push(p),n.edges.push({srcKey:o.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=c.childForFieldName("body");f&&ob(n,p.nodeKey,f,eN)}}function Ud(e,t,n,r,o){return{nodeKey:an(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vr(e.startPosition.row),endLine:vr(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Fd(e),doc:null}}function lX(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var eN,rN=w(()=>{"use strict";eo();Hd();eN="call";s(tN,"extractPython");s(nN,"unwrapDecorated");s(sX,"handleTopLevel");s(aX,"addClass");s(Ud,"makeNode");s(lX,"firstDottedName")});function iN(e,t){let n=jd(),r=t.language!=="typescript";for(let o of e.namedChildren)uX(o,t,n,r);return fX(e,t,n),n}function cX(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function uX(e,t,n,r){if(e.type==="export_statement"&&dX(e,t,n,r))return;let o=cX(e),i=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(o.type){case"import_statement":pX(o,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=oN(o,t,n,"function",r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=hX(o,t,n,r);i&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":sb(o,t,n,"interface");return;case"type_alias_declaration":sb(o,t,n,"type_alias");return;case"enum_declaration":sb(o,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of o.namedChildren){if(a.type!=="variable_declarator")continue;let l=a.childForFieldName("name"),c=a.childForFieldName("value");if(!l||l.type!=="identifier"){c&&Sr(n,t.moduleKey,c,r);continue}let u=c?.type==="arrow_function"||c?.type==="function_expression"||c?.type==="function";oN(a,t,n,u?"function":"variable",r,l,c)}return}default:Sr(n,t.moduleKey,o,r);return}}function dX(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let o=lb(e.childForFieldName("source")),i=e.namedChildren.find(c=>c.type==="export_clause"),a=e.namedChildren.find(c=>c.type==="namespace_export");if(o!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:o}),i)for(let c of i.namedChildren.filter(u=>u.type==="export_specifier")){let u=c.childForFieldName("name")?.text;if(!u)continue;let d=c.childForFieldName("alias")?.text??u;n.exports.push({exportedName:d,specifier:o,importedName:u})}else if(a){let c=a.namedChildren.find(u=>u.type==="identifier")?.text;c&&n.exports.push({exportedName:c,specifier:o,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:o});return!0}if(i){for(let c of i.namedChildren.filter(u=>u.type==="export_specifier")){let u=c.childForFieldName("name")?.text;if(!u)continue;let d=c.childForFieldName("alias")?.text??u;d!==u&&n.exports.push({exportedName:d,localName:u})}return!0}let l=e.childForFieldName("value");return l?(l.type==="identifier"?n.exports.push({exportedName:"default",localName:l.text}):Sr(n,t.moduleKey,l,r),!0):!1}function pX(e,t,n){let r=lb(e.childForFieldName("source"));if(r===null)return;let o=e.namedChildren.find(l=>l.type==="import_clause"),i=[],a=s((l,c)=>{i.push({fromModuleKey:t.moduleKey,specifier:r,importedName:l,localName:c})},"bind");for(let l of o?.namedChildren??[])if(l.type==="identifier")a("default",l.text);else if(l.type==="namespace_import"){let c=l.namedChildren.find(u=>u.type==="identifier")?.text;c&&a("*",c)}else if(l.type==="named_imports")for(let c of l.namedChildren.filter(u=>u.type==="import_specifier")){let u=c.childForFieldName("name")?.text;u&&a(u,c.childForFieldName("alias")?.text??u)}i.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...i)}function fX(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let o=r.childForFieldName("arguments")?.namedChildren[0]??null,i=o?.type==="string"?lb(o):null;if(i===null)continue;let l=mX(r)?.childForFieldName("name");if(l?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:i,importedName:"*",localName:l.text});else if(l?.type==="object_pattern"){for(let c of l.namedChildren)if(c.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:i,importedName:c.text,localName:c.text});else if(c.type==="pair_pattern"){let u=c.childForFieldName("key")?.text,d=c.childForFieldName("value");u&&d?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i,importedName:u,localName:d.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:i})}}function mX(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function oN(e,t,n,r,o,i,a){let c=(i??e.childForFieldName("name"))?.text;if(!c)return null;let u=Bd(e,t,c,c,r);if(n.nodes.push(u),n.edges.push({srcKey:t.moduleKey,dstKey:u.nodeKey,kind:"contains"}),r==="function"){let d=a??e.childForFieldName("body")??e;Sr(n,u.nodeKey,d,o,{locals:ul(e)})}else a&&Sr(n,u.nodeKey,a,o);return u}function sb(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return;let i=Bd(e,t,o,o,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function hX(e,t,n,r){let o=e.childForFieldName("name")?.text;if(!o)return null;let i=Bd(e,t,o,o,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=e.namedChildren.find(u=>u.type==="class_heritage");for(let u of a?.namedChildren??[]){let d=u.type==="implements_clause"?u.namedChildren.map(p=>({kind:"implements",ref:ab(p)})):[{kind:"extends",ref:ab(u.type==="extends_clause"?u.childForFieldName("value"):u)}];for(let{kind:p,ref:f}of d)f&&n.refs.push({fromKey:i.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let l=e.childForFieldName("body");if(!l)return i;let c=gX(l);for(let u of l.namedChildren){if(u.type==="public_field_definition"||u.type==="field_definition"){let h=u.childForFieldName("value");h&&Sr(n,i.nodeKey,h,r,{locals:ul(h),thisFields:c});continue}if(u.type!=="method_definition")continue;let d=u.childForFieldName("name")?.text;if(!d)continue;let p=`${o}.${d}`,f=Bd(u,t,d,p,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let m=u.childForFieldName("body");m&&Sr(n,f.nodeKey,m,r,{locals:ul(u),thisFields:c})}return i}function gX(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),o=wr(n.childForFieldName("type"))??ib(n.childForFieldName("value"));r&&o&&t.set(r.text,o)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(a=>a.type==="accessibility_modifier"||a.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let o=r.childForFieldName("pattern"),i=wr(r.childForFieldName("type"));o?.type==="identifier"&&i&&t.set(o.text,i)}return t}function Bd(e,t,n,r,o){return{nodeKey:an(t.filePath,r,o),kind:o,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:vr(e.startPosition.row),endLine:vr(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Fd(e),doc:null}}function ab(e){if(!e)return null;switch(e.type){case"generic_type":return ab(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return cl(e);default:return null}}function lb(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var sN=w(()=>{"use strict";eo();Hd();s(iN,"extractTypescript");s(cX,"unwrapExport");s(uX,"handleTopLevel");s(dX,"handleExportForm");s(pX,"addImport");s(fX,"collectDynamicImports");s(mX,"enclosingDeclarator");s(oN,"addFunctionLike");s(sb,"addSimpleNamed");s(hX,"addClass");s(gX,"classFieldTypes");s(Bd,"makeNode");s(ab,"heritageRef");s(lb,"stringValue")});import{createRequire as yX}from"node:module";import{join as _X}from"node:path";function cN(e,t){return t?_X(t,aN[e]):yX(import.meta.url).resolve(`tree-sitter-wasms/out/${aN[e]}`)}var aN,lN,uN=w(()=>{"use strict";aN={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},lN="tree-sitter.wasm";s(cN,"grammarPath")});import{join as bX}from"node:path";import cb from"web-tree-sitter";var kX,Gd,dN=w(()=>{"use strict";eo();vc();rN();sN();Hd();uN();kX=["typescript","tsx","javascript","python"],Gd=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await cb.init(this.assetDir?{locateFile:s(t=>bX(this.assetDir,t||lN),"locateFile")}:void 0),this.parser=new cb,this.initialized=!0)}supports(t){return kX.includes(t)}async parse(t,n,r){await this.init();let o=this.parser;o.setLanguage(await this.grammar(r));let i=o.parse(n);if(!i)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=i.rootNode,l=sn(t),c={nodeKey:l,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:vr(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:l},d=r==="python"?tN(a,u):iN(a,u);return i.delete(),{filePath:t,language:r,nodes:[c,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports,exports:d.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await cb.Language.load(cN(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as wX}from"node:module";function pN(){return Kd("node:sqlite")}function Qi(){if(dl)return dl;try{let{DatabaseSync:e}=pN(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),dl={ok:!0}}finally{t.close()}}catch(e){dl={ok:!1,reason:e instanceof Error?e.message:String(e)}}return dl}function vX(e){let{DatabaseSync:t}=pN(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(o){try{n.exec("ROLLBACK")}catch{}throw o}},"transaction")}}function SX(e){let t=Kd("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function fN(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Wd(e){let t=fN(),n=s(()=>{let{DatabaseSync:o}=Kd("node:sqlite"),i=new o(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>i.exec(a),"exec"),close:s(()=>i.close(),"close"),transaction:s(a=>a,"transaction")}}},"openBuiltinRo"),r=s(()=>{let o=Kd("better-sqlite3"),i=new o(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:s(a=>i.prepare(a),"prepare"),exec:s(a=>{i.exec(a)},"exec"),close:s(()=>{i.close()},"close"),transaction:s(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(o){try{return r()}catch(i){let a=s(l=>l instanceof Error?l.message:String(l),"reason");throw new Error(`no usable SQLite backend for a read-only open: node:sqlite (${a(o)}); better-sqlite3 (${a(i)})`)}}}function Vd(e){let t=fN(),n=s(o=>{let i=o==="node:sqlite"?vX(e):SX(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:o}},"openAs");if(t==="builtin"){let o=Qi();if(!o.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${o.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=Qi();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${i})`)}}var Kd,dl,qd=w(()=>{"use strict";Kd=wX(import.meta.url);s(pN,"loadBuiltin");dl=null;s(Qi,"probeBuiltinSqlite");s(vX,"openBuiltin");s(SX,"openBetter");s(fN,"backendOverride");s(Wd,"openSqliteReadOnly");s(Vd,"openSqliteDatabase")});function wN(e,t){return{refs:t.refs.map(n=>[e,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:t.imports.map(n=>[e,n.specifier,n.importedName??null,n.localName??null]),exports:t.exports.map(n=>[e,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function vN(e,t,n,r){let o=new Map;for(let a of e)o.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let i=s(a=>o.get(String(a.file_path)),"entry");for(let a of t)i(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Mo(a.receiver),receiverType:Mo(a.receiver_type)});for(let a of n){let l=i(a);if(!l)continue;let c={fromModuleKey:sn(l.filePath),specifier:String(a.specifier),importedName:Mo(a.imported_name),localName:Mo(a.local_name)};l.imports.push(c)}for(let a of r){let l={exportedName:String(a.exported_name),localName:Mo(a.local_name),specifier:Mo(a.specifier),importedName:Mo(a.imported_name)};i(a)?.exports.push(l)}return[...o.values()]}var mN,hN,gN,yN,_N,bN,kN,Mo,SN=w(()=>{"use strict";eo();mN=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],hN="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",gN="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",yN="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",_N="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",bN="SELECT file_path, specifier, imported_name, local_name FROM file_imports",kN="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";s(wN,"factRows");Mo=s(e=>e==null?null:String(e),"str");s(vN,"assembleFacts")});function zd(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var xN,pl,EN=w(()=>{"use strict";qd();bi();SN();og();s(zd,"toNodeRow");xN=400,pl=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Vd(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(eg)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,o){this.db.transaction(()=>{this.deleteFileGraph(t.path);let a=this.insertNodeStmt(),l=this.insertFtsStmt();for(let c of n)a.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),l.run(c.nodeKey,r.get(c.nodeKey)??c.name);if(o){let c=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let m of o.contains)c.run(m.srcKey,m.dstKey,m.kind);let u=wN(t.path,o),d=this.db.prepare(hN);for(let m of u.refs)d.run(...m);let p=this.db.prepare(gN);for(let m of u.imports)p.run(...m);let f=this.db.prepare(yN);for(let m of u.exports)f.run(...m)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return vN(t,this.db.prepare(_N).all(),this.db.prepare(bN).all(),this.db.prepare(kN).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of t)r.run(o.srcKey,o.dstKey,o.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let o=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)o.run(a);let i=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)i.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?zd(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(zd)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(zd)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(zd)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let o of t){let i=Buffer.from(o.vec.buffer,o.vec.byteOffset,o.vec.byteLength);n.run(o.nodeKey,o.dim,i,o.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let o=IA(t);if(!o)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
917
917
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
918
918
  WHERE nodes_fts MATCH ? AND n.kind = ?
919
919
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
@@ -936,58 +936,58 @@ ${i}`:c,n,e)}async function X4(e){try{if(!H4(e))return null;let t=JSON.parse(awa
936
936
  content_hash = excluded.content_hash,
937
937
  mtime_ms = excluded.mtime_ms,
938
938
  size = excluded.size,
939
- indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as vX}from"node:crypto";function es(e){return vX("sha256").update(e,"utf8").digest("hex")}function TN(e){return{node_key_hash:es(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:es(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?es(e.signature):null}}function AN(e){return{src_key_hash:es(e.srcKey),dst_key_hash:es(e.dstKey),kind:e.kind}}function RN(e,t,n){return{node_key_hash:es(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var CN=w(()=>{"use strict";s(es,"sha256");s(TN,"toCloudNode");s(AN,"toCloudEdge");s(RN,"toCloudEmbedding")});import{randomUUID as SX}from"node:crypto";function ub(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function IN(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function ON(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ts,ns,xX,db=w(()=>{"use strict";bi();CN();ts=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},ns=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(yi),lastSyncedAt:IN(await this.store.getMeta(ng))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(TN),n=(await this.store.getAllEdges()).map(AN),r=await this.store.getMeta(Zn)??Xn,o=await this.store.getMeta(yi),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),l=SX(),c={project_key:this.cfg.projectKey,head_commit:o,schema_version:r,file_count:i,lang_dist:a},u=0,d=ub(t,this.chunk),p=ub(n,this.chunk*2),f=Math.max(1,d.length+p.length);for(let _ of d)await this.post("/api/codebase/push",{...c,nodes:_,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++u,total:f});for(let _ of p)await this.post("/api/codebase/push",{...c,nodes:[],edges:_,sync_gen:l}),this.cfg.onProgress?.({phase:"edges",done:++u,total:f});d.length===0&&p.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let m=t.map(_=>_.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,edge_sync_gen:l});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let g=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ng,String(Date.now())),o&&await this.store.setMeta(RA,o),{nodes:t.length,edges:n.length,pruned:ON(h.nodes_deleted),edgesPruned:ON(h.edges_deleted),embeddings:g,headCommit:o}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),i=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>RN(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&i[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let l=ub(a,xX),c=0;for(let u of l)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++c,total:l.length});return a.length}async embedMeta(){let t=await this.store.getMeta(Zc),n=await this.store.getMeta(Qc),r=IN(await this.store.getMeta(eu));if(!t||!n||!r)throw new ts("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),o=null;try{o=r?JSON.parse(r):null}catch{o=null}if(!t.ok||!o||o.ok!==!0){let i=o?.error;throw new ts(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return o}},xX=250;s(ub,"chunkArray");s(IN,"numOrNull");s(ON,"numOr0")});var fb={};Q(fb,{CodeIndexSync:()=>ns,DEFAULT_DB_RELPATH:()=>pb,SyncError:()=>ts,createCodeIndexSync:()=>TX,createNodeCodeIndex:()=>Yd,openIndexReader:()=>AX,openSqliteDatabase:()=>Vd,openSqliteReadOnly:()=>Wd,probeBuiltinSqlite:()=>Qi});import{mkdirSync as EX}from"node:fs";import{posix as Jd}from"node:path";function Yd(e){let t=e.dbPath??Jd.join(e.repoRoot,pb);EX(Jd.dirname(t),{recursive:!0}),e.dbPath===void 0&&Ys(Jd.dirname(t));let n=new pl(t),r=new Gd;return new da({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function TX(e){let t=e.dbPath??Jd.join(e.repoRoot,pb),n=e.projectKey??qE(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new pl(t);return new ns(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function AX(e){return yg(Wd(e).db)}var pb,Xd=w(()=>{"use strict";Vm();dN();ig();_g();EN();qd();db();xc();db();qd();pb=".maind/code-index.sqlite";s(Yd,"createNodeCodeIndex");s(TX,"createCodeIndexSync");s(AX,"openIndexReader")});import{execFileSync as NN}from"node:child_process";import{existsSync as DN,realpathSync as PN}from"node:fs";import{createRequire as RX}from"node:module";import{basename as CX,dirname as IX,isAbsolute as MN,join as OX,relative as $N,resolve as Zd,sep as LN}from"node:path";function Qd(){let e=Qi();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return RX(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function jN(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function pt(e=process.cwd()){try{let t=NN("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 HN(e,t=pt(),n=process.cwd()){let r=MN(e)?[e]:[Zd(t,e),Zd(n,e)];for(let o of r){let i=IX(o);if(!DN(i))continue;let a;try{a=PN(i)}catch{continue}let l=UN(a);if(l===null)continue;let c=$N(l,OX(a,CX(o)));if(!c.startsWith(".."))return{repoRoot:l,repoRelPath:c.split(LN).join("/")}}return null}function rs(e,t=pt(),n=process.cwd()){let r=MN(e)?[e]:[Zd(t,e),Zd(n,e)];for(let o of r){if(!DN(o))continue;let i;try{i=PN(o)}catch{continue}let a=UN(i);if(a===null)continue;let l=$N(a,i);if(!l.startsWith(".."))return{repoRoot:a,repoRelDir:l===""?"":l.split(LN).join("/")}}return null}function UN(e){try{let t=NN("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function BN(){return Yd({repoRoot:pt()})}function GN(e){return Yd({repoRoot:e})}var FN,xr=w(()=>{"use strict";Xd();s(Qd,"probeNativeStore");s(jN,"isNativeStoreUnavailable");FN="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(pt,"resolveRepoRoot");s(HN,"resolveRepoRootForPath");s(rs,"resolveRepoRootForDir");s(UN,"gitToplevelOf");s(BN,"defaultEngineFactory");s(GN,"engineForRoot")});function ep(e){return e==="SessionStart"?"SessionStart":e==="UserPromptSubmit"?"BeforeAgent":e==="Stop"?"AfterAgent":e==="PostToolUse"?"AfterTool":null}function ft(e,t,n){let r=$e.find(o=>o.subcommand===e);if(r===void 0)throw new Error(`not in the core inventory: ${e}`);return{subcommand:e,event:t,timeout:r.timeout,label:r.label,...n?{tools:n}:{}}}function jn(e,t="core"){let n=[...(t==="guard"?LX:$X)[e]],r=new Set(n.filter(o=>o.extent==="none").map(o=>o.subcommand));return{hooks:(t==="guard"?WN:KN).filter(o=>!r.has(o.subcommand)),gaps:n}}function os(e,t){let n=new Set(t.map(o=>o.tools));if(n.has(void 0)||n.has("all")||n.size===0)return null;if(n.has("shell"))return n.size>1?null:e==="codex"?"Bash":e==="gemini"?"run_shell_command":"Bash|bash|run_in_terminal";if(e==="gemini")return n.has("plan")&&n.size===1?"^exit_plan_mode$":null;if(e==="codex")return n.has("read")&&n.size===1?null:"apply_patch";let r=[];return(n.has("edit")||n.has("write"))&&r.push("Edit","Write"),n.has("read")&&r.push("Read"),n.has("plan")&&r.push("exit_plan_mode","ExitPlanMode"),r.join("|")}function is(e){let t=[];for(let n of[...KN,...WN]){if(!e.some(o=>o.subcommand===n.subcommand))continue;let r=t.find(o=>o.event===n.event);r===void 0?t.push({event:n.event,hooks:[n]}):r.hooks.push(n)}return t}function ss(e){return e.reduce((t,n)=>t+n.timeout,0)}function as(e,t){let n=e==="codex"?"Codex":e==="gemini"?"Gemini CLI":"Copilot (VS Code's agent and the Copilot CLI)",r=e==="codex"?"apply_patch \u2014 the hook gets the patch text Codex hands every hook and reads only its file-header lines (*** Add File: / *** Update File: \u2026), never the changed lines":"the file-creating and file-editing tools (VS Code: create_file, replace_string_in_file, multi_replace_string_in_file, insert_edit_into_file, apply_patch; the CLI: create, edit) \u2014 the target PATHS only, never the contents",o=`It runs 'maind-mcp-bridge ${t.subcommand}' in ${n}`;switch(t.subcommand){case"on-session-reminder":return`${o} when a session starts and adds ~/.claude/maind-session-start-reminder.md \u2014 the maind consultation triggers \`install\` wrote there \u2014 to the session context. It reads that one file; nothing leaves the machine.`;case"on-session-start":return`${o} when a session starts \u2014 opens a tracked session so duration and tool-call counts can be measured, and adds one line on parallel sessions and open issues assigned to you from this machine's local presence snapshot. Writes only under ~/.maind; nothing leaves the machine here.`;case ce:return`${o} when a session starts and adds your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles. Delivery, not enforcement: it never blocks anything. It fetches the briefing from mcp.maind.dev, sending your API key, device id, the project key (a hash of the repository's git remote) and the client family '${e==="gemini"?"gemini-cli":e}' \u2014 never file contents, never paths. Cache-first (~12h), so most starts add no network call.`;case"on-prompt-context":return`${o} each time you submit a prompt. It reads the PROMPT TEXT on this machine only and matches it against the conventions MAIND already cached here and the symbol names in this repository's local code index; matches go to the model (at most ~2,000 characters). The prompt is never uploaded, stored or logged; no network call is made.`;case"on-tool-use":return`${o} before every tool call \u2014 counts calls for your Tier-3 session metrics. Only the tool NAME is read, never its arguments.`;case"on-file-write":return`${o} before a tool creates a file \u2014 ${r}. It checks whether a numbered filename (ADR-262-\u2026, 0001-\u2026) would claim a number a sibling branch or worktree already holds and refuses that one call, naming the next free number. Git and the filesystem on this machine; nothing is uploaded.`;case"on-file-edit":return`${o} before a tool changes a file \u2014 ${r}. It compares the paths LOCALLY with the claims of your parallel sessions (~/.maind/presence) and informs the agent when one overlaps. Never blocks; the paths never leave the machine.`;case"on-repo-health":return`${o} before the first file change in a repository per session \u2014 ${r}. It inspects that repository with git and the filesystem (missing tooling files in this worktree, uninstalled dependencies, stale builds, a rebase in progress, a detached HEAD, unwired git hooks) and adds a note for the model. Never blocks; two counters (runs, findings) ride with your Tier-3 metrics, numbers only.`;case"on-read-context":return`${o} before a tool reads a file (VS Code: read_file; the CLI: view). It reads the target PATH \u2014 never the contents \u2014 and looks it up in this repository's local code index; if the index matches the file on disk it adds at most ~1,500 characters on who calls and imports it. Nothing is uploaded.`;case"on-write-health":return`${o} after a tool changed a file \u2014 ${r}. It then READS THE REPOSITORY'S TRACKED SOURCE FILES from disk to run the checks that path makes relevant (spec contracts, Tailwind theme tokens, Supabase default grants \u2014 only where the repository declares them) and reports what this branch introduced, once per session. Nothing is stored or uploaded; it never blocks.`;case"on-session-end":return e==="codex"?`${o} at the end of every turn and returns at once: it closes the turn's counters in ~/.maind/state.json and hands the flush of your queued Tier-3 metrics (counts only) to a detached run. Codex's rollout is read only if you also allow Codex session analytics \u2014 a separate question that follows.`:`${o} at the end of every turn and returns at once: it closes the turn's counters in ~/.maind/state.json and hands the flush of your queued Tier-3 metrics (counts only) to a detached run. Copilot's transcript is not read.`;case"on-index-refresh":return`${o} at the end of a turn and refreshes this repository's local code index (.maind/code-index.sqlite) from the source files git reports as changed \u2014 it READS YOUR SOURCE FILES to do so. Only an index that already exists; nothing is uploaded; it returns at once (the work runs detached).`;case"guard-outcome":return`${o} after a shell command (${e==="codex"?"Bash":e==="gemini"?"run_shell_command":"VS Code: run_in_terminal; the CLI: bash"}) has run (ADR-360). It reads the PROGRAM and subcommand of the command line (e.g. \`pnpm test\`) \u2014 never paths, flags or values \u2014 and, on this machine only, the end of the command's output (last 8 KB) to recognise a failure summary or the exit code the host reports, then discards it. It appends one line (time, fail or ok, that program name) to a local per-session log in ~/.maind/guard/triggers/ \u2014 an 'ok' only for a program that already failed. When four failed attempts follow each other without a pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key \u2014 never tool data \u2014 and may add ONE hint for the model to consult maind. Nothing else leaves the machine. Inactive while guard mode is off.`;case"guard-capture":return`${o} when ${e==="gemini"?"the agent's turn ends (AfterAgent)":"a turn ends"} (ADR-360). Only after a hard-won fix recorded by guard-outcome \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it sends the agent back ONCE per episode with a reason asking it to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'. Inactive while guard mode is off.`;case"on-plan-accepted":return`${o} after exit_plan_mode \u2014 when you approve or reject a plan (${e==="gemini"?"AfterTool":"the Copilot CLI; VS Code's local agent has no such tool and ignores matchers, so there it starts after other tools and stops at once"}) (MAIND-1189). From the tool's answer it reads only whether the plan was approved and the plan file's PATH; on this machine it reads that file's LENGTH, never passing on its text, and from this session's local presence file (~/.maind) which MAIND work objects the session is bound to. For an approved plan it adds ONE note for the model: attach the plan to the work object it belongs to, with the ready command \u2014 or, if the plan is longer than the server accepts, to shorten it first. It never attaches anything itself and never blocks. Nothing is stored and nothing leaves the machine; without a maind presence for the session it says nothing.`;case"on-doc-duty":return`${o} when ${e==="gemini"?"the agent's turn ends (AfterAgent)":"a turn ends"}. When this session is bound to a MAIND work object and this branch has work for it (commits against the default branch or changes in the working tree), it checks LOCALLY whether a changed Markdown file names the object's key or a commit carries a 'Doc-Decision:' trailer \u2014 reading those Markdown files and the commit messages on this machine. Only when neither is there does it ask mcp.maind.dev whether the object still lacks documentation, sending your API key, device id, the project key, the session id and the object's key \u2014 never paths, never file contents. It makes the same call, with the same data, when a commit on this branch is a fix that states its cause, to learn whether the object's team turned on the lesson check (lesson_check); if so, it first asks the agent to check that finding against the lesson prerequisites and to ask you before submitting anything \u2014 once per finding, remembered in ~/.maind/lesson-check/, which also keeps the team setting for the learning-capture hook. If documentation is still missing (or the server does not answer), it sends the agent back ONCE with a short reminder naming the key and the two ways out \u2014 ${e==="gemini"?"Gemini CLI retries the turn with it as the prompt":`${e==="codex"?"Codex":"Copilot"} continues with it as the next prompt`}. Never twice for the same object in a session, and not at all once \`maind feature ship\` or \`promote\` said it (~/.maind/doc-duty/). Your organization switches it off with doc_duty = off.`;default:return`${o}.`}}var KN,WN,NX,DX,VN,PX,MX,$X,mb,LX,tp=w(()=>{"use strict";Le();s(ep,"geminiEventFor");s(ft,"fromInventory");KN=[ft("on-session-reminder","SessionStart"),ft("on-session-start","SessionStart"),ft(ce,"SessionStart"),ft("on-prompt-context","UserPromptSubmit"),ft("on-tool-use","PreToolUse","all"),ft("on-file-write","PreToolUse","write"),ft("on-file-edit","PreToolUse","edit"),ft("on-repo-health","PreToolUse","edit"),ft("on-read-context","PreToolUse","read"),ft("on-write-health","PostToolUse","edit"),ft("on-plan-accepted","PostToolUse","plan"),ft("on-session-end","Stop"),ft("on-index-refresh","Stop"),ft("on-doc-duty","Stop")],WN=(()=>{let e=s((t,n,r)=>{let o=cr.find(i=>i.subcommand===t);if(o===void 0)throw new Error(`not in the guard inventory: ${t}`);return{subcommand:t,event:n,timeout:o.timeout,label:o.label,pack:"guard",...r?{tools:r}:{}}},"of");return[e("guard-outcome","PostToolUse","shell"),e("guard-capture","Stop")]})(),NX="not wired for Gemini CLI yet \u2014 its BeforeTool/AfterTool payloads (write_file, replace, read_file, run_shell_command) are not read by the hooks yet",DX=[...["on-tool-use","on-file-write","on-file-edit","on-repo-health","on-read-context","on-write-health","on-shell-write","on-shell-changes"].map(e=>({subcommand:e,extent:"none",reason:NX})),{subcommand:"on-session-end",extent:"none",reason:"not wired for Gemini CLI yet \u2014 its AfterAgent/SessionEnd events and transcript format are not read; no session analytics or cost slices from Gemini"},{subcommand:"on-index-refresh",extent:"none",reason:"not wired for Gemini CLI yet \u2014 the local code index is refreshed by the next Claude Code or Codex turn, or by `maind index`"}],VN="`maind feature ship` and `promote --check` name an object without a plan",PX={subcommand:"on-plan-accepted",extent:"none",reason:`no tool call marks an accepted plan in Codex (its terminal UI sends a fixed message), so the note to attach it to its work object does not come here \u2014 ${VN}`},MX={subcommand:"on-plan-accepted",extent:"partial",reason:`the Copilot CLI (and VS Code's "Copilot" session target) only \u2014 VS Code's local agent hands a plan over with the Plan agent's prompt, no tool call; there ${VN}`},$X={gemini:DX,codex:[{subcommand:"on-read-context",extent:"none",reason:"Codex has no file-read tool \u2014 it reads files through the shell (Bash), so there is no read to attach the code-index context to"},{subcommand:"on-session-end",extent:"partial",reason:"session analytics and cost slices from Codex's rollout only with the separate codex_session_analytics answer, and without behaviour signals \u2014 Codex writes none"},{subcommand:"on-tool-use",extent:"partial",reason:"counts tool calls; the token-usage advisory reads Claude Code transcripts only"},{subcommand:"on-file-write",extent:"partial",reason:"sees edits made through apply_patch; a file written by a shell command (Bash) passes no file hook"},{subcommand:"on-shell-write",extent:"none",reason:"not wired for Codex yet \u2014 files written by a shell command (Bash) are not checked before the command runs"},{subcommand:"on-shell-changes",extent:"none",reason:"not wired for Codex yet \u2014 files a shell command changed are not checked after it runs"},PX],copilot:[{subcommand:"on-prompt-context",extent:"partial",reason:"delivered in VS Code; the Copilot CLI documents the output of command hooks on a submitted prompt as dropped"},{subcommand:"on-session-end",extent:"partial",reason:"closes the turn's counters and sends the Tier-3 metrics; Copilot's transcripts are not analysed, so there are no session analytics or cost slices"},{subcommand:"on-tool-use",extent:"partial",reason:"counts tool calls; the token-usage advisory reads Claude Code transcripts only"},{subcommand:"on-shell-write",extent:"none",reason:"not wired for Copilot yet \u2014 files written by a shell command are not checked before the command runs"},{subcommand:"on-shell-changes",extent:"none",reason:"not wired for Copilot yet \u2014 files a shell command changed are not checked after it runs"},MX]},mb="listens to PostToolUseFailure, which this host's hook file has no event for \u2014 a failed shell call arrives in PostToolUse here, and guard-outcome reads it there",LX={codex:[{subcommand:"guard-difficulty",extent:"none",reason:mb},{subcommand:"guard-outcome",extent:"partial",reason:"Codex hands hooks the output but no exit code \u2014 a failed command counts when its output ends in a failure summary (tests, tsc, pnpm, git \u2026), a bare non-zero exit does not; MCP tools are not watched (Codex matches tools by exact name)"}],copilot:[{subcommand:"guard-difficulty",extent:"none",reason:mb},{subcommand:"guard-outcome",extent:"partial",reason:"VS Code: the terminal's exit code from the tool's answer; the Copilot CLI sends a failed call to postToolUseFailure, which is not wired \u2014 there only failures summarised in the output count; MCP tools are not counted"}],gemini:[{subcommand:"guard-difficulty",extent:"none",reason:mb},{subcommand:"guard-outcome",extent:"partial",reason:"run_shell_command only \u2014 MCP tools (mcp_<server>_<tool>) cannot be told apart from maind's own and are not counted"}]};s(jn,"agentHooksFor");s(os,"matcherFor");s(is,"groupByEvent");s(ss,"entryTimeout");s(as,"agentHookConsent")});var YN={};Q(YN,{COPILOT_HOOKS_TARGET:()=>JN,COPILOT_HOOKS_VERSION:()=>np,COPILOT_HOST_FLAG:()=>yb,copilotCommand:()=>ip,copilotCommands:()=>op,copilotHookTarget:()=>gb,copilotHookWiring:()=>_b,copilotHooksDir:()=>rp,copilotHooksPath:()=>cs,copilotPresence:()=>fl,copilotRunsHook:()=>FX,mergeCopilotHooks:()=>us});import*as Er from"node:fs";import*as ls from"node:path";import*as zN from"node:readline";function rp(e){return ls.join(e.homeDir,".copilot","hooks")}function cs(e){return ls.join(rp(e),"maind.json")}function fl(e){return{evidence:[...ka(e).evidence,{kind:"foreign-entries",dir:ls.join(e.homeDir,".copilot"),ours:["instructions","hooks"]}],skipDetail:"Copilot not found (no VS Code app data, nothing of the Copilot CLI's in ~/.copilot)"}}function gb(e){return`hook(${e}):~/.copilot/hooks/maind.json`}function Fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function op(e,t){if(!Fn(e)||!Fn(e.hooks))return[];let n=e.hooks[t];if(!Array.isArray(n))return[];let r=[];for(let o of n)if(Fn(o)){for(let i of["command","bash","powershell"])typeof o[i]=="string"&&r.push(o[i]);if(Array.isArray(o.hooks))for(let i of o.hooks)Fn(i)&&typeof i.command=="string"&&r.push(i.command)}return r}function qN(e){return`'${e.replace(/'/g,"''")}'`}function ip(e,t=process.platform){return t==="win32"?`${Object.entries(e.env).map(([r,o])=>`$env:${r}=${qN(o)}; `).join("")}& ${[e.command,...e.args].map(qN).join(" ")}; exit 0`:`${at(e)} || true`}async function jX(e,t){let n=new Map,r=[];try{r=Er.readdirSync(e).filter(o=>o.toLowerCase().endsWith(".json"))}catch{return n}for(let o of r){let i;try{i=JSON.parse(await W(ls.join(e,o))??"null")}catch{continue}for(let a of t){if(n.has(a.subcommand))continue;let l=op(i,a.event).find(c=>c.includes(a.subcommand));l!==void 0&&n.set(a.subcommand,l)}}return n}async function us(e){let t=cs(e),{hooks:n,gaps:r}=jn("copilot",e.pack??"core"),o=s((v,S,x,T="merge")=>({target:gb(v),action:T,status:S,detail:x}),"row"),i=s(()=>r.map(v=>({target:gb(v.subcommand).replace(/^hook\(/,"gap("),action:"gap",status:"skipped",detail:`${v.extent==="none"?"not wired":"in part"} \u2014 ${v.reason}`})),"gapRows"),a=s((v,S,x="skip")=>[{target:JN,action:x,status:v,detail:S}],"one");if(e.skip)return a("skipped","--no-hook");if(!e.explicit&&!Te(fl(e.presence.ctx),e.presence.probe))return a("skipped",fl(e.presence.ctx).skipDetail);let l;try{l=await W(t)}catch(v){return a("failed",`read: ${hb(v)}`,"merge")}let c=l===null||l.trim().length===0,u={};if(!c){let v;try{v=JSON.parse(l)}catch(S){return a("failed",`parse: ${hb(S)} \u2014 ${t} left untouched`,"merge")}if(!Fn(v))return a("failed",`${t} is not a JSON object \u2014 left untouched`,"merge");if(v.version!==void 0&&v.version!==np)return a("skipped",`${t} has version ${JSON.stringify(v.version)}, not one this bridge knows (${np}) \u2014 left untouched`);if(v.hooks!==void 0&&!Fn(v.hooks))return a("failed",`"hooks" in ${t} is not an object \u2014 left untouched`,"merge");u=v}let d=await jX(rp(e),n),p=e.platform??process.platform,f=e.launchFor??(v=>Ee({entryPath:se(),nodePath:process.execPath,extraArgs:[hn,yb,...v],isElectron:process.versions.electron!==void 0})),m=[],h=[];for(let v of n){let S=d.get(v.subcommand);if(S!==void 0){let x=`Copilot already runs maind ${v.subcommand}`;m.push(o(v.subcommand,"skipped",It(S)?`${x}, but via \`npx\` \u2014 PATH decides which bridge that is`:x,"skip"));continue}if(!e.full){if(!e.isInteractive){m.push(o(v.subcommand,"skipped","consent-required: pass --full to write the hook non-interactively","skip"));continue}if(e.dryRun){m.push(o(v.subcommand,c?"would-create":"would-merge",`${t} (would prompt for consent in real run)`));continue}if(!await(e.prompt??HX)(e.out,`
939
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as xX}from"node:crypto";function es(e){return xX("sha256").update(e,"utf8").digest("hex")}function TN(e){return{node_key_hash:es(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:es(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?es(e.signature):null}}function AN(e){return{src_key_hash:es(e.srcKey),dst_key_hash:es(e.dstKey),kind:e.kind}}function RN(e,t,n){return{node_key_hash:es(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var CN=w(()=>{"use strict";s(es,"sha256");s(TN,"toCloudNode");s(AN,"toCloudEdge");s(RN,"toCloudEmbedding")});import{randomUUID as EX}from"node:crypto";function ub(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function IN(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function ON(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ts,ns,TX,db=w(()=>{"use strict";bi();CN();ts=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},ns=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(yi),lastSyncedAt:IN(await this.store.getMeta(ng))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(TN),n=(await this.store.getAllEdges()).map(AN),r=await this.store.getMeta(Zn)??Xn,o=await this.store.getMeta(yi),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(_=>[_.language,_.count])),l=EX(),c={project_key:this.cfg.projectKey,head_commit:o,schema_version:r,file_count:i,lang_dist:a},u=0,d=ub(t,this.chunk),p=ub(n,this.chunk*2),f=Math.max(1,d.length+p.length);for(let _ of d)await this.post("/api/codebase/push",{...c,nodes:_,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++u,total:f});for(let _ of p)await this.post("/api/codebase/push",{...c,nodes:[],edges:_,sync_gen:l}),this.cfg.onProgress?.({phase:"edges",done:++u,total:f});d.length===0&&p.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let m=t.map(_=>_.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m,edge_sync_gen:l});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let g=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ng,String(Date.now())),o&&await this.store.setMeta(RA,o),{nodes:t.length,edges:n.length,pruned:ON(h.nodes_deleted),edgesPruned:ON(h.edges_deleted),embeddings:g,headCommit:o}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),i=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>RN(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&i[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let l=ub(a,TX),c=0;for(let u of l)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++c,total:l.length});return a.length}async embedMeta(){let t=await this.store.getMeta(Zc),n=await this.store.getMeta(Qc),r=IN(await this.store.getMeta(eu));if(!t||!n||!r)throw new ts("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),o=null;try{o=r?JSON.parse(r):null}catch{o=null}if(!t.ok||!o||o.ok!==!0){let i=o?.error;throw new ts(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return o}},TX=250;s(ub,"chunkArray");s(IN,"numOrNull");s(ON,"numOr0")});var fb={};Q(fb,{CodeIndexSync:()=>ns,DEFAULT_DB_RELPATH:()=>pb,SyncError:()=>ts,createCodeIndexSync:()=>RX,createNodeCodeIndex:()=>Yd,openIndexReader:()=>CX,openSqliteDatabase:()=>Vd,openSqliteReadOnly:()=>Wd,probeBuiltinSqlite:()=>Qi});import{mkdirSync as AX}from"node:fs";import{posix as Jd}from"node:path";function Yd(e){let t=e.dbPath??Jd.join(e.repoRoot,pb);AX(Jd.dirname(t),{recursive:!0}),e.dbPath===void 0&&Ys(Jd.dirname(t));let n=new pl(t),r=new Gd;return new da({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function RX(e){let t=e.dbPath??Jd.join(e.repoRoot,pb),n=e.projectKey??qE(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new pl(t);return new ns(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function CX(e){return yg(Wd(e).db)}var pb,Xd=w(()=>{"use strict";Vm();dN();ig();_g();EN();qd();db();xc();db();qd();pb=".maind/code-index.sqlite";s(Yd,"createNodeCodeIndex");s(RX,"createCodeIndexSync");s(CX,"openIndexReader")});import{execFileSync as NN}from"node:child_process";import{existsSync as DN,realpathSync as PN}from"node:fs";import{createRequire as IX}from"node:module";import{basename as OX,dirname as NX,isAbsolute as MN,join as DX,relative as $N,resolve as Zd,sep as LN}from"node:path";function Qd(){let e=Qi();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return IX(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function jN(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function pt(e=process.cwd()){try{let t=NN("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 HN(e,t=pt(),n=process.cwd()){let r=MN(e)?[e]:[Zd(t,e),Zd(n,e)];for(let o of r){let i=NX(o);if(!DN(i))continue;let a;try{a=PN(i)}catch{continue}let l=UN(a);if(l===null)continue;let c=$N(l,DX(a,OX(o)));if(!c.startsWith(".."))return{repoRoot:l,repoRelPath:c.split(LN).join("/")}}return null}function rs(e,t=pt(),n=process.cwd()){let r=MN(e)?[e]:[Zd(t,e),Zd(n,e)];for(let o of r){if(!DN(o))continue;let i;try{i=PN(o)}catch{continue}let a=UN(i);if(a===null)continue;let l=$N(a,i);if(!l.startsWith(".."))return{repoRoot:a,repoRelDir:l===""?"":l.split(LN).join("/")}}return null}function UN(e){try{let t=NN("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function BN(){return Yd({repoRoot:pt()})}function GN(e){return Yd({repoRoot:e})}var FN,xr=w(()=>{"use strict";Xd();s(Qd,"probeNativeStore");s(jN,"isNativeStoreUnavailable");FN="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(pt,"resolveRepoRoot");s(HN,"resolveRepoRootForPath");s(rs,"resolveRepoRootForDir");s(UN,"gitToplevelOf");s(BN,"defaultEngineFactory");s(GN,"engineForRoot")});function ep(e){return e==="SessionStart"?"SessionStart":e==="UserPromptSubmit"?"BeforeAgent":e==="Stop"?"AfterAgent":e==="PostToolUse"?"AfterTool":null}function ft(e,t,n){let r=$e.find(o=>o.subcommand===e);if(r===void 0)throw new Error(`not in the core inventory: ${e}`);return{subcommand:e,event:t,timeout:r.timeout,label:r.label,...n?{tools:n}:{}}}function jn(e,t="core"){let n=[...(t==="guard"?FX:jX)[e]],r=new Set(n.filter(o=>o.extent==="none").map(o=>o.subcommand));return{hooks:(t==="guard"?WN:KN).filter(o=>!r.has(o.subcommand)),gaps:n}}function os(e,t){let n=new Set(t.map(o=>o.tools));if(n.has(void 0)||n.has("all")||n.size===0)return null;if(n.has("shell"))return n.size>1?null:e==="codex"?"Bash":e==="gemini"?"run_shell_command":"Bash|bash|run_in_terminal";if(e==="gemini")return n.has("plan")&&n.size===1?"^exit_plan_mode$":null;if(e==="codex")return n.has("read")&&n.size===1?null:"apply_patch";let r=[];return(n.has("edit")||n.has("write"))&&r.push("Edit","Write"),n.has("read")&&r.push("Read"),n.has("plan")&&r.push("exit_plan_mode","ExitPlanMode"),r.join("|")}function is(e){let t=[];for(let n of[...KN,...WN]){if(!e.some(o=>o.subcommand===n.subcommand))continue;let r=t.find(o=>o.event===n.event);r===void 0?t.push({event:n.event,hooks:[n]}):r.hooks.push(n)}return t}function ss(e){return e.reduce((t,n)=>t+n.timeout,0)}function as(e,t){let n=e==="codex"?"Codex":e==="gemini"?"Gemini CLI":"Copilot (VS Code's agent and the Copilot CLI)",r=e==="codex"?"apply_patch \u2014 the hook gets the patch text Codex hands every hook and reads only its file-header lines (*** Add File: / *** Update File: \u2026), never the changed lines":"the file-creating and file-editing tools (VS Code: create_file, replace_string_in_file, multi_replace_string_in_file, insert_edit_into_file, apply_patch; the CLI: create, edit) \u2014 the target PATHS only, never the contents",o=`It runs 'maind-mcp-bridge ${t.subcommand}' in ${n}`;switch(t.subcommand){case"on-session-reminder":return`${o} when a session starts and adds ~/.claude/maind-session-start-reminder.md \u2014 the maind consultation triggers \`install\` wrote there \u2014 to the session context. It reads that one file; nothing leaves the machine.`;case"on-session-start":return`${o} when a session starts \u2014 opens a tracked session so duration and tool-call counts can be measured, and adds one line on parallel sessions and open issues assigned to you from this machine's local presence snapshot. Writes only under ~/.maind; nothing leaves the machine here.`;case ce:return`${o} when a session starts and adds your maind session briefing \u2014 the project conventions first, then your top lessons, skills and memory titles. Delivery, not enforcement: it never blocks anything. It fetches the briefing from mcp.maind.dev, sending your API key, device id, the project key (a hash of the repository's git remote) and the client family '${e==="gemini"?"gemini-cli":e}' \u2014 never file contents, never paths. Cache-first (~12h), so most starts add no network call.`;case"on-prompt-context":return`${o} each time you submit a prompt. It reads the PROMPT TEXT on this machine only and matches it against the conventions MAIND already cached here and the symbol names in this repository's local code index; matches go to the model (at most ~2,000 characters). The prompt is never uploaded, stored or logged; no network call is made.`;case"on-tool-use":return`${o} before every tool call \u2014 counts calls for your Tier-3 session metrics. Only the tool NAME is read, never its arguments.`;case"on-file-write":return`${o} before a tool creates a file \u2014 ${r}. It checks whether a numbered filename (ADR-262-\u2026, 0001-\u2026) would claim a number a sibling branch or worktree already holds and refuses that one call, naming the next free number. Git and the filesystem on this machine; nothing is uploaded.`;case"on-file-edit":return`${o} before a tool changes a file \u2014 ${r}. It compares the paths LOCALLY with the claims of your parallel sessions (~/.maind/presence) and informs the agent when one overlaps. Never blocks; the paths never leave the machine.`;case"on-repo-health":return`${o} before the first file change in a repository per session \u2014 ${r}. It inspects that repository with git and the filesystem (missing tooling files in this worktree, uninstalled dependencies, stale builds, a rebase in progress, a detached HEAD, unwired git hooks) and adds a note for the model. Never blocks; two counters (runs, findings) ride with your Tier-3 metrics, numbers only.`;case"on-read-context":return`${o} before a tool reads a file (VS Code: read_file; the CLI: view). It reads the target PATH \u2014 never the contents \u2014 and looks it up in this repository's local code index; if the index matches the file on disk it adds at most ~1,500 characters on who calls and imports it. Nothing is uploaded.`;case"on-write-health":return`${o} after a tool changed a file \u2014 ${r}. It then READS THE REPOSITORY'S TRACKED SOURCE FILES from disk to run the checks that path makes relevant (spec contracts, Tailwind theme tokens, Supabase default grants \u2014 only where the repository declares them) and reports what this branch introduced, once per session. Nothing is stored or uploaded; it never blocks.`;case"on-session-end":return e==="codex"?`${o} at the end of every turn and returns at once: it closes the turn's counters in ~/.maind/state.json and hands the flush of your queued Tier-3 metrics (counts only) to a detached run. Codex's rollout is read only if you also allow Codex session analytics \u2014 a separate question that follows.`:`${o} at the end of every turn and returns at once: it closes the turn's counters in ~/.maind/state.json and hands the flush of your queued Tier-3 metrics (counts only) to a detached run. Copilot's transcript is not read.`;case"on-index-refresh":return`${o} at the end of a turn and refreshes this repository's local code index (.maind/code-index.sqlite) from the source files git reports as changed \u2014 it READS YOUR SOURCE FILES to do so. Only an index that already exists; nothing is uploaded; it returns at once (the work runs detached).`;case"guard-outcome":return`${o} after a shell command (${e==="codex"?"Bash":e==="gemini"?"run_shell_command":"VS Code: run_in_terminal; the CLI: bash"}) has run (ADR-360). It reads the PROGRAM and subcommand of the command line (e.g. \`pnpm test\`) \u2014 never paths, flags or values \u2014 and, on this machine only, the end of the command's output (last 8 KB) to recognise a failure summary or the exit code the host reports, then discards it. It appends one line (time, fail or ok, that program name) to a local per-session log in ~/.maind/guard/triggers/ \u2014 an 'ok' only for a program that already failed. When four failed attempts follow each other without a pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key \u2014 never tool data \u2014 and may add ONE hint for the model to consult maind. Nothing else leaves the machine. Inactive while guard mode is off.`;case"guard-capture":return`${o} when ${e==="gemini"?"the agent's turn ends (AfterAgent)":"a turn ends"} (ADR-360). Only after a hard-won fix recorded by guard-outcome \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it sends the agent back ONCE per episode with a reason asking it to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'. Inactive while guard mode is off.`;case"on-plan-accepted":return`${o} after exit_plan_mode \u2014 when you approve or reject a plan (${e==="gemini"?"AfterTool":"the Copilot CLI; VS Code's local agent has no such tool and ignores matchers, so there it starts after other tools and stops at once"}) (MAIND-1189). From the tool's answer it reads only whether the plan was approved and the plan file's PATH; on this machine it reads that file's LENGTH, never passing on its text, and from this session's local presence file (~/.maind) which MAIND work objects the session is bound to. For an approved plan it adds ONE note for the model: attach the plan to the work object it belongs to, with the ready command \u2014 or, if the plan is longer than the server accepts, to shorten it first. It never attaches anything itself and never blocks. Nothing is stored and nothing leaves the machine; without a maind presence for the session it says nothing.`;case"on-doc-duty":return`${o} when ${e==="gemini"?"the agent's turn ends (AfterAgent)":"a turn ends"}. When this session is bound to a MAIND work object and this branch has work for it (commits against the default branch or changes in the working tree), it checks LOCALLY whether a changed Markdown file names the object's key or a commit carries a 'Doc-Decision:' trailer \u2014 reading those Markdown files and the commit messages on this machine. Only when neither is there does it ask mcp.maind.dev whether the object still lacks documentation, sending your API key, device id, the project key, the session id and the object's key \u2014 never paths, never file contents. It makes the same call, with the same data, when a commit on this branch is a fix that states its cause, to learn whether the object's team turned on the lesson check (lesson_check); if so, it first asks the agent to check that finding against the lesson prerequisites and to ask you before submitting anything \u2014 once per finding, remembered in ~/.maind/lesson-check/, which also keeps the team setting for the learning-capture hook. If documentation is still missing (or the server does not answer), it sends the agent back ONCE with a short reminder naming the key and the two ways out \u2014 ${e==="gemini"?"Gemini CLI retries the turn with it as the prompt":`${e==="codex"?"Codex":"Copilot"} continues with it as the next prompt`}. Never twice for the same object in a session, and not at all once \`maind feature ship\` or \`promote\` said it (~/.maind/doc-duty/). Your organization switches it off with doc_duty = off.`;default:return`${o}.`}}var KN,WN,PX,MX,VN,$X,LX,jX,mb,FX,tp=w(()=>{"use strict";Le();s(ep,"geminiEventFor");s(ft,"fromInventory");KN=[ft("on-session-reminder","SessionStart"),ft("on-session-start","SessionStart"),ft(ce,"SessionStart"),ft("on-prompt-context","UserPromptSubmit"),ft("on-tool-use","PreToolUse","all"),ft("on-file-write","PreToolUse","write"),ft("on-file-edit","PreToolUse","edit"),ft("on-repo-health","PreToolUse","edit"),ft("on-read-context","PreToolUse","read"),ft("on-write-health","PostToolUse","edit"),ft("on-plan-accepted","PostToolUse","plan"),ft("on-session-end","Stop"),ft("on-index-refresh","Stop"),ft("on-doc-duty","Stop")],WN=(()=>{let e=s((t,n,r)=>{let o=cr.find(i=>i.subcommand===t);if(o===void 0)throw new Error(`not in the guard inventory: ${t}`);return{subcommand:t,event:n,timeout:o.timeout,label:o.label,pack:"guard",...r?{tools:r}:{}}},"of");return[e("guard-outcome","PostToolUse","shell"),e("guard-capture","Stop")]})(),PX="not wired for Gemini CLI yet \u2014 its BeforeTool/AfterTool payloads (write_file, replace, read_file, run_shell_command) are not read by the hooks yet",MX=[...["on-tool-use","on-file-write","on-file-edit","on-repo-health","on-read-context","on-write-health","on-shell-write","on-shell-changes"].map(e=>({subcommand:e,extent:"none",reason:PX})),{subcommand:"on-session-end",extent:"none",reason:"not wired for Gemini CLI yet \u2014 its AfterAgent/SessionEnd events and transcript format are not read; no session analytics or cost slices from Gemini"},{subcommand:"on-index-refresh",extent:"none",reason:"not wired for Gemini CLI yet \u2014 the local code index is refreshed by the next Claude Code or Codex turn, or by `maind index`"}],VN="`maind feature ship` and `promote --check` name an object without a plan",$X={subcommand:"on-plan-accepted",extent:"none",reason:`no tool call marks an accepted plan in Codex (its terminal UI sends a fixed message), so the note to attach it to its work object does not come here \u2014 ${VN}`},LX={subcommand:"on-plan-accepted",extent:"partial",reason:`the Copilot CLI (and VS Code's "Copilot" session target) only \u2014 VS Code's local agent hands a plan over with the Plan agent's prompt, no tool call; there ${VN}`},jX={gemini:MX,codex:[{subcommand:"on-read-context",extent:"none",reason:"Codex has no file-read tool \u2014 it reads files through the shell (Bash), so there is no read to attach the code-index context to"},{subcommand:"on-session-end",extent:"partial",reason:"session analytics and cost slices from Codex's rollout only with the separate codex_session_analytics answer, and without behaviour signals \u2014 Codex writes none"},{subcommand:"on-tool-use",extent:"partial",reason:"counts tool calls; the token-usage advisory reads Claude Code transcripts only"},{subcommand:"on-file-write",extent:"partial",reason:"sees edits made through apply_patch; a file written by a shell command (Bash) passes no file hook"},{subcommand:"on-shell-write",extent:"none",reason:"not wired for Codex yet \u2014 files written by a shell command (Bash) are not checked before the command runs"},{subcommand:"on-shell-changes",extent:"none",reason:"not wired for Codex yet \u2014 files a shell command changed are not checked after it runs"},$X],copilot:[{subcommand:"on-prompt-context",extent:"partial",reason:"delivered in VS Code; the Copilot CLI documents the output of command hooks on a submitted prompt as dropped"},{subcommand:"on-session-end",extent:"partial",reason:"closes the turn's counters and sends the Tier-3 metrics; Copilot's transcripts are not analysed, so there are no session analytics or cost slices"},{subcommand:"on-tool-use",extent:"partial",reason:"counts tool calls; the token-usage advisory reads Claude Code transcripts only"},{subcommand:"on-shell-write",extent:"none",reason:"not wired for Copilot yet \u2014 files written by a shell command are not checked before the command runs"},{subcommand:"on-shell-changes",extent:"none",reason:"not wired for Copilot yet \u2014 files a shell command changed are not checked after it runs"},LX]},mb="listens to PostToolUseFailure, which this host's hook file has no event for \u2014 a failed shell call arrives in PostToolUse here, and guard-outcome reads it there",FX={codex:[{subcommand:"guard-difficulty",extent:"none",reason:mb},{subcommand:"guard-outcome",extent:"partial",reason:"Codex hands hooks the output but no exit code \u2014 a failed command counts when its output ends in a failure summary (tests, tsc, pnpm, git \u2026), a bare non-zero exit does not; MCP tools are not watched (Codex matches tools by exact name)"}],copilot:[{subcommand:"guard-difficulty",extent:"none",reason:mb},{subcommand:"guard-outcome",extent:"partial",reason:"VS Code: the terminal's exit code from the tool's answer; the Copilot CLI sends a failed call to postToolUseFailure, which is not wired \u2014 there only failures summarised in the output count; MCP tools are not counted"}],gemini:[{subcommand:"guard-difficulty",extent:"none",reason:mb},{subcommand:"guard-outcome",extent:"partial",reason:"run_shell_command only \u2014 MCP tools (mcp_<server>_<tool>) cannot be told apart from maind's own and are not counted"}]};s(jn,"agentHooksFor");s(os,"matcherFor");s(is,"groupByEvent");s(ss,"entryTimeout");s(as,"agentHookConsent")});var YN={};Q(YN,{COPILOT_HOOKS_TARGET:()=>JN,COPILOT_HOOKS_VERSION:()=>np,COPILOT_HOST_FLAG:()=>yb,copilotCommand:()=>ip,copilotCommands:()=>op,copilotHookTarget:()=>gb,copilotHookWiring:()=>_b,copilotHooksDir:()=>rp,copilotHooksPath:()=>cs,copilotPresence:()=>fl,copilotRunsHook:()=>UX,mergeCopilotHooks:()=>us});import*as Er from"node:fs";import*as ls from"node:path";import*as zN from"node:readline";function rp(e){return ls.join(e.homeDir,".copilot","hooks")}function cs(e){return ls.join(rp(e),"maind.json")}function fl(e){return{evidence:[...ka(e).evidence,{kind:"foreign-entries",dir:ls.join(e.homeDir,".copilot"),ours:["instructions","hooks"]}],skipDetail:"Copilot not found (no VS Code app data, nothing of the Copilot CLI's in ~/.copilot)"}}function gb(e){return`hook(${e}):~/.copilot/hooks/maind.json`}function Fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function op(e,t){if(!Fn(e)||!Fn(e.hooks))return[];let n=e.hooks[t];if(!Array.isArray(n))return[];let r=[];for(let o of n)if(Fn(o)){for(let i of["command","bash","powershell"])typeof o[i]=="string"&&r.push(o[i]);if(Array.isArray(o.hooks))for(let i of o.hooks)Fn(i)&&typeof i.command=="string"&&r.push(i.command)}return r}function qN(e){return`'${e.replace(/'/g,"''")}'`}function ip(e,t=process.platform){return t==="win32"?`${Object.entries(e.env).map(([r,o])=>`$env:${r}=${qN(o)}; `).join("")}& ${[e.command,...e.args].map(qN).join(" ")}; exit 0`:`${at(e)} || true`}async function HX(e,t){let n=new Map,r=[];try{r=Er.readdirSync(e).filter(o=>o.toLowerCase().endsWith(".json"))}catch{return n}for(let o of r){let i;try{i=JSON.parse(await W(ls.join(e,o))??"null")}catch{continue}for(let a of t){if(n.has(a.subcommand))continue;let l=op(i,a.event).find(c=>c.includes(a.subcommand));l!==void 0&&n.set(a.subcommand,l)}}return n}async function us(e){let t=cs(e),{hooks:n,gaps:r}=jn("copilot",e.pack??"core"),o=s((v,S,x,T="merge")=>({target:gb(v),action:T,status:S,detail:x}),"row"),i=s(()=>r.map(v=>({target:gb(v.subcommand).replace(/^hook\(/,"gap("),action:"gap",status:"skipped",detail:`${v.extent==="none"?"not wired":"in part"} \u2014 ${v.reason}`})),"gapRows"),a=s((v,S,x="skip")=>[{target:JN,action:x,status:v,detail:S}],"one");if(e.skip)return a("skipped","--no-hook");if(!e.explicit&&!Te(fl(e.presence.ctx),e.presence.probe))return a("skipped",fl(e.presence.ctx).skipDetail);let l;try{l=await W(t)}catch(v){return a("failed",`read: ${hb(v)}`,"merge")}let c=l===null||l.trim().length===0,u={};if(!c){let v;try{v=JSON.parse(l)}catch(S){return a("failed",`parse: ${hb(S)} \u2014 ${t} left untouched`,"merge")}if(!Fn(v))return a("failed",`${t} is not a JSON object \u2014 left untouched`,"merge");if(v.version!==void 0&&v.version!==np)return a("skipped",`${t} has version ${JSON.stringify(v.version)}, not one this bridge knows (${np}) \u2014 left untouched`);if(v.hooks!==void 0&&!Fn(v.hooks))return a("failed",`"hooks" in ${t} is not an object \u2014 left untouched`,"merge");u=v}let d=await HX(rp(e),n),p=e.platform??process.platform,f=e.launchFor??(v=>Ee({entryPath:se(),nodePath:process.execPath,extraArgs:[hn,yb,...v],isElectron:process.versions.electron!==void 0})),m=[],h=[];for(let v of n){let S=d.get(v.subcommand);if(S!==void 0){let x=`Copilot already runs maind ${v.subcommand}`;m.push(o(v.subcommand,"skipped",It(S)?`${x}, but via \`npx\` \u2014 PATH decides which bridge that is`:x,"skip"));continue}if(!e.full){if(!e.isInteractive){m.push(o(v.subcommand,"skipped","consent-required: pass --full to write the hook non-interactively","skip"));continue}if(e.dryRun){m.push(o(v.subcommand,c?"would-create":"would-merge",`${t} (would prompt for consent in real run)`));continue}if(!await(e.prompt??BX)(e.out,`
940
940
  Add Copilot's ${v.label.replace(/ hook$/,"")} hook to ${t}?
941
941
  ${as("copilot",v)}
942
942
  [Y/n]: `)){m.push(o(v.subcommand,"skipped","user declined","skip"));continue}}h.push(v)}if(h.length===0)return[...m,...i()];let g=Fn(u.hooks)?{...u.hooks}:{};for(let{event:v,hooks:S}of is(h)){let x=Array.isArray(g[v])?[...g[v]]:[],T=S.map(L=>L.subcommand),A=os("copilot",S);x.push({type:"command",command:ip(f(T),p),timeout:ss(S),...A!==null?{matcher:A}:{}}),g[v]=x}let _={...u,version:u.version??np,hooks:g},b=s((v,S)=>[...m,...h.map(x=>o(x.subcommand,v,S,c?"write":"merge")),...i()],"done"),k="VS Code: needs chat.useHooks (on by default); the Copilot CLI reads it at its next start";if(e.dryRun)return b(c?"would-create":"would-merge",`${t} \u2014 ${k}`);try{await G(t,JSON.stringify(_,null,2)+`
943
- `)}catch(v){return[...m,...h.map(S=>o(S.subcommand,"failed",`write: ${hb(v)}`)),...i()]}return b(c?"created":"merged",`${t} \u2014 ${k}`)}function _b(e){let t=rp({homeDir:e}),{hooks:n,gaps:r}=jn("copilot"),o=[];try{for(let a of Er.readdirSync(t))if(a.toLowerCase().endsWith(".json"))try{o.push(JSON.parse(Er.readFileSync(ls.join(t,a),"utf8")))}catch{}}catch{}let i=n.filter(a=>o.some(l=>op(l,a.event).some(c=>c.includes(a.subcommand)))).map(a=>a.subcommand);return{wired:i,missing:n.map(a=>a.subcommand).filter(a=>!i.includes(a)),gaps:r.filter(a=>a.extent==="none").map(a=>a.subcommand),file:Er.existsSync(cs({homeDir:e}))}}function FX(e,t){try{let n=JSON.parse(Er.readFileSync(cs({homeDir:e}),"utf8"));return!Fn(n)||!Fn(n.hooks)?!1:Object.keys(n.hooks).some(r=>op(n,r).some(o=>o.includes(yb)&&o.includes(t)))}catch{return!1}}async function HX(e,t){e.write(t);let n=zN.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function hb(e){return e instanceof Error?e.message:String(e)}var yb,np,JN,ds=w(()=>{"use strict";Oe();tp();le();Ze();We();ir();yb="--host=copilot",np=1;s(rp,"copilotHooksDir");s(cs,"copilotHooksPath");s(fl,"copilotPresence");JN="hooks:~/.copilot/hooks/maind.json";s(gb,"copilotHookTarget");s(Fn,"isObject");s(op,"copilotCommands");s(qN,"psQuote");s(ip,"copilotCommand");s(jX,"wiredCommands");s(us,"mergeCopilotHooks");s(_b,"copilotHookWiring");s(FX,"copilotRunsHook");s(HX,"promptYesNo");s(hb,"errMessage")});import{readFileSync as UX}from"node:fs";import*as ZN from"node:readline";function bb(e){switch(e){case"SessionStart":return"maind-session-start";case"BeforeAgent":return"maind-before-agent";case"AfterAgent":return"maind-after-agent";case"AfterTool":return"maind-after-tool"}}function XN(e){return`hook(${e}):~/.gemini/settings.json`}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QN(e,t){if(!gn(e)||!gn(e.hooks))return[];let n=e.hooks[t];if(!Array.isArray(n))return[];let r=[];for(let o of n)if(!(!gn(o)||!Array.isArray(o.hooks)))for(let i of o.hooks)gn(i)&&typeof i.command=="string"&&r.push(i.command);return r}function GX(e,t){if(e.hooks!==void 0&&!gn(e.hooks))return`"hooks" in ${t} is not an object`;if(gn(e.hooks))for(let n of["SessionStart","BeforeAgent","AfterAgent","AfterTool"]){let r=e.hooks[n];if(r!==void 0&&!Array.isArray(r))return`"hooks.${n}" in ${t} is not an array`}return e.hooksConfig!==void 0&&!gn(e.hooksConfig)?`"hooksConfig" in ${t} is not an object`:null}async function ml(e){let t=Ii(e.presence.ctx),{hooks:n,gaps:r}=jn("gemini",e.pack??"core"),o=s((S,x,T,A="merge")=>({target:XN(S),action:A,status:x,detail:T}),"row"),i=s(()=>r.map(S=>({target:XN(S.subcommand).replace(/^hook\(/,"gap("),action:"gap",status:"skipped",detail:`${S.extent==="none"?"not wired":"in part"} \u2014 ${S.reason}`})),"gapRows"),a=s((S,x,T="skip")=>[{target:BX,action:T,status:S,detail:x}],"one");if(e.skip)return a("skipped","--no-hook");if(!e.explicit&&!Te(Oi(e.presence.ctx),e.presence.probe))return a("skipped",Oi(e.presence.ctx).skipDetail);let l;try{l=await W(t)}catch(S){return a("failed",`read: ${kb(S)}`,"merge")}let c=l===null||l.trim().length===0,u={};if(!c){let S;try{S=JSON.parse(l)}catch(T){return a("failed",`parse: ${kb(T)} \u2014 ${t} left untouched (comments are fine for Gemini, not for this writer; add the hooks by hand or remove the comments)`,"merge")}if(!gn(S))return a("failed",`${t} is not a JSON object \u2014 left untouched`,"merge");let x=GX(S,t);if(x!==null)return a("failed",`${x} \u2014 left untouched`,"merge");u=S}let d=gn(u.hooksConfig)?u.hooksConfig:null;if(d!==null&&d.enabled===!1)return[...a("skipped",`hooks are off in Gemini CLI (hooksConfig.enabled: false in ${t}) \u2014 left as you set it`),...i()];let p=new Set(Array.isArray(d?.disabled)?d.disabled.filter(S=>typeof S=="string"):[]),f=e.platform??process.platform,m=e.launchFor??(S=>Ee({entryPath:se(),nodePath:process.execPath,extraArgs:[hn,wb,...S],isElectron:process.versions.electron!==void 0})),h=[],g=[];for(let S of n){let x=ep(S.event);if(x===null)continue;if(p.has(bb(x))){h.push(o(S.subcommand,"skipped",`${bb(x)} is in hooksConfig.disabled \u2014 left as you set it`,"skip"));continue}let T=QN(u,x).find(A=>A.includes(wb)&&A.includes(S.subcommand));if(T!==void 0){let A=`Gemini CLI already runs maind ${S.subcommand}`;h.push(o(S.subcommand,"skipped",It(T)?`${A}, but via \`npx\` \u2014 PATH decides which bridge that is`:A,"skip"));continue}if(!e.full){if(!e.isInteractive){h.push(o(S.subcommand,"skipped","consent-required: pass --full to write the hook non-interactively","skip"));continue}if(e.dryRun){h.push(o(S.subcommand,c?"would-create":"would-merge",`${t} (would prompt for consent in real run)`));continue}if(!await(e.prompt??KX)(e.out,`
943
+ `)}catch(v){return[...m,...h.map(S=>o(S.subcommand,"failed",`write: ${hb(v)}`)),...i()]}return b(c?"created":"merged",`${t} \u2014 ${k}`)}function _b(e){let t=rp({homeDir:e}),{hooks:n,gaps:r}=jn("copilot"),o=[];try{for(let a of Er.readdirSync(t))if(a.toLowerCase().endsWith(".json"))try{o.push(JSON.parse(Er.readFileSync(ls.join(t,a),"utf8")))}catch{}}catch{}let i=n.filter(a=>o.some(l=>op(l,a.event).some(c=>c.includes(a.subcommand)))).map(a=>a.subcommand);return{wired:i,missing:n.map(a=>a.subcommand).filter(a=>!i.includes(a)),gaps:r.filter(a=>a.extent==="none").map(a=>a.subcommand),file:Er.existsSync(cs({homeDir:e}))}}function UX(e,t){try{let n=JSON.parse(Er.readFileSync(cs({homeDir:e}),"utf8"));return!Fn(n)||!Fn(n.hooks)?!1:Object.keys(n.hooks).some(r=>op(n,r).some(o=>o.includes(yb)&&o.includes(t)))}catch{return!1}}async function BX(e,t){e.write(t);let n=zN.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function hb(e){return e instanceof Error?e.message:String(e)}var yb,np,JN,ds=w(()=>{"use strict";Oe();tp();le();Ze();We();ir();yb="--host=copilot",np=1;s(rp,"copilotHooksDir");s(cs,"copilotHooksPath");s(fl,"copilotPresence");JN="hooks:~/.copilot/hooks/maind.json";s(gb,"copilotHookTarget");s(Fn,"isObject");s(op,"copilotCommands");s(qN,"psQuote");s(ip,"copilotCommand");s(HX,"wiredCommands");s(us,"mergeCopilotHooks");s(_b,"copilotHookWiring");s(UX,"copilotRunsHook");s(BX,"promptYesNo");s(hb,"errMessage")});import{readFileSync as GX}from"node:fs";import*as ZN from"node:readline";function bb(e){switch(e){case"SessionStart":return"maind-session-start";case"BeforeAgent":return"maind-before-agent";case"AfterAgent":return"maind-after-agent";case"AfterTool":return"maind-after-tool"}}function XN(e){return`hook(${e}):~/.gemini/settings.json`}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QN(e,t){if(!gn(e)||!gn(e.hooks))return[];let n=e.hooks[t];if(!Array.isArray(n))return[];let r=[];for(let o of n)if(!(!gn(o)||!Array.isArray(o.hooks)))for(let i of o.hooks)gn(i)&&typeof i.command=="string"&&r.push(i.command);return r}function WX(e,t){if(e.hooks!==void 0&&!gn(e.hooks))return`"hooks" in ${t} is not an object`;if(gn(e.hooks))for(let n of["SessionStart","BeforeAgent","AfterAgent","AfterTool"]){let r=e.hooks[n];if(r!==void 0&&!Array.isArray(r))return`"hooks.${n}" in ${t} is not an array`}return e.hooksConfig!==void 0&&!gn(e.hooksConfig)?`"hooksConfig" in ${t} is not an object`:null}async function ml(e){let t=Ii(e.presence.ctx),{hooks:n,gaps:r}=jn("gemini",e.pack??"core"),o=s((S,x,T,A="merge")=>({target:XN(S),action:A,status:x,detail:T}),"row"),i=s(()=>r.map(S=>({target:XN(S.subcommand).replace(/^hook\(/,"gap("),action:"gap",status:"skipped",detail:`${S.extent==="none"?"not wired":"in part"} \u2014 ${S.reason}`})),"gapRows"),a=s((S,x,T="skip")=>[{target:KX,action:T,status:S,detail:x}],"one");if(e.skip)return a("skipped","--no-hook");if(!e.explicit&&!Te(Oi(e.presence.ctx),e.presence.probe))return a("skipped",Oi(e.presence.ctx).skipDetail);let l;try{l=await W(t)}catch(S){return a("failed",`read: ${kb(S)}`,"merge")}let c=l===null||l.trim().length===0,u={};if(!c){let S;try{S=JSON.parse(l)}catch(T){return a("failed",`parse: ${kb(T)} \u2014 ${t} left untouched (comments are fine for Gemini, not for this writer; add the hooks by hand or remove the comments)`,"merge")}if(!gn(S))return a("failed",`${t} is not a JSON object \u2014 left untouched`,"merge");let x=WX(S,t);if(x!==null)return a("failed",`${x} \u2014 left untouched`,"merge");u=S}let d=gn(u.hooksConfig)?u.hooksConfig:null;if(d!==null&&d.enabled===!1)return[...a("skipped",`hooks are off in Gemini CLI (hooksConfig.enabled: false in ${t}) \u2014 left as you set it`),...i()];let p=new Set(Array.isArray(d?.disabled)?d.disabled.filter(S=>typeof S=="string"):[]),f=e.platform??process.platform,m=e.launchFor??(S=>Ee({entryPath:se(),nodePath:process.execPath,extraArgs:[hn,wb,...S],isElectron:process.versions.electron!==void 0})),h=[],g=[];for(let S of n){let x=ep(S.event);if(x===null)continue;if(p.has(bb(x))){h.push(o(S.subcommand,"skipped",`${bb(x)} is in hooksConfig.disabled \u2014 left as you set it`,"skip"));continue}let T=QN(u,x).find(A=>A.includes(wb)&&A.includes(S.subcommand));if(T!==void 0){let A=`Gemini CLI already runs maind ${S.subcommand}`;h.push(o(S.subcommand,"skipped",It(T)?`${A}, but via \`npx\` \u2014 PATH decides which bridge that is`:A,"skip"));continue}if(!e.full){if(!e.isInteractive){h.push(o(S.subcommand,"skipped","consent-required: pass --full to write the hook non-interactively","skip"));continue}if(e.dryRun){h.push(o(S.subcommand,c?"would-create":"would-merge",`${t} (would prompt for consent in real run)`));continue}if(!await(e.prompt??VX)(e.out,`
944
944
  Add Gemini CLI's ${S.label.replace(/ hook$/,"")} hook to ${t}?
945
945
  ${as("gemini",S)}
946
946
  Everything else in settings.json stays as it is. [Y/n]: `)){h.push(o(S.subcommand,"skipped","user declined","skip"));continue}}g.push(S)}if(g.length===0)return[...h,...i()];let _=gn(u.hooks)?{...u.hooks}:{};for(let{event:S,hooks:x}of is(g)){let T=ep(S);if(T===null)continue;let A=Array.isArray(_[T])?[..._[T]]:[],L=os("gemini",x);A.push({...L===null?{}:{matcher:L},hooks:[{name:bb(T),type:"command",command:ip(m(x.map(R=>R.subcommand)),f),timeout:ss(x)*1e3}]}),_[T]=A}let b={...u,hooks:_},k=s((S,x)=>[...h,...g.map(T=>o(T.subcommand,S,x,c?"write":"merge")),...i()],"done"),v="Gemini CLI reads it at its next start";if(e.dryRun)return k(c?"would-create":"would-merge",`${t} \u2014 ${v}`);try{await G(t,JSON.stringify(b,null,2)+`
947
- `)}catch(S){return[...h,...g.map(x=>o(x.subcommand,"failed",`write: ${kb(S)}`)),...i()]}return k(c?"created":"merged",`${t} \u2014 ${v}`)}async function KX(e,t){e.write(t);let n=ZN.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function kb(e){return e instanceof Error?e.message:String(e)}function eD(e){let{hooks:t,gaps:n}=jn("gemini"),r=null;try{r=JSON.parse(UX(Ii(e),"utf8"))}catch{}let o=t.filter(i=>{let a=ep(i.event);return a!==null&&QN(r,a).some(l=>l.includes(wb)&&l.includes(i.subcommand))}).map(i=>i.subcommand);return{wired:o,missing:t.map(i=>i.subcommand).filter(i=>!o.includes(i)),gaps:n.filter(i=>i.extent==="none").map(i=>i.subcommand)}}var wb,BX,sp=w(()=>{"use strict";Oe();tp();le();Ze();We();ds();ir();wb="--host=gemini",BX="hooks:~/.gemini/settings.json";s(bb,"geminiHookName");s(XN,"geminiHookTarget");s(gn,"isObject");s(QN,"geminiCommands");s(GX,"shapeProblem");s(ml,"mergeGeminiHooks");s(KX,"promptYesNo");s(kb,"errMessage");s(eD,"geminiHookWiring")});import{createHash as WX}from"node:crypto";import*as $t from"node:path";import*as nD from"node:readline";function qX(e){return $t.join(e.homeDir,".copilot","instructions","maind.instructions.md")}function zX(e,t){let n=(e.documentsDirs&&e.documentsDirs.length>0?e.documentsDirs:[$t.join(e.homeDir,"Documents")]).map(r=>$t.join(r,"Cline","Rules"));return n.find(r=>t.exists(r))??n[0]}function JX(e){return $t.join(Su(e),"rules","maind.md")}function $o(e,t){return[{id:"copilot",family:"copilot",label:"GitHub Copilot user instructions",path:qX(e),presence:ka(e),frontmatter:["name: maind",`description: ${tD}`,'applyTo: "**"'],loads:'VS Code\'s Copilot chat (and the Copilot CLI) adds to every request in every workspace (`applyTo: "**"`)'},{id:"cline",family:"cline",label:"Cline global rule",path:$t.join(zX(e,t),"maind.md"),presence:Vg(e),frontmatter:null,loads:"Cline loads as an always-active global rule in every workspace"},{id:"continue",family:"continue",label:"Continue global rule",path:JX(e),presence:qg(e),frontmatter:["name: maind",`description: ${tD}`,"alwaysApply: true"],loads:"Continue includes in every workspace (`alwaysApply: true`)"}]}function oD(e){return e==="copilot"||e==="cline"||e==="continue"?e:null}function YX(e,t){return`rules(${e.id}):${XX(e.path,t)}`}function XX(e,t){let n=$t.relative(t,e);return n!==""&&!n.startsWith("..")&&!$t.isAbsolute(n)?`~/${n.split($t.sep).join("/")}`:e}function vb(e,t,n){let r=[];e.frontmatter!==null&&r.push("---",...e.frontmatter,"---"),r.push(VX,"",cn.replace(/\r\n/g,`
947
+ `)}catch(S){return[...h,...g.map(x=>o(x.subcommand,"failed",`write: ${kb(S)}`)),...i()]}return k(c?"created":"merged",`${t} \u2014 ${v}`)}async function VX(e,t){e.write(t);let n=ZN.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function kb(e){return e instanceof Error?e.message:String(e)}function eD(e){let{hooks:t,gaps:n}=jn("gemini"),r=null;try{r=JSON.parse(GX(Ii(e),"utf8"))}catch{}let o=t.filter(i=>{let a=ep(i.event);return a!==null&&QN(r,a).some(l=>l.includes(wb)&&l.includes(i.subcommand))}).map(i=>i.subcommand);return{wired:o,missing:t.map(i=>i.subcommand).filter(i=>!o.includes(i)),gaps:n.filter(i=>i.extent==="none").map(i=>i.subcommand)}}var wb,KX,sp=w(()=>{"use strict";Oe();tp();le();Ze();We();ds();ir();wb="--host=gemini",KX="hooks:~/.gemini/settings.json";s(bb,"geminiHookName");s(XN,"geminiHookTarget");s(gn,"isObject");s(QN,"geminiCommands");s(WX,"shapeProblem");s(ml,"mergeGeminiHooks");s(VX,"promptYesNo");s(kb,"errMessage");s(eD,"geminiHookWiring")});import{createHash as qX}from"node:crypto";import*as $t from"node:path";import*as nD from"node:readline";function JX(e){return $t.join(e.homeDir,".copilot","instructions","maind.instructions.md")}function YX(e,t){let n=(e.documentsDirs&&e.documentsDirs.length>0?e.documentsDirs:[$t.join(e.homeDir,"Documents")]).map(r=>$t.join(r,"Cline","Rules"));return n.find(r=>t.exists(r))??n[0]}function XX(e){return $t.join(Su(e),"rules","maind.md")}function $o(e,t){return[{id:"copilot",family:"copilot",label:"GitHub Copilot user instructions",path:JX(e),presence:ka(e),frontmatter:["name: maind",`description: ${tD}`,'applyTo: "**"'],loads:'VS Code\'s Copilot chat (and the Copilot CLI) adds to every request in every workspace (`applyTo: "**"`)'},{id:"cline",family:"cline",label:"Cline global rule",path:$t.join(YX(e,t),"maind.md"),presence:Vg(e),frontmatter:null,loads:"Cline loads as an always-active global rule in every workspace"},{id:"continue",family:"continue",label:"Continue global rule",path:XX(e),presence:qg(e),frontmatter:["name: maind",`description: ${tD}`,"alwaysApply: true"],loads:"Continue includes in every workspace (`alwaysApply: true`)"}]}function oD(e){return e==="copilot"||e==="cline"||e==="continue"?e:null}function ZX(e,t){return`rules(${e.id}):${QX(e.path,t)}`}function QX(e,t){let n=$t.relative(t,e);return n!==""&&!n.startsWith("..")&&!$t.isAbsolute(n)?`~/${n.split($t.sep).join("/")}`:e}function vb(e,t,n){let r=[];e.frontmatter!==null&&r.push("---",...e.frontmatter,"---"),r.push(zX,"",cn.replace(/\r\n/g,`
948
948
  `).trimEnd(),"","### Project conventions","");let o=t.repo??"no repository (organization- and user-wide only)",i=(t.conventions??"").replace(/\r\n/g,`
949
- `).trim();return i.length===0?r.push(`Conventions for ${o}: not loaded yet \u2014 the bridge fills them on the next session start or refresh.`):(r.push(`Conventions for ${o}, refreshed ${ZX(n.nowMs)} (mcp-bridge ${n.bridgeVersion}).`,""),r.push(my(i,fy).text)),r.join(`
949
+ `).trim();return i.length===0?r.push(`Conventions for ${o}: not loaded yet \u2014 the bridge fills them on the next session start or refresh.`):(r.push(`Conventions for ${o}, refreshed ${e6(n.nowMs)} (mcp-bridge ${n.bridgeVersion}).`,""),r.push(my(i,fy).text)),r.join(`
950
950
  `)+`
951
- `}function ZX(e){return new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}function fs(e){let t=e.replace(/^/,"").split(/\r?\n/),n=0;if(t[0]?.trim()==="---"){let r=t.findIndex((o,i)=>i>0&&o.trim()==="---");if(r<0)return!1;n=r+1}for(;n<t.length&&t[n].trim()==="";)n++;return n<t.length&&t[n].trim().startsWith(rD)}function ps(e){return e.replace(/\r\n/g,`
951
+ `}function e6(e){return new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}function fs(e){let t=e.replace(/^/,"").split(/\r?\n/),n=0;if(t[0]?.trim()==="---"){let r=t.findIndex((o,i)=>i>0&&o.trim()==="---");if(r<0)return!1;n=r+1}for(;n<t.length&&t[n].trim()==="";)n++;return n<t.length&&t[n].trim().startsWith(rD)}function ps(e){return e.replace(/\r\n/g,`
952
952
  `).split(`
953
953
  `).map(t=>t.replace(/^(Conventions for .+?), refreshed .*$/,"$1")).join(`
954
- `)}function hl(e){return WX("sha256").update(ps(e)).digest("hex")}function QX(e){return`It writes ${e.path}, a file of the bridge's own that ${e.loads}: the MAIND consultation triggers and the project conventions of the repository you work in, under a line that names that repository and when it was refreshed. The bridge keeps it current \u2014 when a session of this client starts, and when the MAIND extension reports a workspace switch (maind-mcp-bridge refresh-rules) \u2014, at most every 12 h per repository and only when the conventions changed (MAIND_NO_RULES_REFRESH=1 stops that). The conventions come from the same local cache as the session-start hook (~/.maind/guard/briefing-cache.json); a refresh may fetch them from mcp.maind.dev (API key, device id, project key \u2014 never file contents or paths). Nothing is written into your repository. A file of that name without the maind marker is yours and is left untouched.`}async function e6(e,t){let n=YX(t,e.homeDir),r=s((o,i,a="write")=>({target:n,action:a,status:o,detail:i}),"row");if(e.skip)return r("skipped","--no-rules","skip");if(e.explicitFamily!==t.family&&!Te(t.presence,e.probe))return r("skipped",t.presence.skipDetail,"skip");try{let o=await W(t.path);if(o!==null&&!fs(o))return r("skipped",`${t.path} is yours (no maind marker) \u2014 left as it is`,"skip");let i=await e.content(),a=vb(t,i,{nowMs:e.nowMs??Date.now(),bridgeVersion:e.bridgeVersion??K});if(o!==null)return ps(o)===ps(a)?(e.dryRun||await e.onChecked?.(t.path,o),r("skipped","already up to date","skip")):e.dryRun?r("would-merge",`${t.path} (would refresh)`,"merge"):(await G(t.path,a),await e.onChecked?.(t.path,a),r("merged",`${t.path} (refreshed)`,"merge"));if(!e.full){if(!e.isInteractive)return r("skipped","consent-required: pass --full to write it non-interactively","skip");if(e.dryRun)return r("would-create",`${t.path} (would prompt for consent in real run)`);if(!await(e.prompt??t6)(e.out,`
954
+ `)}function hl(e){return qX("sha256").update(ps(e)).digest("hex")}function t6(e){return`It writes ${e.path}, a file of the bridge's own that ${e.loads}: the MAIND consultation triggers and the project conventions of the repository you work in, under a line that names that repository and when it was refreshed. The bridge keeps it current \u2014 when a session of this client starts, and when the MAIND extension reports a workspace switch (maind-mcp-bridge refresh-rules) \u2014, at most every 12 h per repository and only when the conventions changed (MAIND_NO_RULES_REFRESH=1 stops that). The conventions come from the same local cache as the session-start hook (~/.maind/guard/briefing-cache.json); a refresh may fetch them from mcp.maind.dev (API key, device id, project key \u2014 never file contents or paths). Nothing is written into your repository. A file of that name without the maind marker is yours and is left untouched.`}async function n6(e,t){let n=ZX(t,e.homeDir),r=s((o,i,a="write")=>({target:n,action:a,status:o,detail:i}),"row");if(e.skip)return r("skipped","--no-rules","skip");if(e.explicitFamily!==t.family&&!Te(t.presence,e.probe))return r("skipped",t.presence.skipDetail,"skip");try{let o=await W(t.path);if(o!==null&&!fs(o))return r("skipped",`${t.path} is yours (no maind marker) \u2014 left as it is`,"skip");let i=await e.content(),a=vb(t,i,{nowMs:e.nowMs??Date.now(),bridgeVersion:e.bridgeVersion??K});if(o!==null)return ps(o)===ps(a)?(e.dryRun||await e.onChecked?.(t.path,o),r("skipped","already up to date","skip")):e.dryRun?r("would-merge",`${t.path} (would refresh)`,"merge"):(await G(t.path,a),await e.onChecked?.(t.path,a),r("merged",`${t.path} (refreshed)`,"merge"));if(!e.full){if(!e.isInteractive)return r("skipped","consent-required: pass --full to write it non-interactively","skip");if(e.dryRun)return r("would-create",`${t.path} (would prompt for consent in real run)`);if(!await(e.prompt??r6)(e.out,`
955
955
  Write the ${t.label} ${t.path}?
956
- ${QX(t)}
957
- [Y/n]: `))return r("skipped","user declined","skip")}return e.dryRun?r("would-create",t.path):(await G(t.path,a),await e.onChecked?.(t.path,a),r("created",t.path))}catch(o){return r("failed",o instanceof Error?o.message:String(o))}}async function Sb(e,t){let n=[];for(let r of t)n.push(await e6(e,r));return n}async function t6(e,t){e.write(t);let n=nD.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var rD,VX,tD,ap=w(()=>{"use strict";Lu();Xe();Pi();le();We();We();ir();rD="<!-- maind:rules v1",VX=`${rD} \xB7 written by maind-mcp-bridge (ADR-364): the bridge rewrites this file when it refreshes \u2014 do not edit by hand -->`;s(qX,"copilotInstructionsPath");s(zX,"clineRulesDir");s(JX,"continueRulesPath");tD="MAIND consultation triggers and the project conventions of the repository you work in";s($o,"ruleChannels");s(oD,"ruleChannelIdForFamily");s(YX,"rulesTargetKey");s(XX,"tildify");s(vb,"renderRulesFile");s(ZX,"stamp");s(fs,"isOurRulesFile");s(ps,"canonicalRulesContent");s(hl,"rulesContentHash");s(QX,"ruleConsentDescription");s(e6,"mergeRuleChannel");s(Sb,"mergeRuleChannels");s(t6,"promptYesNo")});function sD(e){let t=Nt(e);if(!("value"in t))return null;let n=t.value;if(!ne(n.mcp_servers)||!ne(n.mcp_servers.maind))return null;let r=$C(e,{token:lD});if(r.kind!=="write")return{action:"manual",next:null,stays:iD(n,e),removes:["[mcp_servers.maind]"]};let o=Nt(r.next),i="value"in o?iD(o.value,r.next):[],a=Sa(r.next);return a!==null&&a.statements.every(c=>c.kind==="blank")?{action:"delete",next:null,stays:[],removes:r.removed}:{action:"edit",next:r.next,stays:i,removes:r.removed}}function iD(e,t){let n=ne(e.mcp_servers)?Object.keys(e.mcp_servers).filter(a=>a!=="maind").length:0,r=Object.keys(e).filter(a=>a!=="mcp_servers"),o=Sa(t),i=o===null||o.statements.some(a=>a.kind==="comment"||(a.kind==="keyval"||a.kind==="header")&&a.comment!==null);return[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[],...i?["comments"]:[]]}var aD=w(()=>{"use strict";Pu();Cu();Ia();ms();s(sD,"planTomlPhantomRemoval");s(iD,"foreign")});import{findNodeAtLocation as n6,parse as cD,parseTree as r6,stripComments as o6}from"jsonc-parser";function uD(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||tb(n)===null)continue;if(n.kind==="toml"){let f=i6(n,n.raw);f!==null&&t.push(f);continue}let r=[],o=cD(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!xb(o))continue;let i=xb(o.servers)&&"maind"in o.servers?"servers":"mcpServers",a=o[i];if(!xb(a)||!("maind"in a))continue;let l=Object.keys(a).filter(f=>f!=="maind").length,c=Object.keys(o).filter(f=>f!==i),u=o6(n.raw)!==n.raw;if(l===0&&c.length===0&&!u){t.push({label:n.label,path:n.path,action:"delete",raw:n.raw,next:null,keeps:null});continue}let d=[...l>0?[`${l} other server${l===1?"":"s"}`]:[],...c.length>0?[`keys ${c.join(", ")}`]:[],...u?["comments"]:[]].join(", "),p=s6(n.raw,[i,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${i}.maind by hand \u2014 it cannot be cut out cleanly; stays: ${d}`}:{label:n.label,path:n.path,action:"edit",raw:n.raw,next:p,keeps:`remove ${i}.maind; stays: ${d}`})}return t}function i6(e,t){let n=sD(t);if(n===null)return null;let r={label:e.label,path:e.path,raw:t},o=n.stays.length>0?`; stays: ${n.stays.join(", ")}`:"",i=n.removes.join(", ");switch(n.action){case"delete":return{...r,action:"delete",next:null,keeps:null};case"edit":return{...r,action:"edit",next:n.next,keeps:`remove ${i}${o}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove ${i} by hand \u2014 it cannot be cut out cleanly${o}`}}}function s6(e,t){let n=r6(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:n6(n,[...t])?.parent,o=r?.parent?.children;if(r===void 0||r.type!=="property"||o===void 0)return null;let i=o.indexOf(r),a=r.offset,l=r.offset+r.length;if(i+1<o.length)l=o[i+1].offset;else if(i>0){let d=o[i-1];a=d.offset+d.length}else{let d=r.parent;d!==void 0&&e.slice(d.offset+1,r.offset).trim()===""&&(a=d.offset+1);let p=/^\s*,/.exec(e.slice(l));p&&(l+=p[0].length)}let c=e.slice(0,a)+e.slice(l),u=[];return cD(c,u,{allowTrailingComma:!0}),u.length===0?c:null}function dD(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
956
+ ${t6(t)}
957
+ [Y/n]: `))return r("skipped","user declined","skip")}return e.dryRun?r("would-create",t.path):(await G(t.path,a),await e.onChecked?.(t.path,a),r("created",t.path))}catch(o){return r("failed",o instanceof Error?o.message:String(o))}}async function Sb(e,t){let n=[];for(let r of t)n.push(await n6(e,r));return n}async function r6(e,t){e.write(t);let n=nD.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var rD,zX,tD,ap=w(()=>{"use strict";Lu();Xe();Pi();le();We();We();ir();rD="<!-- maind:rules v1",zX=`${rD} \xB7 written by maind-mcp-bridge (ADR-364): the bridge rewrites this file when it refreshes \u2014 do not edit by hand -->`;s(JX,"copilotInstructionsPath");s(YX,"clineRulesDir");s(XX,"continueRulesPath");tD="MAIND consultation triggers and the project conventions of the repository you work in";s($o,"ruleChannels");s(oD,"ruleChannelIdForFamily");s(ZX,"rulesTargetKey");s(QX,"tildify");s(vb,"renderRulesFile");s(e6,"stamp");s(fs,"isOurRulesFile");s(ps,"canonicalRulesContent");s(hl,"rulesContentHash");s(t6,"ruleConsentDescription");s(n6,"mergeRuleChannel");s(Sb,"mergeRuleChannels");s(r6,"promptYesNo")});function sD(e){let t=Nt(e);if(!("value"in t))return null;let n=t.value;if(!ne(n.mcp_servers)||!ne(n.mcp_servers.maind))return null;let r=$C(e,{token:lD});if(r.kind!=="write")return{action:"manual",next:null,stays:iD(n,e),removes:["[mcp_servers.maind]"]};let o=Nt(r.next),i="value"in o?iD(o.value,r.next):[],a=Sa(r.next);return a!==null&&a.statements.every(c=>c.kind==="blank")?{action:"delete",next:null,stays:[],removes:r.removed}:{action:"edit",next:r.next,stays:i,removes:r.removed}}function iD(e,t){let n=ne(e.mcp_servers)?Object.keys(e.mcp_servers).filter(a=>a!=="maind").length:0,r=Object.keys(e).filter(a=>a!=="mcp_servers"),o=Sa(t),i=o===null||o.statements.some(a=>a.kind==="comment"||(a.kind==="keyval"||a.kind==="header")&&a.comment!==null);return[...n>0?[`${n} other server${n===1?"":"s"}`]:[],...r.length>0?[`keys ${r.join(", ")}`]:[],...i?["comments"]:[]]}var aD=w(()=>{"use strict";Pu();Cu();Ia();ms();s(sD,"planTomlPhantomRemoval");s(iD,"foreign")});import{findNodeAtLocation as o6,parse as cD,parseTree as i6,stripComments as s6}from"jsonc-parser";function uD(e){let t=[];for(let n of e){if(n.present!==!1||n.raw===null||tb(n)===null)continue;if(n.kind==="toml"){let f=a6(n,n.raw);f!==null&&t.push(f);continue}let r=[],o=cD(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!xb(o))continue;let i=xb(o.servers)&&"maind"in o.servers?"servers":"mcpServers",a=o[i];if(!xb(a)||!("maind"in a))continue;let l=Object.keys(a).filter(f=>f!=="maind").length,c=Object.keys(o).filter(f=>f!==i),u=s6(n.raw)!==n.raw;if(l===0&&c.length===0&&!u){t.push({label:n.label,path:n.path,action:"delete",raw:n.raw,next:null,keeps:null});continue}let d=[...l>0?[`${l} other server${l===1?"":"s"}`]:[],...c.length>0?[`keys ${c.join(", ")}`]:[],...u?["comments"]:[]].join(", "),p=l6(n.raw,[i,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${i}.maind by hand \u2014 it cannot be cut out cleanly; stays: ${d}`}:{label:n.label,path:n.path,action:"edit",raw:n.raw,next:p,keeps:`remove ${i}.maind; stays: ${d}`})}return t}function a6(e,t){let n=sD(t);if(n===null)return null;let r={label:e.label,path:e.path,raw:t},o=n.stays.length>0?`; stays: ${n.stays.join(", ")}`:"",i=n.removes.join(", ");switch(n.action){case"delete":return{...r,action:"delete",next:null,keeps:null};case"edit":return{...r,action:"edit",next:n.next,keeps:`remove ${i}${o}`};case"manual":return{...r,action:"manual",next:null,keeps:`remove ${i} by hand \u2014 it cannot be cut out cleanly${o}`}}}function l6(e,t){let n=i6(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:o6(n,[...t])?.parent,o=r?.parent?.children;if(r===void 0||r.type!=="property"||o===void 0)return null;let i=o.indexOf(r),a=r.offset,l=r.offset+r.length;if(i+1<o.length)l=o[i+1].offset;else if(i>0){let d=o[i-1];a=d.offset+d.length}else{let d=r.parent;d!==void 0&&e.slice(d.offset+1,r.offset).trim()===""&&(a=d.offset+1);let p=/^\s*,/.exec(e.slice(l));p&&(l+=p[0].length)}let c=e.slice(0,a)+e.slice(l),u=[];return cD(c,u,{allowTrailingComma:!0}),u.length===0?c:null}function dD(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
958
958
  `;let n=["Configs that name maind for a client that is not installed \u2014 nothing reads them:",""];for(let r of e)n.push(` ${r.action.padEnd(6)} ${r.path}`),n.push(` ${r.label} \u2014 ${r.action==="delete"?"holds nothing but maind's entry":r.keeps}`);return n.push(""),n.push(t?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --remove-phantoms --yes"),n.join(`
959
959
  `)+`
960
- `}function xb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var pD=w(()=>{"use strict";Nd();aD();s(uD,"planPhantomRemovals");s(i6,"tomlRemoval");s(s6,"withoutProperty");s(dD,"renderPhantomPlan");s(xb,"isObject")});import{execFileSync as a6}from"node:child_process";import{existsSync as l6,readFileSync as c6,realpathSync as u6}from"node:fs";import{dirname as d6,join as p6,relative as fD,resolve as f6}from"node:path";function Eb(e){try{return l6(e)?c6(e,"utf8"):null}catch{return null}}function m6(e){try{let t=a6("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function mD(e){try{return u6(e)}catch{return f6(e)}}function hs(e,t={}){let n=mD(e),r=(t.toplevel??m6)(n),o=r===null?null:mD(r),i=t.read??Eb,a=o??n,l=[];if(o===null)l.push(n);else{let u=n;for(let d=0;d<64;d++){l.push(u);let p=fD(o,u);if(p===""||p.startsWith(".."))break;let f=d6(u);if(f===u)break;u=f}l.includes(o)||l.push(o)}let c=[];for(let u of l)for(let d of NO){let p=p6(u,d),f=i(p);if(f===null)continue;let m=PO(fD(a,p).split("\\").join("/")||d,p,f);m!==null&&c.push(m)}return{root:a,inRepo:o!==null,plans:c}}var lp=w(()=>{"use strict";al();s(Eb,"readOrNull");s(m6,"gitToplevelSync");s(mD,"realOrResolve");s(hs,"scanRepoBlocks")});function cp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function h6(e){for(let t of $e)if(new RegExp(`(^|[\\s/"'])${t.subcommand}(\\s|$|["'])`).test(e)||t.supersedes!==void 0&&t.supersedes.replaceable.test(e))return t.subcommand;return null}function hD(e,t){if(e===null||e.trim().length===0)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!cp(n)||!cp(n.hooks))return null;let r=[],o={};for(let[a,l]of Object.entries(n.hooks)){if(!Array.isArray(l)){o[a]=l;continue}let c=[];for(let u of l){if(!cp(u)||!Array.isArray(u.hooks)){c.push(u);continue}let d=u.hooks.filter(p=>{if(!cp(p)||typeof p.command!="string")return!0;let f=h6(p.command);return f===null?!0:(r.push({event:a,subcommand:f,command:p.command}),!1)});d.length===u.hooks.length?c.push(u):d.length>0&&c.push({...u,hooks:d})}(c.length>0||l.length===0)&&(o[a]=c)}if(r.length===0)return null;let i={...n};return Object.keys(o).length>0?i.hooks=o:delete i.hooks,{file:t,raw:e,next:JSON.stringify(i,null,2)+`
960
+ `}function xb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var pD=w(()=>{"use strict";Nd();aD();s(uD,"planPhantomRemovals");s(a6,"tomlRemoval");s(l6,"withoutProperty");s(dD,"renderPhantomPlan");s(xb,"isObject")});import{execFileSync as c6}from"node:child_process";import{existsSync as u6,readFileSync as d6,realpathSync as p6}from"node:fs";import{dirname as f6,join as m6,relative as fD,resolve as h6}from"node:path";function Eb(e){try{return u6(e)?d6(e,"utf8"):null}catch{return null}}function g6(e){try{let t=c6("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function mD(e){try{return p6(e)}catch{return h6(e)}}function hs(e,t={}){let n=mD(e),r=(t.toplevel??g6)(n),o=r===null?null:mD(r),i=t.read??Eb,a=o??n,l=[];if(o===null)l.push(n);else{let u=n;for(let d=0;d<64;d++){l.push(u);let p=fD(o,u);if(p===""||p.startsWith(".."))break;let f=f6(u);if(f===u)break;u=f}l.includes(o)||l.push(o)}let c=[];for(let u of l)for(let d of NO){let p=m6(u,d),f=i(p);if(f===null)continue;let m=PO(fD(a,p).split("\\").join("/")||d,p,f);m!==null&&c.push(m)}return{root:a,inRepo:o!==null,plans:c}}var lp=w(()=>{"use strict";al();s(Eb,"readOrNull");s(g6,"gitToplevelSync");s(mD,"realOrResolve");s(hs,"scanRepoBlocks")});function cp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function y6(e){for(let t of $e)if(new RegExp(`(^|[\\s/"'])${t.subcommand}(\\s|$|["'])`).test(e)||t.supersedes!==void 0&&t.supersedes.replaceable.test(e))return t.subcommand;return null}function hD(e,t){if(e===null||e.trim().length===0)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!cp(n)||!cp(n.hooks))return null;let r=[],o={};for(let[a,l]of Object.entries(n.hooks)){if(!Array.isArray(l)){o[a]=l;continue}let c=[];for(let u of l){if(!cp(u)||!Array.isArray(u.hooks)){c.push(u);continue}let d=u.hooks.filter(p=>{if(!cp(p)||typeof p.command!="string")return!0;let f=y6(p.command);return f===null?!0:(r.push({event:a,subcommand:f,command:p.command}),!1)});d.length===u.hooks.length?c.push(u):d.length>0&&c.push({...u,hooks:d})}(c.length>0||l.length===0)&&(o[a]=c)}if(r.length===0)return null;let i={...n};return Object.keys(o).length>0?i.hooks=o:delete i.hooks,{file:t,raw:e,next:JSON.stringify(i,null,2)+`
961
961
  `,removed:r}}function gD(e,t,n){return n?e===null?`No bridge hooks in settings.json next to the maind plugin \u2014 the plugin runs them.
962
962
  `:[`The maind plugin is enabled, and ${e.file} still wires the bridge's own hooks \u2014 the plugin's copies stand down for them, so these run instead:`,"",...e.removed.map(o=>` remove ${o.event.padEnd(18)} ${o.subcommand}`),"",t?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --remove-duplicate-hooks --yes"].join(`
963
963
  `)+`
964
964
  `:`The maind plugin is not enabled \u2014 the hooks in settings.json are the ones Claude Code runs; nothing to remove.
965
- `}var yD=w(()=>{"use strict";Le();s(cp,"isObject");s(h6,"ourSubcommand");s(hD,"planDuplicateHookRemoval");s(gD,"renderDuplicateHooksPlan")});var kD={};Q(kD,{renderMigrationPlan:()=>bD,runMigrateRepoBlocks:()=>k6});import{unlinkSync as g6}from"node:fs";import{homedir as y6,platform as _D}from"node:os";function bD(e,t,n){let r=[],o=e.plans.filter(i=>i.action!=="keep");r.push(`maind blocks an earlier install wrote into ${e.root} (ADR-364):`,"");for(let i of o)r.push(` ${i.action.padEnd(6)} ${i.rel}`),i.action==="manual"?r.push(` ${i.keeps.join("; ")} \u2014 remove it by hand`):i.action==="delete"?r.push(` holds nothing but ${i.removes.join(" and ")} \u2014 the file goes`):r.push(` remove ${i.removes.join(" and ")}${i.keeps.length>0?`; stays: ${i.keeps.join(", ")}`:""}`);for(let i of e.plans.filter(a=>a.action==="keep"))r.push(` keep ${i.rel}`,` ${i.keeps.join(", ")} \u2014 the team option stays`);r.push("","Set up first, so nothing is lost (user level, for the clients installed here):","");for(let i of t)r.push(` ${b6(i).padEnd(6)} ${i.target}${i.detail?` \u2014 ${i.detail}`:""}`);return r.push(""),r.push(n?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --migrate-repo-blocks --yes"),r.join(`
965
+ `}var yD=w(()=>{"use strict";Le();s(cp,"isObject");s(y6,"ourSubcommand");s(hD,"planDuplicateHookRemoval");s(gD,"renderDuplicateHooksPlan")});var kD={};Q(kD,{renderMigrationPlan:()=>bD,runMigrateRepoBlocks:()=>v6});import{unlinkSync as _6}from"node:fs";import{homedir as b6,platform as _D}from"node:os";function bD(e,t,n){let r=[],o=e.plans.filter(i=>i.action!=="keep");r.push(`maind blocks an earlier install wrote into ${e.root} (ADR-364):`,"");for(let i of o)r.push(` ${i.action.padEnd(6)} ${i.rel}`),i.action==="manual"?r.push(` ${i.keeps.join("; ")} \u2014 remove it by hand`):i.action==="delete"?r.push(` holds nothing but ${i.removes.join(" and ")} \u2014 the file goes`):r.push(` remove ${i.removes.join(" and ")}${i.keeps.length>0?`; stays: ${i.keeps.join(", ")}`:""}`);for(let i of e.plans.filter(a=>a.action==="keep"))r.push(` keep ${i.rel}`,` ${i.keeps.join(", ")} \u2014 the team option stays`);r.push("","Set up first, so nothing is lost (user level, for the clients installed here):","");for(let i of t)r.push(` ${w6(i).padEnd(6)} ${i.target}${i.detail?` \u2014 ${i.detail}`:""}`);return r.push(""),r.push(n?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --migrate-repo-blocks --yes"),r.join(`
966
966
  `)+`
967
- `}function b6(e){switch(e.status){case"would-create":case"created":return"add";case"would-merge":case"merged":return"update";case"failed":return"failed";default:return e.detail!==void 0&&/already|up to date/.test(e.detail)?"ok":"skip"}}async function k6(e,t={}){let n=t.out??process.stdout,r=t.cwd??process.cwd(),o=(t.scan??hs)(r);if(o===null||o.plans.length===0)return n.write(`No maind blocks in ${o?.root??r} \u2014 nothing to migrate.
967
+ `}function w6(e){switch(e.status){case"would-create":case"created":return"add";case"would-merge":case"merged":return"update";case"failed":return"failed";default:return e.detail!==void 0&&/already|up to date/.test(e.detail)?"ok":"skip"}}async function v6(e,t={}){let n=t.out??process.stdout,r=t.cwd??process.cwd(),o=(t.scan??hs)(r);if(o===null||o.plans.length===0)return n.write(`No maind blocks in ${o?.root??r} \u2014 nothing to migrate.
968
968
  `),0;if(!No(o.plans))return n.write(`Only the team conventions block (install --team) in ${o.root} \u2014 it stays; nothing to migrate.
969
- `),0;let i=t.setUpChannels??(u=>w6(u,t.homeDir??y6(),r,n));if(n.write(bD(o,await i(!0),e)),!e)return 0;let a=await i(!1),l=a.filter(u=>u.status==="failed");for(let u of a.filter(d=>d.status==="created"||d.status==="merged"))n.write(` set up ${u.target}
969
+ `),0;let i=t.setUpChannels??(u=>S6(u,t.homeDir??b6(),r,n));if(n.write(bD(o,await i(!0),e)),!e)return 0;let a=await i(!1),l=a.filter(u=>u.status==="failed");for(let u of a.filter(d=>d.status==="created"||d.status==="merged"))n.write(` set up ${u.target}
970
970
  `);if(l.length>0){for(let u of l){n.write(` failed ${u.target}: ${u.detail??"unknown error"}
971
971
  `);for(let d of u.manual??[])n.write(d===""?`
972
972
  `:` ${d}
973
973
  `)}return n.write(`Nothing was removed \u2014 a channel could not be set up, and removing the blocks first would lose them.
974
974
  `),1}let c=0;for(let u of o.plans)if(u.action!=="keep"){if(u.action==="manual"){n.write(` left ${u.rel} \u2014 remove the maind section by hand
975
975
  `);continue}if(Eb(u.path)!==u.raw){n.write(` skipped ${u.rel} \u2014 changed since it was read
976
- `),c++;continue}try{u.action==="delete"?g6(u.path):await G(u.path,u.next??u.raw),n.write(` ${u.action==="delete"?"deleted":"edited "} ${u.rel}
976
+ `),c++;continue}try{u.action==="delete"?_6(u.path):await G(u.path,u.next??u.raw),n.write(` ${u.action==="delete"?"deleted":"edited "} ${u.rel}
977
977
  `)}catch(d){n.write(` failed ${u.rel}: ${d instanceof Error?d.message:String(d)}
978
978
  `),c++}}return n.write(`Commit the changed files when you are ready; your user-level channels carry the same content from now on.
979
- `),c>0?1:0}async function w6(e,t,n,r){let o={homeDir:t,isInteractive:!1,full:!0,skip:!1,dryRun:e,out:r},i=[],a=_t(bt(t,process.env,_D()));if(a.enabled)i.push({target:Tb,action:"skip",status:"skipped",detail:cd(a)});else for(let l of _6)i.push(await Da(o,l));return i.push(...await Ab(o,{ctx:qt({projectRoot:n,homeDir:t,platform:_D(),env:process.env,bridgeEntry:se()}),probe:fe,noRules:!1,cwd:n})),i}var _6,wD=w(()=>{"use strict";le();Ze();We();Ku();Le();Rb();Ui();al();lp();_6=$e.filter(e=>e.subcommand===Nn||e.subcommand===ce);s(bD,"renderMigrationPlan");s(b6,"channelVerb");s(k6,"runMigrateRepoBlocks");s(w6,"defaultChannelSetup")});var AD={};Q(AD,{channelProbe:()=>TD,contextProbe:()=>ED,realProbe:()=>yl,resolveNvmAlias:()=>xD,runDoctor:()=>F6});import{execFileSync as v6}from"node:child_process";import{existsSync as gl,readFileSync as S6,readdirSync as Cb,realpathSync as x6,statSync as E6,unlinkSync as T6}from"node:fs";import{homedir as yn,platform as Lo}from"node:os";import{delimiter as A6,dirname as vD,join as Ae}from"node:path";function Ye(e){try{return gl(e)?S6(e,"utf8"):null}catch{return null}}function R6(){try{let e=v6(Lo()==="win32"?"npm.cmd":"npm",["view",SD,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function Ib(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:Ae(yn(),".nvm")}function C6(){let e=Ae(Ib(),"versions","node"),t=[];try{t=Cb(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Ye(Ae(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),o=null;try{o=r?JSON.parse(r).version??null:null}catch{o=null}return{node:n,bridgeVersion:o}})}function xD(e,t,n){let r=e.trim();for(let l=0;l<5;l++){let c=n(r);if(c===null)break;r=c.trim()}let o=[...t].sort((l,c)=>{let u=l.slice(1).split(".").map(Number),d=c.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(u[p]!==d[p])return(u[p]??0)-(d[p]??0);return 0});if(r==="node"||r==="stable")return o.at(-1)??null;let i=r.startsWith("v")?r:`v${r}`;if(t.includes(i))return i;let a=i.endsWith(".")?i:`${i}.`;return o.filter(l=>l.startsWith(a)).at(-1)??null}function I6(e){let t=Ye(Ae(Ib(),"alias","default"));return t===null?null:xD(t,e.map(n=>n.node),n=>{let r=Ye(Ae(Ib(),"alias",n));return r===null?null:r})}function O6(){let e=Lo()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(A6))if(t)for(let n of e){let r=Ae(t,n);if(gl(r)){let o=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:o?o[1]:null,path:r}}}return null}function N6(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Lo()==="win32"?Ae(process.env.LOCALAPPDATA??Ae(yn(),"AppData","Local"),"npm-cache"):Ae(yn(),".npm"),t=Ae(e,"_npx"),n=[],r=[];try{r=Cb(t)}catch{return[]}for(let o of r)try{let i=Cb(Ae(t,o,"node_modules"));i.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:Ae(t,o),maind:i.includes("@maind-dev")})}catch{}return n}function D6(e){let t;try{t=vD(x6(e))}catch{return null}for(let n=0;n<6;n++){let r=Ye(Ae(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===SD)return i.version??null}catch{}let o=vD(t);if(o===t)break;t=o}return null}function ED(e){let t=pr(e),n=!1;try{let o=Ye(Pd);n=o!==null&&typeof JSON.parse(o).conventions=="string"}catch{n=!1}let r=Qd();return{repoRoot:t,indexPresent:t!==null&&gl(Ae(t,dr)),conventionsCached:n||t!==null&&gl(Ae(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function yl(e=process.cwd(),t={}){let n=C6(),r=Ye(Ae(Vt(),"device-id")),o=qt({projectRoot:e,homeDir:yn(),platform:Lo(),env:process.env,bridgeEntry:se()}),i=null;try{i=ee()}catch{i=null}let a=(process.env.MAIND_API_KEY??"").trim(),l=re(),c=Ee({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:K,latestVersion:t.offline===!0?null:R6(),nodeTrees:n,nvmDefault:I6(n),pathWinner:O6(),clientConfigs:wa(o).map(u=>({key:u.key,label:u.label,path:u.path,kind:u.kind,raw:Ye(u.path),present:u.presence===void 0?null:Te(u.presence,fe)})),npxStaleDirs:N6(),connection:$R(),claudeSettings:Ye(Ae(yn(),".claude","settings.json")),fileExists:s(u=>gl(u),"fileExists"),installVersionOf:D6,deviceId:r===null?null:r.trim(),apiKey:i,envApiKey:a.length>0?a:null,guardMode:Se(process.env,l).mode,declinedHooks:l?.declined_hooks??[],bridgeCommand:c.fallbackReason===null?at(c):null,context:t.offline===!0?null:ED(e),foreignHookHosts:M6(o),repoBlocks:t.offline===!0?null:P6(e),channels:t.offline===!0?[]:TD(o),plugin:_t(bt(yn(),process.env,Lo()))}}function P6(e){try{return hs(e)}catch{return null}}function TD(e){let t=[];try{if(Te(Ci(e),fe)){let n=bo(e),r=up(Ye(n),Ye(Ae(rr(e),"hooks.json")));t.push({client:"codex",label:"Codex hooks",path:n,state:r.wired.length===0?"missing":"ok",hooks:r})}if(Te(fl(e),fe)){let n=_b(e.homeDir);t.push({client:"copilot",label:"Copilot hooks",path:cs(e),state:n.wired.length===0?"missing":"ok",hooks:n})}if(Te(Oi(e),fe)){let n=eD(e);t.push({client:"gemini-cli",label:"Gemini CLI hooks",path:Ii(e),state:n.wired.length===0?"missing":"ok",hooks:n})}for(let n of $o(e,fe)){if(!Te(n.presence,fe))continue;let r=Ye(n.path);t.push({client:n.id,label:n.label,path:n.path,state:r===null?"missing":fs(r)?"ok":"foreign"})}}catch{}return t}function M6(e){let t=[];try{Te(Cn(e),fe)&&t.push("cursor"),Te(wu(e),fe)&&t.push("devin")}catch{}return t}async function $6(e){let t=uD(yl(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(dD(t,e)),!e)return 0;let n=0;for(let r of t){if(r.action==="manual"){process.stdout.write(` left ${r.path} \u2014 remove the maind entry by hand
979
+ `),c>0?1:0}async function S6(e,t,n,r){let o={homeDir:t,isInteractive:!1,full:!0,skip:!1,dryRun:e,out:r},i=[],a=_t(bt(t,process.env,_D()));if(a.enabled)i.push({target:Tb,action:"skip",status:"skipped",detail:cd(a)});else for(let l of k6)i.push(await Da(o,l));return i.push(...await Ab(o,{ctx:qt({projectRoot:n,homeDir:t,platform:_D(),env:process.env,bridgeEntry:se()}),probe:fe,noRules:!1,cwd:n})),i}var k6,wD=w(()=>{"use strict";le();Ze();We();Ku();Le();Rb();Ui();al();lp();k6=$e.filter(e=>e.subcommand===Nn||e.subcommand===ce);s(bD,"renderMigrationPlan");s(w6,"channelVerb");s(v6,"runMigrateRepoBlocks");s(S6,"defaultChannelSetup")});var AD={};Q(AD,{channelProbe:()=>TD,contextProbe:()=>ED,realProbe:()=>yl,resolveNvmAlias:()=>xD,runDoctor:()=>U6});import{execFileSync as x6}from"node:child_process";import{existsSync as gl,readFileSync as E6,readdirSync as Cb,realpathSync as T6,statSync as A6,unlinkSync as R6}from"node:fs";import{homedir as yn,platform as Lo}from"node:os";import{delimiter as C6,dirname as vD,join as Ae}from"node:path";function Ye(e){try{return gl(e)?E6(e,"utf8"):null}catch{return null}}function I6(){try{let e=x6(Lo()==="win32"?"npm.cmd":"npm",["view",SD,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function Ib(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:Ae(yn(),".nvm")}function O6(){let e=Ae(Ib(),"versions","node"),t=[];try{t=Cb(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Ye(Ae(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),o=null;try{o=r?JSON.parse(r).version??null:null}catch{o=null}return{node:n,bridgeVersion:o}})}function xD(e,t,n){let r=e.trim();for(let l=0;l<5;l++){let c=n(r);if(c===null)break;r=c.trim()}let o=[...t].sort((l,c)=>{let u=l.slice(1).split(".").map(Number),d=c.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(u[p]!==d[p])return(u[p]??0)-(d[p]??0);return 0});if(r==="node"||r==="stable")return o.at(-1)??null;let i=r.startsWith("v")?r:`v${r}`;if(t.includes(i))return i;let a=i.endsWith(".")?i:`${i}.`;return o.filter(l=>l.startsWith(a)).at(-1)??null}function N6(e){let t=Ye(Ae(Ib(),"alias","default"));return t===null?null:xD(t,e.map(n=>n.node),n=>{let r=Ye(Ae(Ib(),"alias",n));return r===null?null:r})}function D6(){let e=Lo()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(C6))if(t)for(let n of e){let r=Ae(t,n);if(gl(r)){let o=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:o?o[1]:null,path:r}}}return null}function P6(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:Lo()==="win32"?Ae(process.env.LOCALAPPDATA??Ae(yn(),"AppData","Local"),"npm-cache"):Ae(yn(),".npm"),t=Ae(e,"_npx"),n=[],r=[];try{r=Cb(t)}catch{return[]}for(let o of r)try{let i=Cb(Ae(t,o,"node_modules"));i.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:Ae(t,o),maind:i.includes("@maind-dev")})}catch{}return n}function M6(e){let t;try{t=vD(T6(e))}catch{return null}for(let n=0;n<6;n++){let r=Ye(Ae(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===SD)return i.version??null}catch{}let o=vD(t);if(o===t)break;t=o}return null}function ED(e){let t=pr(e),n=!1;try{let o=Ye(Pd);n=o!==null&&typeof JSON.parse(o).conventions=="string"}catch{n=!1}let r=Qd();return{repoRoot:t,indexPresent:t!==null&&gl(Ae(t,dr)),conventionsCached:n||t!==null&&gl(Ae(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function yl(e=process.cwd(),t={}){let n=O6(),r=Ye(Ae(Vt(),"device-id")),o=qt({projectRoot:e,homeDir:yn(),platform:Lo(),env:process.env,bridgeEntry:se()}),i=null;try{i=ee()}catch{i=null}let a=(process.env.MAIND_API_KEY??"").trim(),l=re(),c=Ee({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:K,latestVersion:t.offline===!0?null:I6(),nodeTrees:n,nvmDefault:N6(n),pathWinner:D6(),clientConfigs:wa(o).map(u=>({key:u.key,label:u.label,path:u.path,kind:u.kind,raw:Ye(u.path),present:u.presence===void 0?null:Te(u.presence,fe)})),npxStaleDirs:P6(),connection:$R(),claudeSettings:Ye(Ae(yn(),".claude","settings.json")),fileExists:s(u=>gl(u),"fileExists"),installVersionOf:M6,deviceId:r===null?null:r.trim(),apiKey:i,envApiKey:a.length>0?a:null,guardMode:Se(process.env,l).mode,declinedHooks:l?.declined_hooks??[],bridgeCommand:c.fallbackReason===null?at(c):null,context:t.offline===!0?null:ED(e),foreignHookHosts:L6(o),repoBlocks:t.offline===!0?null:$6(e),channels:t.offline===!0?[]:TD(o),plugin:_t(bt(yn(),process.env,Lo()))}}function $6(e){try{return hs(e)}catch{return null}}function TD(e){let t=[];try{if(Te(Ci(e),fe)){let n=bo(e),r=up(Ye(n),Ye(Ae(rr(e),"hooks.json")));t.push({client:"codex",label:"Codex hooks",path:n,state:r.wired.length===0?"missing":"ok",hooks:r})}if(Te(fl(e),fe)){let n=_b(e.homeDir);t.push({client:"copilot",label:"Copilot hooks",path:cs(e),state:n.wired.length===0?"missing":"ok",hooks:n})}if(Te(Oi(e),fe)){let n=eD(e);t.push({client:"gemini-cli",label:"Gemini CLI hooks",path:Ii(e),state:n.wired.length===0?"missing":"ok",hooks:n})}for(let n of $o(e,fe)){if(!Te(n.presence,fe))continue;let r=Ye(n.path);t.push({client:n.id,label:n.label,path:n.path,state:r===null?"missing":fs(r)?"ok":"foreign"})}}catch{}return t}function L6(e){let t=[];try{Te(Cn(e),fe)&&t.push("cursor"),Te(wu(e),fe)&&t.push("devin")}catch{}return t}async function j6(e){let t=uD(yl(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(dD(t,e)),!e)return 0;let n=0;for(let r of t){if(r.action==="manual"){process.stdout.write(` left ${r.path} \u2014 remove the maind entry by hand
980
980
  `);continue}if(Ye(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
981
- `),n++;continue}try{r.action==="delete"?T6(r.path):await G(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
981
+ `),n++;continue}try{r.action==="delete"?R6(r.path):await G(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
982
982
  `)}catch(o){process.stdout.write(` failed ${r.path}: ${o instanceof Error?o.message:String(o)}
983
- `),n++}}return n>0?1:0}async function L6(e){let t=Ae(yn(),".claude","settings.json"),n=_t(bt(yn(),process.env,Lo())),r=Ye(t),o=n.enabled?hD(r,t):null;if(process.stdout.write(gD(o,e,n.enabled)),!e||o===null)return 0;if(Ye(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
983
+ `),n++}}return n>0?1:0}async function F6(e){let t=Ae(yn(),".claude","settings.json"),n=_t(bt(yn(),process.env,Lo())),r=Ye(t),o=n.enabled?hD(r,t):null;if(process.stdout.write(gD(o,e,n.enabled)),!e||o===null)return 0;if(Ye(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
984
984
  `),1;try{return await G(t,o.next,384),process.stdout.write(` edited ${t} \u2014 ${o.removed.length} hook entr${o.removed.length===1?"y":"ies"} removed
985
985
  `),0}catch(i){return process.stdout.write(` failed ${t}: ${i instanceof Error?i.message:String(i)}
986
- `),1}}async function j6(e){let t=Ae(yn(),".claude.json"),n=_t(bt(yn(),process.env,Lo())),r=Ye(t),o=n.enabled?IO(r,t):null;if(process.stdout.write(OO(o,e,n.enabled)),!e||o===null)return 0;if(Ye(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
987
- `),1;try{let i;try{i=E6(t).mode&511}catch{i=384}return await G(t,o.next,i),process.stdout.write(` edited ${t} \u2014 removed ${o.removed.map(a=>a.join(".")).join(", ")}
986
+ `),1}}async function H6(e){let t=Ae(yn(),".claude.json"),n=_t(bt(yn(),process.env,Lo())),r=Ye(t),o=n.enabled?IO(r,t):null;if(process.stdout.write(OO(o,e,n.enabled)),!e||o===null)return 0;if(Ye(t)!==o.raw)return process.stdout.write(` skipped ${t} \u2014 changed since it was read
987
+ `),1;try{let i;try{i=A6(t).mode&511}catch{i=384}return await G(t,o.next,i),process.stdout.write(` edited ${t} \u2014 removed ${o.removed.map(a=>a.join(".")).join(", ")}
988
988
  `),0}catch(i){return process.stdout.write(` failed ${t}: ${i instanceof Error?i.message:String(i)}
989
- `),1}}async function F6(e){if(e.includes("--remove-phantoms"))return $6(e.includes("--yes"));if(e.includes("--remove-duplicate-hooks"))return L6(e.includes("--yes"));if(e.includes("--remove-duplicate-mcp"))return j6(e.includes("--yes"));if(e.includes("--migrate-repo-blocks")){let{runMigrateRepoBlocks:n}=await Promise.resolve().then(()=>(wD(),kD));return n(e.includes("--yes"))}let t=Od(yl());return e.includes("--json")?process.stdout.write(JSON.stringify({version:K,findings:t},null,2)+`
990
- `):process.stdout.write(LO(t)),t.some(n=>n.level==="error")?1:0}var SD,Ob=w(()=>{"use strict";Ce();Gg();Po();ld();xr();we();Zt();Ze();le();We();ir();ms();ds();sp();ap();Xe();Nd();pD();lp();yD();X_();Ui();SD="@maind-dev/mcp-bridge";s(Ye,"readOrNull");s(R6,"latestVersion");s(Ib,"nvmDir");s(C6,"nodeTrees");s(xD,"resolveNvmAlias");s(I6,"nvmDefault");s(O6,"pathWinner");s(N6,"npxStaleDirs");s(D6,"installVersionOf");s(ED,"contextProbe");s(yl,"realProbe");s(P6,"safeScan");s(TD,"channelProbe");s(M6,"foreignHookHosts");s($6,"removePhantoms");s(L6,"removeDuplicateHooks");s(j6,"removeDuplicateMcp");s(F6,"runDoctor")});import{createHash as H6}from"node:crypto";import{mkdirSync as U6,readFileSync as B6,renameSync as G6,writeFileSync as K6}from"node:fs";import{dirname as W6,join as V6}from"node:path";function z6(e){try{let t=JSON.parse(B6(e,"utf8"));if(t&&typeof t.repos=="object"&&t.repos!==null){let n={};for(let[r,o]of Object.entries(t.repos))typeof o=="string"&&(n[r]=o);return{version:1,repos:n}}}catch{}return{version:1,repos:{}}}function J6(e,t){U6(W6(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;K6(n,JSON.stringify(t,null,2),{mode:384}),G6(n,e)}function Y6(e){return`[maind] setup note \u2014 this repository still carries the maind blocks earlier installs wrote into it: ${Id(e.plans)}. The bridge no longer writes into repositories (ADR-364); this session gets the same hint and conventions from its hooks and user-level files, and the blocks stay effective until you remove them. To list them (and, after a look, remove them with --yes), run in a terminal: maind-mcp-bridge doctor --migrate-repo-blocks (or npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks).`}function RD(e,t={}){try{let n=(t.scan??hs)(e);if(n===null||!n.inRepo||!No(n.plans))return null;let r=t.stateFile??q6,o=z6(r),i=H6("sha256").update(n.root).digest("hex");return o.repos[i]!==void 0?null:(o.repos[i]=new Date(t.nowMs??Date.now()).toISOString(),J6(r,o),Y6(n))}catch{return null}}var q6,CD=w(()=>{"use strict";Je();al();lp();q6=V6(he,"repo-blocks-notice.json");s(z6,"readNoticeState");s(J6,"writeNoticeState");s(Y6,"repoBlocksNoticeText");s(RD,"repoBlocksNotice")});import{mkdirSync as X6,readFileSync as Z6,renameSync as Q6,writeFileSync as e3}from"node:fs";import{dirname as t3,join as n3}from"node:path";function o3(e){try{let t=JSON.parse(Z6(e,"utf8"));if(t&&typeof t.told=="object"&&t.told!==null){let n={};for(let[r,o]of Object.entries(t.told))if(o&&typeof o=="object"&&typeof o.at=="string"){let i=Array.isArray(o.named)?o.named.filter(a=>typeof a=="string"):[];n[r]={at:o.at,named:i}}return{version:1,told:n}}}catch{}return{version:1,told:{}}}function i3(e,t){X6(t3(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;e3(n,JSON.stringify(t,null,2),{mode:384}),Q6(n,e)}function OD(e,t=[]){let n=e.filter(o=>o.status==="missing"&&o.subcommand!==ce).filter(o=>!t.includes(o.subcommand)).map(o=>o.subcommand),r=e.filter(o=>o.status==="superseded"&&o.remedy==="run-install").filter(o=>!t.includes(o.subcommand)).map(o=>o.subcommand);return{missing:n,superseded:r}}function ID(e){let t=$e.find(n=>n.subcommand===e);return t===void 0?e:`${e} (${t.label})`}function s3(e,t){let{missing:n,superseded:r}=OD(e,t.declined??[]);if(n.length===0&&r.length===0)return null;let o=[];return n.length>0&&o.push(`bridge ${t.bridgeVersion} can run ${n.length===1?"a core hook":"core hooks"} that ~/.claude/settings.json does not wire: ${n.map(ID).join(", ")}. Updating the bridge replaces the binary and never adds a hook entry, so ${n.length===1?"it stays":"they stay"} off until added`),r.length>0&&o.push(`the ${r.map(ID).join(", ")} still ${r.length===1?"runs":"run"} the old form an earlier install wrote, which the same command replaces`),`[maind] setup gap \u2014 ${o.join("; ")}. To add ${n.length>0?n.length===1?"it":"them":"the replacement"}, run in a terminal (asks consent per hook, rewrites no entry of yours but that old form): ${t.bridgeCommand} install --hooks-only. This line comes once per bridge version; \`maind-mcp-bridge doctor\` lists the gap any time.`}function ND(e,t){try{let n=s3(e,t);if(n===null)return null;let r=t.stateFile??r3,o=o3(r);if(o.told[t.bridgeVersion]!==void 0)return null;let{missing:i,superseded:a}=OD(e,t.declined??[]);return o.told[t.bridgeVersion]={at:new Date(t.nowMs??Date.now()).toISOString(),named:[...i,...a]},i3(r,o),n}catch{return null}}var r3,DD=w(()=>{"use strict";Je();Le();r3=n3(he,"hook-wiring-notice.json");s(o3,"readNoticeState");s(i3,"writeNoticeState");s(OD,"wiringNoticeSubjects");s(ID,"labelOf");s(s3,"hookWiringNoticeText");s(ND,"hookWiringNotice")});var UD={};Q(UD,{EDIT_MOMENT_FINDINGS:()=>Nb,METRIC_REPO_HEALTH_FINDINGS:()=>$D,METRIC_REPO_HEALTH_RUNS:()=>MD,alreadySeen:()=>jD,formatRepoHealth:()=>LD,markSeen:()=>FD,nearestExistingDir:()=>jo,repoHealthCore:()=>dp,repoHealthForEdit:()=>HD,runOnRepoHealth:()=>Db});import{existsSync as a3,realpathSync as l3,statSync as c3}from"node:fs";import{dirname as PD,isAbsolute as u3,join as d3}from"node:path";function LD(e,t){let n=e.filter(o=>Nb.includes(o.id));if(n.length===0)return null;let r=n.map(o=>{let i=o.hint?`
989
+ `),1}}async function U6(e){if(e.includes("--remove-phantoms"))return j6(e.includes("--yes"));if(e.includes("--remove-duplicate-hooks"))return F6(e.includes("--yes"));if(e.includes("--remove-duplicate-mcp"))return H6(e.includes("--yes"));if(e.includes("--migrate-repo-blocks")){let{runMigrateRepoBlocks:n}=await Promise.resolve().then(()=>(wD(),kD));return n(e.includes("--yes"))}let t=Od(yl());return e.includes("--json")?process.stdout.write(JSON.stringify({version:K,findings:t},null,2)+`
990
+ `):process.stdout.write(LO(t)),t.some(n=>n.level==="error")?1:0}var SD,Ob=w(()=>{"use strict";Ce();Gg();Po();ld();xr();we();Zt();Ze();le();We();ir();ms();ds();sp();ap();Xe();Nd();pD();lp();yD();X_();Ui();SD="@maind-dev/mcp-bridge";s(Ye,"readOrNull");s(I6,"latestVersion");s(Ib,"nvmDir");s(O6,"nodeTrees");s(xD,"resolveNvmAlias");s(N6,"nvmDefault");s(D6,"pathWinner");s(P6,"npxStaleDirs");s(M6,"installVersionOf");s(ED,"contextProbe");s(yl,"realProbe");s($6,"safeScan");s(TD,"channelProbe");s(L6,"foreignHookHosts");s(j6,"removePhantoms");s(F6,"removeDuplicateHooks");s(H6,"removeDuplicateMcp");s(U6,"runDoctor")});import{createHash as B6}from"node:crypto";import{mkdirSync as G6,readFileSync as K6,renameSync as W6,writeFileSync as V6}from"node:fs";import{dirname as q6,join as z6}from"node:path";function Y6(e){try{let t=JSON.parse(K6(e,"utf8"));if(t&&typeof t.repos=="object"&&t.repos!==null){let n={};for(let[r,o]of Object.entries(t.repos))typeof o=="string"&&(n[r]=o);return{version:1,repos:n}}}catch{}return{version:1,repos:{}}}function X6(e,t){G6(q6(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;V6(n,JSON.stringify(t,null,2),{mode:384}),W6(n,e)}function Z6(e){return`[maind] setup note \u2014 this repository still carries the maind blocks earlier installs wrote into it: ${Id(e.plans)}. The bridge no longer writes into repositories (ADR-364); this session gets the same hint and conventions from its hooks and user-level files, and the blocks stay effective until you remove them. To list them (and, after a look, remove them with --yes), run in a terminal: maind-mcp-bridge doctor --migrate-repo-blocks (or npx -y @maind-dev/mcp-bridge doctor --migrate-repo-blocks).`}function RD(e,t={}){try{let n=(t.scan??hs)(e);if(n===null||!n.inRepo||!No(n.plans))return null;let r=t.stateFile??J6,o=Y6(r),i=B6("sha256").update(n.root).digest("hex");return o.repos[i]!==void 0?null:(o.repos[i]=new Date(t.nowMs??Date.now()).toISOString(),X6(r,o),Z6(n))}catch{return null}}var J6,CD=w(()=>{"use strict";Je();al();lp();J6=z6(he,"repo-blocks-notice.json");s(Y6,"readNoticeState");s(X6,"writeNoticeState");s(Z6,"repoBlocksNoticeText");s(RD,"repoBlocksNotice")});import{mkdirSync as Q6,readFileSync as e3,renameSync as t3,writeFileSync as n3}from"node:fs";import{dirname as r3,join as o3}from"node:path";function s3(e){try{let t=JSON.parse(e3(e,"utf8"));if(t&&typeof t.told=="object"&&t.told!==null){let n={};for(let[r,o]of Object.entries(t.told))if(o&&typeof o=="object"&&typeof o.at=="string"){let i=Array.isArray(o.named)?o.named.filter(a=>typeof a=="string"):[];n[r]={at:o.at,named:i}}return{version:1,told:n}}}catch{}return{version:1,told:{}}}function a3(e,t){Q6(r3(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;n3(n,JSON.stringify(t,null,2),{mode:384}),t3(n,e)}function OD(e,t=[]){let n=e.filter(o=>o.status==="missing"&&o.subcommand!==ce).filter(o=>!t.includes(o.subcommand)).map(o=>o.subcommand),r=e.filter(o=>o.status==="superseded"&&o.remedy==="run-install").filter(o=>!t.includes(o.subcommand)).map(o=>o.subcommand);return{missing:n,superseded:r}}function ID(e){let t=$e.find(n=>n.subcommand===e);return t===void 0?e:`${e} (${t.label})`}function l3(e,t){let{missing:n,superseded:r}=OD(e,t.declined??[]);if(n.length===0&&r.length===0)return null;let o=[];return n.length>0&&o.push(`bridge ${t.bridgeVersion} can run ${n.length===1?"a core hook":"core hooks"} that ~/.claude/settings.json does not wire: ${n.map(ID).join(", ")}. Updating the bridge replaces the binary and never adds a hook entry, so ${n.length===1?"it stays":"they stay"} off until added`),r.length>0&&o.push(`the ${r.map(ID).join(", ")} still ${r.length===1?"runs":"run"} the old form an earlier install wrote, which the same command replaces`),`[maind] setup gap \u2014 ${o.join("; ")}. To add ${n.length>0?n.length===1?"it":"them":"the replacement"}, run in a terminal (asks consent per hook, rewrites no entry of yours but that old form): ${t.bridgeCommand} install --hooks-only. This line comes once per bridge version; \`maind-mcp-bridge doctor\` lists the gap any time.`}function ND(e,t){try{let n=l3(e,t);if(n===null)return null;let r=t.stateFile??i3,o=s3(r);if(o.told[t.bridgeVersion]!==void 0)return null;let{missing:i,superseded:a}=OD(e,t.declined??[]);return o.told[t.bridgeVersion]={at:new Date(t.nowMs??Date.now()).toISOString(),named:[...i,...a]},a3(r,o),n}catch{return null}}var i3,DD=w(()=>{"use strict";Je();Le();i3=o3(he,"hook-wiring-notice.json");s(s3,"readNoticeState");s(a3,"writeNoticeState");s(OD,"wiringNoticeSubjects");s(ID,"labelOf");s(l3,"hookWiringNoticeText");s(ND,"hookWiringNotice")});var UD={};Q(UD,{EDIT_MOMENT_FINDINGS:()=>Nb,METRIC_REPO_HEALTH_FINDINGS:()=>$D,METRIC_REPO_HEALTH_RUNS:()=>MD,alreadySeen:()=>jD,formatRepoHealth:()=>LD,markSeen:()=>FD,nearestExistingDir:()=>jo,repoHealthCore:()=>dp,repoHealthForEdit:()=>HD,runOnRepoHealth:()=>Db});import{existsSync as c3,realpathSync as u3,statSync as d3}from"node:fs";import{dirname as PD,isAbsolute as p3,join as f3}from"node:path";function LD(e,t){let n=e.filter(o=>Nb.includes(o.id));if(n.length===0)return null;let r=n.map(o=>{let i=o.hint?`
991
991
  \u2192 ${o.hint}`:"";return` \u2022 ${o.title}
992
992
  ${o.detail}${i}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
993
993
 
@@ -995,21 +995,21 @@ ${QX(t)}
995
995
 
996
996
  `)+`
997
997
 
998
- This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function jD(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function FD(e,t,n,r=Date.now()){let o=e.repo_health_seen??{},i=o[t]??{};i[n]=new Date(r).toISOString(),o[t]=i,e.repo_health_seen=o}function jo(e){let t=PD(e);for(;;){try{if(c3(t).isDirectory())return t}catch{}let n=PD(t);if(n===t)return t;t=n}}async function HD(e,t,n){let r=await n.load();if(jD(r,e,t))return null;FD(r,e,t,n.now?.()),await n.save(r);let o;try{o=await n.check(t)}catch{return null}let i=o.filter(l=>Nb.includes(l.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:MD,metric_value:1},{session_id:e,metric_key:$D,metric_value:i}),await n.save(a),LD(o,t)}async function Db(){return ve(["on-repo-health"])}async function dp(e,t){let n=Mt(e).find(d=>d.act!=="read");if(n===void 0||!me(t,{kind:"context",event:"PreToolUse"}))return null;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return null;let o=n.path,i=be(e,t),a=u3(o)?o:d3(i,o),l=a3(a)?l3(a):mn(a),c=gt(jo(l));try{sd()&&Y0(c,{memoryPath:Hi})}catch{}let u=await HD(r,c,{load:ue,save:un,check:s(async d=>(await Zs(d,{includeRelease:!1})).findings,"check")});return u===null?null:{kind:"context",event:"PreToolUse",text:u}}var Nb,MD,$D,_l=w(()=>{"use strict";Me();Wt();ad();Oe();Ie();tt();il();ut();Nb=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],MD="repo_health_hook_runs",$D="repo_health_hook_findings";s(LD,"formatRepoHealth");s(jD,"alreadySeen");s(FD,"markSeen");s(jo,"nearestExistingDir");s(HD,"repoHealthForEdit");s(Db,"runOnRepoHealth");s(dp,"repoHealthCore")});var XD={};Q(XD,{METRIC_WRITE_HEALTH_FINDINGS:()=>VD,METRIC_WRITE_HEALTH_RUNS:()=>WD,formatWriteHealth:()=>YD,routesAreEmpty:()=>zD,routesForPath:()=>qD,runOnWriteHealth:()=>Pb,takeUnreported:()=>JD,writeHealthCore:()=>Mb});import{existsSync as p3,readFileSync as f3,realpathSync as m3}from"node:fs";import{isAbsolute as GD,join as KD,posix as h3,relative as g3,sep as y3}from"node:path";function BD(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function qD(e,t,n=[]){return{contracts:t.filter(o=>BD(o.spec)===e||BD(o.impl)===e).map(o=>o.id),theme:_3.test(e),acl:b3.test(e),mockupSets:Dh(e,n)}}function zD(e){return e.contracts.length===0&&!e.theme&&!e.acl&&e.mockupSets.length===0}function JD(e,t,n,r,o=Date.now()){let i=e.write_health_seen??{},a=i[t]??{},l=new Set(a[n]?.keys??[]),c=r.filter(u=>!l.has(u.key));if(c.length>0){for(let u of c)l.add(u.key);a[n]={at:new Date(o).toISOString(),keys:[...l]},i[t]=a,e.write_health_seen=i}return c}function YD(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
998
+ This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function jD(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function FD(e,t,n,r=Date.now()){let o=e.repo_health_seen??{},i=o[t]??{};i[n]=new Date(r).toISOString(),o[t]=i,e.repo_health_seen=o}function jo(e){let t=PD(e);for(;;){try{if(d3(t).isDirectory())return t}catch{}let n=PD(t);if(n===t)return t;t=n}}async function HD(e,t,n){let r=await n.load();if(jD(r,e,t))return null;FD(r,e,t,n.now?.()),await n.save(r);let o;try{o=await n.check(t)}catch{return null}let i=o.filter(l=>Nb.includes(l.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:MD,metric_value:1},{session_id:e,metric_key:$D,metric_value:i}),await n.save(a),LD(o,t)}async function Db(){return ve(["on-repo-health"])}async function dp(e,t){let n=Mt(e).find(d=>d.act!=="read");if(n===void 0||!me(t,{kind:"context",event:"PreToolUse"}))return null;let r=typeof e.session_id=="string"?e.session_id:"";if(!r)return null;let o=n.path,i=be(e,t),a=p3(o)?o:f3(i,o),l=c3(a)?u3(a):mn(a),c=gt(jo(l));try{sd()&&Y0(c,{memoryPath:Hi})}catch{}let u=await HD(r,c,{load:ue,save:un,check:s(async d=>(await Zs(d,{includeRelease:!1})).findings,"check")});return u===null?null:{kind:"context",event:"PreToolUse",text:u}}var Nb,MD,$D,_l=w(()=>{"use strict";Me();Wt();ad();Oe();Ie();tt();il();ut();Nb=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],MD="repo_health_hook_runs",$D="repo_health_hook_findings";s(LD,"formatRepoHealth");s(jD,"alreadySeen");s(FD,"markSeen");s(jo,"nearestExistingDir");s(HD,"repoHealthForEdit");s(Db,"runOnRepoHealth");s(dp,"repoHealthCore")});var XD={};Q(XD,{METRIC_WRITE_HEALTH_FINDINGS:()=>VD,METRIC_WRITE_HEALTH_RUNS:()=>WD,formatWriteHealth:()=>YD,routesAreEmpty:()=>zD,routesForPath:()=>qD,runOnWriteHealth:()=>Pb,takeUnreported:()=>JD,writeHealthCore:()=>Mb});import{existsSync as m3,readFileSync as h3,realpathSync as g3}from"node:fs";import{isAbsolute as GD,join as KD,posix as y3,relative as _3,sep as b3}from"node:path";function BD(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function qD(e,t,n=[]){return{contracts:t.filter(o=>BD(o.spec)===e||BD(o.impl)===e).map(o=>o.id),theme:k3.test(e),acl:w3.test(e),mockupSets:Dh(e,n)}}function zD(e){return e.contracts.length===0&&!e.theme&&!e.acl&&e.mockupSets.length===0}function JD(e,t,n,r,o=Date.now()){let i=e.write_health_seen??{},a=i[t]??{},l=new Set(a[n]?.keys??[]),c=r.filter(u=>!l.has(u.key));if(c.length>0){for(let u of c)l.add(u.key);a[n]={at:new Date(o).toISOString(),keys:[...l]},i[t]=a,e.write_health_seen=i}return c}function YD(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
999
999
 
1000
1000
  `+e.map(n=>` \u2022 ${n.line}`).join(`
1001
1001
  `)+`
1002
1002
 
1003
- Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function k3(e,t){let n=g3(e,t);return!n||n.startsWith("..")||GD(n)?null:n.split(y3).join(h3.sep)}function w3(e){try{let t=f3(KD(e,Pc),"utf8"),{manifest:n}=jc(t);return n?.contracts??[]}catch{return[]}}async function Pb(){return ve(["on-write-health"])}async function Mb(e,t){try{let n=Mt(e).find(g=>g.act!=="read");if(n===void 0||!me(t,{kind:"context",event:"PostToolUse"}))return null;let r=typeof e.session_id=="string"?e.session_id:"",o=n.path;if(!r||!o)return null;let i=be(e,t),a=GD(o)?o:KD(i,o),l=p3(a)?m3(a):mn(a),c=gt(jo(l)),u=k3(c,l);if(u===null)return null;let d=qD(u,w3(c),Ph(c));if(zD(d))return null;let p=[];if(d.contracts.length>0)try{let g=await ao(c,{contracts:d.contracts});for(let _ of g.findings)_.status==="open"&&p.push({key:`spec:${_.id}`,line:`spec-drift (${_.contract}): ${_.detail}`})}catch{}if(d.theme)try{let g=po(c);for(let _ of g.findings)_.status==="open"&&p.push({key:`theme:${_.file}:${_.klass}`,line:`theme-class-drift: \`${_.klass}\` in ${_.file} \u2014 no token \`--color-${_.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=uo(c);for(let _ of g.findings)_.status==="open"&&p.push({key:`acl:${_.id}`,line:_.rule==="dead_policy"?`table-acl-lint: \`${_.table}\` has a policy for ${_.deadPolicies.map(b=>`${b.role} ${b.command}`).join(", ")} but no matching GRANT \u2014 the caller gets 42501 before RLS runs; grant the command or drop the policy.`:_.rule==="service_role_undecided"?`table-acl-lint: \`${_.table}\` (created in ${_.createdIn}) never names service_role in a GRANT or REVOKE \u2014 since Supabase's 2026-10-30 switch a new table gives the service key nothing; grant it or revoke it explicitly.`:`table-acl-lint: \`${_.table}\` (created in ${_.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}if(d.mockupSets.length>0)try{let g=ca(c,{sets:d.mockupSets});for(let _ of g.findings)_.status!=="open"&&_.status!=="warn"||p.push({key:`mockup:${_.id}`,line:`mockup-label-drift: ${_.title}`})}catch{}let f=await ue(),m=JD(f,r,c,p);f.pending_metrics.push({session_id:r,metric_key:WD,metric_value:1},{session_id:r,metric_key:VD,metric_value:m.length}),await un(f);let h=YD(m,u);return h===null?null:{kind:"context",event:"PostToolUse",text:h}}catch{return null}}var WD,VD,_3,b3,pp=w(()=>{"use strict";Me();Wt();Oe();Ie();tt();_l();il();ut();WD="write_health_hook_runs",VD="write_health_hook_findings",_3=/\.(tsx?|jsx?|css)$/,b3=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(BD,"declPath");s(qD,"routesForPath");s(zD,"routesAreEmpty");s(JD,"takeUnreported");s(YD,"formatWriteHealth");s(k3,"repoRelative");s(w3,"readContracts");s(Pb,"runOnWriteHealth");s(Mb,"writeHealthCore")});var gs={};Q(gs,{agentHostPidCandidates:()=>Fe,closeSessionMetrics:()=>gp,closeTrackedSession:()=>rP,editRootOf:()=>sP,effectiveConfig:()=>Tr,fileEditCore:()=>hp,fileWriteCore:()=>Hb,flushSessionMetrics:()=>yp,grandparentPid:()=>lP,hookClientFamily:()=>iP,isCaptureTool:()=>jb,isShellCommand:()=>cP,recordGuardSignals:()=>nP,refreshIdentityOnPrompt:()=>Fb,runFlush:()=>B3,runHookStatus:()=>G3,runOnFileEdit:()=>j3,runOnFileWrite:()=>L3,runOnRepoHealth:()=>Db,runOnSessionStart:()=>C3,runOnToolUse:()=>P3,runOnWriteHealth:()=>Pb,runSessionEndMetrics:()=>U3,runSyncConfig:()=>W3,sessionStartCore:()=>R3,toolUseCore:()=>M3,writeIdentitySideChannel:()=>kl});import{execFileSync as Lb}from"node:child_process";import{existsSync as mp,readFileSync as v3,realpathSync as S3}from"node:fs";import{writeFile as x3}from"node:fs/promises";import{homedir as QD}from"node:os";import{dirname as $b,isAbsolute as bl,join as wl,relative as eP}from"node:path";function nP(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let o=e_(n),i=n.includes("review_changes")||n.includes("review_verdict"),a=jb(n);if(!o&&!i&&!a)return;let l=e.guard_signals??{},c=l[t]??{},u=new Date(r).toISOString();o&&(c.consulted_at=u),i&&(c.reviewed_at=u),a&&(c.captured_at=u),l[t]=c,e.guard_signals=l}function jb(e){return e.includes("maind")?e.includes("keep_memory")||e.includes("update_memory")||e.includes("graduate_memory")||e.includes("submit_content_draft")||e.includes("submit_convention_draft")||e.includes("revise_content_draft"):!1}function rP(e,t,n=Date.now()){A3(e,n);let r=e.sessions[t];if(!r)return!1;let o=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,o)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function A3(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let o=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-o>fp&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i)||0));t-o>fp&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i.at)||0));t-o>fp&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let o=Date.parse(r.started_at);!Number.isNaN(o)&&t-o>fp&&delete e.sessions[n]}}function Tr(e){if(e.config)return e.config;let t=ee();return t===null?null:{api_key:t,endpoint:Td}}function oP(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function R3(e,t){let n=me(t,{kind:"text",event:"SessionStart"}),r=[],o={speaks:n,line:s(i=>{n&&r.push(i)},"line")};try{await I3(e,t,o)}catch{}return r.length===0?null:{kind:"text",event:"SessionStart",text:r.join("")}}async function C3(){return ve(["on-session-start"])}async function I3(e,t,n){let r=null;if(n.speaks)try{r=yl(process.cwd(),{offline:!0});let a=$O(Od(r));if(a!==null)n.line(a+`
1003
+ Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function v3(e,t){let n=_3(e,t);return!n||n.startsWith("..")||GD(n)?null:n.split(b3).join(y3.sep)}function S3(e){try{let t=h3(KD(e,Pc),"utf8"),{manifest:n}=jc(t);return n?.contracts??[]}catch{return[]}}async function Pb(){return ve(["on-write-health"])}async function Mb(e,t){try{let n=Mt(e).find(g=>g.act!=="read");if(n===void 0||!me(t,{kind:"context",event:"PostToolUse"}))return null;let r=typeof e.session_id=="string"?e.session_id:"",o=n.path;if(!r||!o)return null;let i=be(e,t),a=GD(o)?o:KD(i,o),l=m3(a)?g3(a):mn(a),c=gt(jo(l)),u=v3(c,l);if(u===null)return null;let d=qD(u,S3(c),Ph(c));if(zD(d))return null;let p=[];if(d.contracts.length>0)try{let g=await ao(c,{contracts:d.contracts});for(let _ of g.findings)_.status==="open"&&p.push({key:`spec:${_.id}`,line:`spec-drift (${_.contract}): ${_.detail}`})}catch{}if(d.theme)try{let g=po(c);for(let _ of g.findings)_.status==="open"&&p.push({key:`theme:${_.file}:${_.klass}`,line:`theme-class-drift: \`${_.klass}\` in ${_.file} \u2014 no token \`--color-${_.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=uo(c);for(let _ of g.findings)_.status==="open"&&p.push({key:`acl:${_.id}`,line:_.rule==="dead_policy"?`table-acl-lint: \`${_.table}\` has a policy for ${_.deadPolicies.map(b=>`${b.role} ${b.command}`).join(", ")} but no matching GRANT \u2014 the caller gets 42501 before RLS runs; grant the command or drop the policy.`:_.rule==="service_role_undecided"?`table-acl-lint: \`${_.table}\` (created in ${_.createdIn}) never names service_role in a GRANT or REVOKE \u2014 since Supabase's 2026-10-30 switch a new table gives the service key nothing; grant it or revoke it explicitly.`:`table-acl-lint: \`${_.table}\` (created in ${_.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}if(d.mockupSets.length>0)try{let g=ca(c,{sets:d.mockupSets});for(let _ of g.findings)_.status!=="open"&&_.status!=="warn"||p.push({key:`mockup:${_.id}`,line:`mockup-label-drift: ${_.title}`})}catch{}let f=await ue(),m=JD(f,r,c,p);f.pending_metrics.push({session_id:r,metric_key:WD,metric_value:1},{session_id:r,metric_key:VD,metric_value:m.length}),await un(f);let h=YD(m,u);return h===null?null:{kind:"context",event:"PostToolUse",text:h}}catch{return null}}var WD,VD,k3,w3,pp=w(()=>{"use strict";Me();Wt();Oe();Ie();tt();_l();il();ut();WD="write_health_hook_runs",VD="write_health_hook_findings",k3=/\.(tsx?|jsx?|css)$/,w3=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(BD,"declPath");s(qD,"routesForPath");s(zD,"routesAreEmpty");s(JD,"takeUnreported");s(YD,"formatWriteHealth");s(v3,"repoRelative");s(S3,"readContracts");s(Pb,"runOnWriteHealth");s(Mb,"writeHealthCore")});var gs={};Q(gs,{agentHostPidCandidates:()=>Fe,closeSessionMetrics:()=>gp,closeTrackedSession:()=>rP,editRootOf:()=>sP,effectiveConfig:()=>Tr,fileEditCore:()=>hp,fileWriteCore:()=>Hb,flushSessionMetrics:()=>yp,grandparentPid:()=>lP,hookClientFamily:()=>iP,isCaptureTool:()=>jb,isShellCommand:()=>cP,recordGuardSignals:()=>nP,refreshIdentityOnPrompt:()=>Fb,runFlush:()=>K3,runHookStatus:()=>W3,runOnFileEdit:()=>H3,runOnFileWrite:()=>F3,runOnRepoHealth:()=>Db,runOnSessionStart:()=>O3,runOnToolUse:()=>$3,runOnWriteHealth:()=>Pb,runSessionEndMetrics:()=>G3,runSyncConfig:()=>q3,sessionStartCore:()=>I3,toolUseCore:()=>L3,writeIdentitySideChannel:()=>kl});import{execFileSync as Lb}from"node:child_process";import{existsSync as mp,readFileSync as x3,realpathSync as E3}from"node:fs";import{writeFile as T3}from"node:fs/promises";import{homedir as QD}from"node:os";import{dirname as $b,isAbsolute as bl,join as wl,relative as eP}from"node:path";function nP(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let o=e_(n),i=n.includes("review_changes")||n.includes("review_verdict"),a=jb(n);if(!o&&!i&&!a)return;let l=e.guard_signals??{},c=l[t]??{},u=new Date(r).toISOString();o&&(c.consulted_at=u),i&&(c.reviewed_at=u),a&&(c.captured_at=u),l[t]=c,e.guard_signals=l}function jb(e){return e.includes("maind")?e.includes("keep_memory")||e.includes("update_memory")||e.includes("graduate_memory")||e.includes("submit_content_draft")||e.includes("submit_convention_draft")||e.includes("revise_content_draft"):!1}function rP(e,t,n=Date.now()){C3(e,n);let r=e.sessions[t];if(!r)return!1;let o=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,o)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function C3(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let o=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-o>fp&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i)||0));t-o>fp&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let o=Math.max(0,...Object.values(r).map(i=>Date.parse(i.at)||0));t-o>fp&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let o=Date.parse(r.started_at);!Number.isNaN(o)&&t-o>fp&&delete e.sessions[n]}}function Tr(e){if(e.config)return e.config;let t=ee();return t===null?null:{api_key:t,endpoint:Td}}function oP(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function I3(e,t){let n=me(t,{kind:"text",event:"SessionStart"}),r=[],o={speaks:n,line:s(i=>{n&&r.push(i)},"line")};try{await N3(e,t,o)}catch{}return r.length===0?null:{kind:"text",event:"SessionStart",text:r.join("")}}async function O3(){return ve(["on-session-start"])}async function N3(e,t,n){let r=null;if(n.speaks)try{r=yl(process.cwd(),{offline:!0});let a=$O(Od(r));if(a!==null)n.line(a+`
1004
1004
  `);else{let l=RD(process.cwd());l!==null&&n.line(l+`
1005
1005
  `)}}catch{}let o=await ue();if(Tr(o)===null)return 0;let i=Ub(e);if(i===null)return 0;oP(o,i),await un(o);try{kl(e,i)}catch{}try{let a=n.speaks?Z():null;if(a!==null){let l=nt(a),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),u=fn(Pt(e)||null,i),d=kt(l,{hostPids:Fe(),cwd:c,selfId:u}),p=ZI(d?.snap??null,u),f=QI(d?.snap??l[0]??null,p.id,Date.now(),void 0,p.announceError);f!==null&&n.line(f+`
1006
1006
  `);let m=tl(i,c,{projectKey:s(()=>a,"projectKey"),hostPids:Fe()});m!==null&&n.line(`[maind] ${m}
1007
1007
  `)}}catch{}if(n.speaks)try{let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=FI(a);l!==null&&n.line(l+`
1008
1008
  `);let c=jI(a);c!==null&&n.line(c+`
1009
1009
  `)}catch{}if(n.speaks&&r!==null)try{let a=r.plugin?.enabled===!0;if(!Ro(t.host)&&!a&&r.claudeSettings!==null){let l=r.fileExists,c=ct(r.claudeSettings,{fileExists:s(d=>l(d),"fileExists")}),u=ND(c,{bridgeVersion:K,bridgeCommand:r.bridgeCommand??(r.pathWinner?"maind-mcp-bridge":"npx -y @maind-dev/mcp-bridge"),declined:r.declinedHooks??[]});u!==null&&n.line(u+`
1010
- `)}}catch{}return 0}function iP(e,t=process.env,n=process.argv.slice(2)){return O3[hr(e,t,za(n))]}function kl(e,t,n,r=kr(),o,i=iP(e)){let a=n??Fe();if(a.length===0)return;let l=fn(Pt(e)||null,t);if(l===null)return;let c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),u=Pt(e)||void 0,d=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let p of a)yO({dir:r,agentPid:p,sessionId:t,transcriptStem:l,cwd:c,transcriptPath:u,model:d,editRoot:o,clientFamily:i})}function sP(e,t){let n=Mt(e).find(o=>o.act!=="read");if(!n)return null;let r=$b(bl(n.path)?n.path:wl(t,n.path));for(;!mp(r)&&$b(r)!==r;)r=$b(r);return Si(r)}function lP(){try{if(process.platform==="win32")return null;let e=Lb("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Fe(e={}){let t=[],n=e.parent??process.ppid;if(Number.isFinite(n)&&n>1&&t.push(n),cP((e.commandOf??D3)(n))){let r=(e.grandparent??lP)();r!==null&&r>1&&r!==n&&t.push(r)}return t}function cP(e){if(e===null)return!1;let n=((e.trim().split(/\s+/)[0]??"").split("/").pop()??"").replace(/^-/,"");return N3.has(n)}function D3(e){try{if(process.platform==="win32")return null;let t=Lb("ps",["-o","comm=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim();return t.length>0?t:null}catch{return null}}async function P3(){return ve(["on-tool-use"])}function Fb(e,t=kr(),n=Fe()){try{let r=Ub(e);if(r===null)return;let o=n.filter(i=>V_(t,i,aP));o.length>0&&kl(e,r,o,t)}catch{}}async function M3(e,t){let n=await ue();if(Tr(n)===null)return null;let r=Ub(e)??"unknown",o=oP(n,r);o.tool_call_count+=1;try{let c=Fe().filter(p=>V_(kr(),p,aP)),u=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),d=r!=="unknown"?sP(e,u):null;d!==null?kl(e,r,void 0,kr(),d):r!=="unknown"&&c.length>0&&kl(e,r,c)}catch{}let i=(e.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(o.lessons_consulted+=1),nP(n,r,i),jb(i)&&r!=="unknown"&&await oe({event:"capture_taken",session_id:r,detail:i});let a=e.transcript_path,l=t.host!=="codex"&&t.host!=="copilot";if(l&&typeof a=="string"&&a&&!o.transcript_path&&(o.transcript_path=a),l&&o.transcript_path){let c=await xy(o.transcript_path);c&&(o.token_count=c.total_tokens,await H3(n,o))}await un(n);try{if(r!=="unknown"&&me(t,{kind:"context",event:"PreToolUse"})){let c=be(e,t),u=Fe(),d=tl(r,c,{hostPids:u}),p=Ed(r,c,{hostPids:u}),f=[d,p].filter(m=>m!==null).map(m=>`[maind] ${m}`);if(f.length>0)return{kind:"context",event:"PreToolUse",text:f.join(`
1010
+ `)}}catch{}return 0}function iP(e,t=process.env,n=process.argv.slice(2)){return D3[hr(e,t,za(n))]}function kl(e,t,n,r=kr(),o,i=iP(e)){let a=n??Fe();if(a.length===0)return;let l=fn(Pt(e)||null,t);if(l===null)return;let c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),u=Pt(e)||void 0,d=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let p of a)yO({dir:r,agentPid:p,sessionId:t,transcriptStem:l,cwd:c,transcriptPath:u,model:d,editRoot:o,clientFamily:i})}function sP(e,t){let n=Mt(e).find(o=>o.act!=="read");if(!n)return null;let r=$b(bl(n.path)?n.path:wl(t,n.path));for(;!mp(r)&&$b(r)!==r;)r=$b(r);return Si(r)}function lP(){try{if(process.platform==="win32")return null;let e=Lb("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Fe(e={}){let t=[],n=e.parent??process.ppid;if(Number.isFinite(n)&&n>1&&t.push(n),cP((e.commandOf??M3)(n))){let r=(e.grandparent??lP)();r!==null&&r>1&&r!==n&&t.push(r)}return t}function cP(e){if(e===null)return!1;let n=((e.trim().split(/\s+/)[0]??"").split("/").pop()??"").replace(/^-/,"");return P3.has(n)}function M3(e){try{if(process.platform==="win32")return null;let t=Lb("ps",["-o","comm=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim();return t.length>0?t:null}catch{return null}}async function $3(){return ve(["on-tool-use"])}function Fb(e,t=kr(),n=Fe()){try{let r=Ub(e);if(r===null)return;let o=n.filter(i=>V_(t,i,aP));o.length>0&&kl(e,r,o,t)}catch{}}async function L3(e,t){let n=await ue();if(Tr(n)===null)return null;let r=Ub(e)??"unknown",o=oP(n,r);o.tool_call_count+=1;try{let c=Fe().filter(p=>V_(kr(),p,aP)),u=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),d=r!=="unknown"?sP(e,u):null;d!==null?kl(e,r,void 0,kr(),d):r!=="unknown"&&c.length>0&&kl(e,r,c)}catch{}let i=(e.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(o.lessons_consulted+=1),nP(n,r,i),jb(i)&&r!=="unknown"&&await oe({event:"capture_taken",session_id:r,detail:i});let a=e.transcript_path,l=t.host!=="codex"&&t.host!=="copilot";if(l&&typeof a=="string"&&a&&!o.transcript_path&&(o.transcript_path=a),l&&o.transcript_path){let c=await xy(o.transcript_path);c&&(o.token_count=c.total_tokens,await B3(n,o))}await un(n);try{if(r!=="unknown"&&me(t,{kind:"context",event:"PreToolUse"})){let c=be(e,t),u=Fe(),d=tl(r,c,{hostPids:u}),p=Ed(r,c,{hostPids:u}),f=[d,p].filter(m=>m!==null).map(m=>`[maind] ${m}`);if(f.length>0)return{kind:"context",event:"PreToolUse",text:f.join(`
1011
1011
 
1012
- `)}}}catch{}return null}function $3(e,t){if(!e.taken&&e.outOfOrder!==null){let r=e.outOfOrder;return`${e.number} is free, but older than the newest migration on ${r.sighting.where}: ${r.newest} (${r.sighting.path}).
1012
+ `)}}}catch{}return null}function j3(e,t){if(!e.taken&&e.outOfOrder!==null){let r=e.outOfOrder;return`${e.number} is free, but older than the newest migration on ${r.sighting.where}: ${r.newest} (${r.sighting.path}).
1013
1013
 
1014
1014
  After the merge the cloud push refuses a version below the newest it has applied, unless it runs with --include-all. Write the file as ${e.suggestion} or with a fresh timestamp instead.`}let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
1015
1015
  `);return`${t.prefix}${e.number} is already taken:
@@ -1017,63 +1017,63 @@ ${n}
1017
1017
 
1018
1018
  Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
1019
1019
 
1020
- Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function L3(){return ve(["on-file-write"])}async function Hb(e,t){let n=Mt(e).filter(o=>o.act==="write");if(n.length===0||!me(t,{kind:"deny"}))return null;let r=be(e,t);for(let{path:o}of n){let i=bl(o)?o:wl(r,o);if(mp(i))continue;let a=gt(r),l=eP(a,mn(i));if(l.length===0||l.startsWith("..")||bl(l))continue;let c=await Tn(a,l);if(!(!(c.taken||c.outOfOrder!==null)||c.namespace===null))return{kind:"deny",reason:$3(c,c.namespace)}}return null}async function j3(){return ve(["on-file-edit"])}async function hp(e,t){let n=Mt(e).filter(d=>d.act!=="read");if(n.length===0||!me(t,{kind:"context",event:"PreToolUse"}))return null;let r=be(e,t),o=Fe(),i=fn(Pt(e)||null,typeof e.session_id=="string"?e.session_id:null),a=gt(r),l=Z(),c=new Map,u=s(d=>{if(!c.has(d)){let p=nt(d);c.set(d,p.length===0?null:kt(p,{hostPids:o,cwd:r,selfId:i}))}return c.get(d)??null},"ownFor");for(let{path:d}of n){let p=bl(d)?d:wl(r,d),f=mp(p)?S3(p):mn(p),m=SO(f),h=m===null||m.root===a,g=h?a:m.root,_=h?l:m.projectKey;if(_===null)continue;let b=u(_);if(b===null)continue;let k=eP(g,f).replace(/\\/g,"/");if(k.length===0||k.startsWith("..")||bl(k))continue;let v=XI(b.snap,k,{via:b.via,currentBranch:b.via==="cwd"?F3(r):null,nowMs:Date.now()});if(v!==null)return{kind:"context",event:"PreToolUse",text:v}}return null}function F3(e){try{let n=Lb("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function H3(e,t){let n=Wy(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let o=r/n.model_token_limit,i="ok";if(o>=n.handoff_at_pct/100?i="handoff_recommended":o>=n.warn_at_pct/100&&(i="warn"),t.last_advisory_status===i||(t.last_advisory_status=i,i==="ok"))return;let a=Math.round(o*100),l={session_id:t.session_id,status:i,tokens:r,ratio:Number(o.toFixed(3)),pct:a,thresholds:n,suggested_next:i==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await x3(wl(et,`handoff_advisory_${t.session_id}.json`),JSON.stringify(l,null,2))}catch(c){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${c instanceof Error?c.message:String(c)}
1020
+ Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function F3(){return ve(["on-file-write"])}async function Hb(e,t){let n=Mt(e).filter(o=>o.act==="write");if(n.length===0||!me(t,{kind:"deny"}))return null;let r=be(e,t);for(let{path:o}of n){let i=bl(o)?o:wl(r,o);if(mp(i))continue;let a=gt(r),l=eP(a,mn(i));if(l.length===0||l.startsWith("..")||bl(l))continue;let c=await Tn(a,l);if(!(!(c.taken||c.outOfOrder!==null)||c.namespace===null))return{kind:"deny",reason:j3(c,c.namespace)}}return null}async function H3(){return ve(["on-file-edit"])}async function hp(e,t){let n=Mt(e).filter(d=>d.act!=="read");if(n.length===0||!me(t,{kind:"context",event:"PreToolUse"}))return null;let r=be(e,t),o=Fe(),i=fn(Pt(e)||null,typeof e.session_id=="string"?e.session_id:null),a=gt(r),l=Z(),c=new Map,u=s(d=>{if(!c.has(d)){let p=nt(d);c.set(d,p.length===0?null:kt(p,{hostPids:o,cwd:r,selfId:i}))}return c.get(d)??null},"ownFor");for(let{path:d}of n){let p=bl(d)?d:wl(r,d),f=mp(p)?E3(p):mn(p),m=SO(f),h=m===null||m.root===a,g=h?a:m.root,_=h?l:m.projectKey;if(_===null)continue;let b=u(_);if(b===null)continue;let k=eP(g,f).replace(/\\/g,"/");if(k.length===0||k.startsWith("..")||bl(k))continue;let v=XI(b.snap,k,{via:b.via,currentBranch:b.via==="cwd"?U3(r):null,nowMs:Date.now()});if(v!==null)return{kind:"context",event:"PreToolUse",text:v}}return null}function U3(e){try{let n=Lb("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function B3(e,t){let n=Wy(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let o=r/n.model_token_limit,i="ok";if(o>=n.handoff_at_pct/100?i="handoff_recommended":o>=n.warn_at_pct/100&&(i="warn"),t.last_advisory_status===i||(t.last_advisory_status=i,i==="ok"))return;let a=Math.round(o*100),l={session_id:t.session_id,status:i,tokens:r,ratio:Number(o.toFixed(3)),pct:a,thresholds:n,suggested_next:i==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await T3(wl(et,`handoff_advisory_${t.session_id}.json`),JSON.stringify(l,null,2))}catch(c){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${c instanceof Error?c.message:String(c)}
1021
1021
  `)}i==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${a}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
1022
1022
  `):process.stderr.write(`[maind] \u26D4 Token usage at ~${a}% (handoff threshold ${n.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
1023
- `)}async function U3(e){await gp(e)&&await yp(tP)}async function gp(e){try{let t=await ue();if(Tr(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(rP(t,r),await un(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
1024
- `),!1}}async function yp(e=tP){try{let t=await ue(),n=Tr(t);return n===null?null:await uP(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function B3(){let e=await ue(),t=Tr(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await uP(t,T3);return process.stdout.write(JSON.stringify(n,null,2)+`
1025
- `),n.ok?0:1}async function uP(e,t){let n=await ue();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),o=pO(e.endpoint,e.api_key,r),i=new Promise(l=>setTimeout(()=>l({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([o,i]);if(a.ok){let l=await ue();return l.pending_metrics=l.pending_metrics.slice(r.length),await un(l),{ok:!0,flushed:r.length,remaining:l.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function G3(){let e=await ue(),t=Tr(e),n=K3(),r=_t(bt(QD(),process.env,process.platform)),o=!r.enabled&&VC(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:Wy(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!o,...r.enabled?{provided_by:`maind plugin (${Fa}, ${r.source??"?"})`}:{},hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...!r.enabled&&yy(n.findings)?{remedy:ZD}:{}}},null,2)+`
1023
+ `)}async function G3(e){await gp(e)&&await yp(tP)}async function gp(e){try{let t=await ue();if(Tr(t)===null)return!1;let r=e??Object.keys(t.sessions)[0];return r&&t.sessions[r]&&(rP(t,r),await un(t)),!0}catch(t){return process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
1024
+ `),!1}}async function yp(e=tP){try{let t=await ue(),n=Tr(t);return n===null?null:await uP(n,e)}catch(t){return{ok:!1,flushed:0,remaining:0,error:t instanceof Error?t.message:String(t)}}}async function K3(){let e=await ue(),t=Tr(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await uP(t,R3);return process.stdout.write(JSON.stringify(n,null,2)+`
1025
+ `),n.ok?0:1}async function uP(e,t){let n=await ue();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),o=pO(e.endpoint,e.api_key,r),i=new Promise(l=>setTimeout(()=>l({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([o,i]);if(a.ok){let l=await ue();return l.pending_metrics=l.pending_metrics.slice(r.length),await un(l),{ok:!0,flushed:r.length,remaining:l.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function W3(){let e=await ue(),t=Tr(e),n=V3(),r=_t(bt(QD(),process.env,process.platform)),o=!r.enabled&&VC(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:Wy(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!o,...r.enabled?{provided_by:`maind plugin (${Fa}, ${r.source??"?"})`}:{},hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...!r.enabled&&yy(n.findings)?{remedy:ZD}:{}}},null,2)+`
1026
1026
  `),o){process.stderr.write(`
1027
1027
  [maind] Claude Code hook wiring is incomplete:
1028
1028
  `);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
1029
1029
  `);yy(n.findings)&&process.stderr.write(` ${ZD}
1030
- `)}return 0}function K3(){let e=wl(QD(),".claude","settings.json"),t=null;try{mp(e)&&(t=v3(e,"utf8"))}catch{}return{settingsPath:e,findings:ct(t)}}async function W3(){let e=await ue(),t=Tr(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??E3,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
1030
+ `)}return 0}function V3(){let e=wl(QD(),".claude","settings.json"),t=null;try{mp(e)&&(t=x3(e,"utf8"))}catch{}return{settingsPath:e,findings:ct(t)}}async function q3(){let e=await ue(),t=Tr(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??A3,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
1031
1031
  `),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
1032
1032
  `);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
1033
1033
  `),1}let o;try{o=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
1034
1034
  `),1}let i=o;return typeof i.warn_at_pct!="number"||typeof i.handoff_at_pct!="number"||typeof i.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
1035
1035
  `),1):(e.thresholds={warn_at_pct:i.warn_at_pct,handoff_at_pct:i.handoff_at_pct,model_token_limit:i.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await un(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
1036
- `),0)}function Ub(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var E3,tP,T3,fp,O3,aP,N3,ZD,Lt=w(()=>{"use strict";Eo();Dt();Me();HI();Wt();uu();pn();we();Le();Mn();kd();G_();de();K_();Oo();Ji();tt();Ie();Oe();il();xO();ut();Ti();Nd();Ob();Ui();CD();DD();Xe();_l();pp();E3=process.env.MAIND_THRESHOLDS_ENDPOINT??Ei("get-context-thresholds"),tP=1500,T3=1e4,fp=7*24*60*60*1e3;s(nP,"recordGuardSignals");s(jb,"isCaptureTool");s(rP,"closeTrackedSession");s(A3,"gcState");s(Tr,"effectiveConfig");s(oP,"getOrCreateSession");s(R3,"sessionStartCore");s(C3,"runOnSessionStart");s(I3,"sessionStartBody");O3={"claude-code":"claude-code",codex:"codex",copilot:"copilot",cursor:"cursor",gemini:"gemini-cli",devin:null,unknown:null};s(iP,"hookClientFamily");s(kl,"writeIdentitySideChannel");s(sP,"editRootOf");aP=6e4;s(lP,"grandparentPid");s(Fe,"agentHostPidCandidates");N3=new Set(["sh","bash","zsh","dash","ksh","fish","tcsh","csh","ash"]);s(cP,"isShellCommand");s(D3,"processCommand");s(P3,"runOnToolUse");s(Fb,"refreshIdentityOnPrompt");s(M3,"toolUseCore");s($3,"denyReason");s(L3,"runOnFileWrite");s(Hb,"fileWriteCore");s(j3,"runOnFileEdit");s(hp,"fileEditCore");s(F3,"currentGitBranch");s(H3,"maybeEmitAdvisory");s(U3,"runSessionEndMetrics");s(gp,"closeSessionMetrics");s(yp,"flushSessionMetrics");s(B3,"runFlush");s(uP,"flushPending");s(G3,"runHookStatus");ZD="Re-run `maind-mcp-bridge install --hooks-only` to add the missing hooks \u2014 it is idempotent: it adds only what is absent, asks consent per hook, and rewrites no entry you already have except the SessionStart reminder's old `cat`, which it replaces with on-session-reminder (MAIND-630).";s(K3,"readHookWiring");s(W3,"runSyncConfig");s(Ub,"sessionIdOf")});var Bb={};Q(Bb,{runOnSessionBriefing:()=>q3,sessionBriefingCore:()=>V3});async function V3(e,t){let n="";return await Ld("core",e,{hostHint:t.host,collect:s(r=>void(n+=r),"collect")}),n.length===0?null:{kind:"text",event:"SessionStart",text:n}}async function q3(e=process.argv.slice(2)){return ve(["on-session-briefing"],e)}var Gb=w(()=>{"use strict";Po();Oe();s(V3,"sessionBriefingCore");s(q3,"runOnSessionBriefing")});import{existsSync as z3}from"node:fs";import{mkdir as J3,readFile as Y3,rename as X3,writeFile as Z3}from"node:fs/promises";import{dirname as Q3,join as e9}from"node:path";function vl(e=process.env){let t=ee();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??ll,keyFp:tr(t)}}async function Kb(e,t=Date.now(),n=_p){try{if(!z3(n))return null;let r=JSON.parse(await Y3(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let o=Date.parse(r.fetched_at);if(Number.isNaN(o))return null;let i=r.policy,a=pd(l_(i)),l=i!==void 0&&Ka.every(c=>c in i);return{policy:a,fetchedAt:r.fetched_at,fresh:l&&t-o<t9}}catch{return null}}async function r9(e,t,n,r){try{await J3(Q3(r),{recursive:!0,mode:448});let o={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},i=`${r}.tmp`;await Z3(i,JSON.stringify(o,null,2),{mode:384}),await X3(i,r)}catch{}}async function o9(){let e=ee();if(e===null)return null;let t=null;try{t=Z()}catch{t=null}let n=await Qt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:i9(),projectKey:t,bridgeVersion:K,timeoutMs:n9});if(n===null)return null;try{return pd(JSON.parse(n))}catch{return null}}async function Ar(e,t={}){let n=t.nowMs??Date.now(),r=t.file??_p,o=t.identity===void 0?vl():t.identity;if(o===null)return Gi;let i=await Kb(o,n,r);if(i?.fresh)return i.policy;if(e){let a=await(t.fetcher??o9)();if(a!==null)return await r9(o,a,n,r),a}return i?.policy??Gi}function i9(){try{return ke()}catch{return null}}var _p,t9,n9,Fo=w(()=>{"use strict";Dt();Wt();we();de();Xe();Ln();Je();_p=e9(he,"trigger-policy.json"),t9=12*60*60*1e3,n9=3e3;s(vl,"currentIdentity");s(Kb,"readCachedPolicy");s(r9,"writeCachedPolicy");s(o9,"fetchTriggerPolicy");s(Ar,"resolveTriggerPolicy");s(i9,"safeDeviceId")});function wp(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&/(sh|ch|x|z|ss)es$/.test(t)||t.length>6&&t.endsWith("ungen")?t.slice(0,-2):t.length>5&&t.endsWith("ing")?t.slice(0,-3):t.length>5&&t.endsWith("en")||t.length>4&&t.endsWith("ed")?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function bp(e){return e.length<3||/^\d+$/.test(e)||dP.has(e)||dP.has(wp(e))}function l9(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function c9(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function fP(e){let t=new Set,n=new Set,r=[];for(let o of e.matchAll(u9)){let i=o[0],a=i.toLowerCase();if(r.push(a),/[._-]/.test(i)){let l=c9(a);l.length>=4&&!pP.has(l)&&n.add(l)}for(let l of l9(i)){let c=l.toLowerCase();bp(c)||t.add(wp(c))}}for(let o=0;o+1<r.length;o++){if(/[._-]/.test(r[o])||/[._-]/.test(r[o+1]))continue;let i=`${r[o]}-${r[o+1]}`;pP.has(i)||n.add(i)}return{words:t,compounds:n}}function d9(e){return e.slice(0,8e3).replace(/<pasted_content\b[\s\S]*?(<\/pasted_content>|$)/g," ").replace(/https?:\/\/\S+/g," ").replace(/(?:~|\.{1,2})?\/[\w.@%+~-]+(?:\/[\w.@%+~-]*)+/g," ").replace(/\b[\w.-]+(?:\/[\w.@%+~-]+)+/g," ")}function mP(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function Vb(e){if(!e)return[];let t=[];for(let n of e.split(`
1037
- `)){let r=p9.exec(n.trim());r&&t.push({scope:r[1],shortId:r[2],id:`conv_${r[2].replace(/-/g,"_")}`,version:Number.parseInt(r[3],10),summary:r[4].trim()})}return t}function f9(e){let t=e.shortId.split("-"),n=new Set;for(let i of t)bp(i)||n.add(wp(i));let r=new Set;for(let i=0;i+1<t.length;i++)!bp(t[i])&&!bp(t[i+1])&&r.add(`${t[i]}-${t[i+1]}`);let o=fP(e.summary);for(let i of o.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(i)&&r.add(i);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:o.words}}function hP(e,t,n=3,r=[]){if(t.length===0)return[];let o=new Set([...r].map(f=>wp(f.toLowerCase()))),i=t.map(f9),a=new Map,l=new Map;for(let f of i){let m=new Set([...f.keyWords,...f.keyCompounds]);for(let h of m)a.set(h,(a.get(h)??0)+1);for(let h of new Set([...m,...f.summaryWords]))l.set(h,(l.get(h)??0)+1)}let c=i.length,u=s(f=>Math.log(1+c/(l.get(f)??c)),"idf"),d=fP(d9(e));for(let f of o)d.words.delete(f);let p=[];for(let f of i){let m=new Set;for(let k of d.words)f.keyWords.has(k)&&m.add(k);for(let k of d.compounds)f.keyCompounds.has(k)&&m.add(k);let h=new Set;for(let k of d.words)!m.has(k)&&f.summaryWords.has(k)&&h.add(k);if(m.size===0&&h.size===0)continue;let g=0;for(let k of m)g+=2*u(k);for(let k of h)g+=u(k);let _=[...m].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),b=m.size>=1&&m.size+h.size>=2&&g>=m9;!_&&!b||p.push({convention:f.convention,score:g,matched:[...m,...h]})}return p.sort((f,m)=>m.score-f.score||f.convention.id.localeCompare(m.convention.id)).slice(0,n)}function y9(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function gP(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],o=new Set,i=s((l,c)=>{if(r.length>=t)return;let u=l.endsWith("()"),d=u?l.slice(0,-2):l;if(d.includes("/")||h9.test(d)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(d)||!c&&!u&&!y9(d))return;let p=d.split("."),f=p[p.length-1];f.length<(c||u?3:4)||g9.has(f.toLowerCase())||o.has(f)||(o.add(f),r.push({name:f,qualifier:p.length>1?p[p.length-2]:null}))},"consider");for(let l of n.matchAll(/`([^`\n]{1,120})`/g))i(l[1].trim(),!0);let a=n.replace(/`[^`\n]{1,120}`/g," ");for(let l of a.matchAll(/(?<![\w$./\\-])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)(?![\w$/\\-])/g))i(l[1],!1);return r}function Wb(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function _P(e,t=2e3){let n=e.conventions,r=e.symbols.filter(u=>u.locations.length>0);if(n.length===0&&r.length===0)return null;let o=new kp(t-yP);if(!o.tryAdd(`${s9} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let i=[],a=[],l=!1;if(n.length>0&&o.tryAdd("Project conventions whose terms appear in this prompt (full text: get_conventions({id})):"))for(let u of n){let d=`- ${u.convention.id} (v${u.convention.version}): ${Wb(u.convention.summary,320)}`;if(!o.tryAdd(d)){l=!0;break}i.push(u.convention.id)}if(r.length>0&&!l){let u=e.repoRoot?` in ${e.repoRoot}`:"";if(o.tryAdd(`Symbols this prompt names, as the local code index places them${u} (files unchanged since indexing):`))for(let d of r){let p=d.locations.slice(0,3),f=p.map(g=>{let _=g.qualifiedName===d.candidate.name?g.kind:`${g.kind} ${g.qualifiedName}`;return`${g.filePath}:${g.startLine} (${_})${g.signature?` '${Wb(g.signature,70)}'`:""}`}).join("; "),m=d.total-p.length,h=`- ${d.candidate.name} \u2192 ${f}${m>0?` (+${m} more \u2014 codebase_search)`:""}`;if(!o.tryAdd(h)){l=!0;break}a.push(d.candidate.name)}}if(i.length===0&&a.length===0)return null;let c=o.toString();return l&&(c+=`
1038
- (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:c,conventionIds:i,symbolNames:a}}function b9(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>_9}function k9(e){if(e.length===0)return"";let t=e.map(o=>o.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(o=>o[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function w9(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function bP(e,t=1500){let n=new Map;for(let h of e.callers){let g=n.get(h.calleeKey)??[];g.some(_=>_.caller.nodeKey===h.caller.nodeKey)||g.push(h),n.set(h.calleeKey,g)}let r=s(h=>new Set((n.get(h)??[]).map(g=>g.caller.filePath)).size,"fileCount"),o=e.symbols.filter(h=>n.has(h.nodeKey)).sort((h,g)=>r(g.nodeKey)-r(h.nodeKey)||h.startLine-g.startLine),i=e.symbols.reduce((h,g)=>Math.max(h,g.endLine),0),a=e.symbols.filter(h=>!h.qualifiedName.includes(".")&&h.kind!=="module"),l=b9(e.range,i)&&a.length>0;if(o.length===0&&e.importers.length===0&&!l)return null;let c=k9([e.relPath,...e.callers.map(h=>h.caller.filePath),...e.importers]),u=new kp(t-yP),d=c?` Paths below are relative to ${c}.`:"";if(!u.tryAdd(`${a9} ${e.relPath} as the local code index knows it (the index matches this file on disk).${d}`))return null;let p=!1;if(l&&u.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let h="",g=0;for(let b of a){let k=`${b.qualifiedName} L${b.startLine}`,v=h.length===0?k:`${h} \xB7 ${k}`;if(v.length>500)break;h=v,g++}let _=a.length-g;u.tryAdd(_>0?`${h} \xB7 +${_} more`:h)||(p=!0)}if(o.length>0&&!p&&u.tryAdd("Called from other files (import-resolved call graph):"))for(let h of o){let g=n.get(h.nodeKey)??[],_=g.slice(0,3).map(S=>`${w9(S.caller,c)}${S.kind==="calls"?"":` [${S.kind}]`}`),b=g.length-_.length,k=h.signature?` '${Wb(h.signature,80)}'`:"",v=`- ${h.qualifiedName} L${h.startLine}${k} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!u.tryAdd(v)){p=!0;break}}if(e.importers.length>0&&!p){let h=e.importers.slice(0,5).map(k=>k.slice(c.length)),g=e.importers.length-h.length,_=e.importers.length,b=`Imported by ${_} file${_===1?"":"s"}: ${h.join(", ")}${g>0?` +${g} more`:""}`;u.tryAdd(b)||(p=!0)}e.hidden>0&&!p&&u.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let f=e.unchecked??0;if(f>0&&!p&&u.tryAdd(`(+${f} more reference${f===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),u.size<=1)return null;let m=u.toString();return p&&(m+=`
1039
- (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var s9,a9,dP,pP,u9,p9,m9,h9,g9,kp,yP,_9,kP=w(()=>{"use strict";s9="[maind context \xB7 prompt]",a9="[maind context \xB7 read]",dP=new Set("a an the and or but if then else when while of to in on at by for with from into onto over under about as is are was were be been being it its this that these those there here we you i me my our your they them their he she his her not no yes do does did done can could should would will shall may might must have has had so too very just also only all any some each every more most less than what which who whom whose why how where please let lets make made use used uses using get got new now one two via per etc out up down off again before after first last next previous other same different main default good bad right wrong both much many few own still even ever never always add added adding build builds built change changes changed check checks checked create created fix fixed fixes update updated updates write writes written read reads run runs running start started stop set show find look need needs want work works working try keep move put give take call called see know think tell say ask help mean like sure ok okay thing things stuff way part step steps case cases time today explicit implicit user users agent agents file files code line lines value values name names list type types data text rule rules policy pattern patterns anti convention conventions maind claude project projects repo repository branch branches feature features task tasks issue issues problem error errors bug bugs test tests verify version versions thanks thank gate gates content note notes org block apply applies render renders object objects title titles comment comments description local remote script scripts sync kind strategy request alternative better open close merge merged action reason lesson lessons word words der die das den dem des ein eine einen einem einer eines und oder aber wenn dann sonst als wie was wer wo warum weil dass ist sind war waren sein bin bist hat haben hatte wird werden wurde kann k\xF6nnen koennen k\xF6nnte soll sollen sollte muss m\xFCssen muessen darf nicht kein keine nur auch noch schon mal bitte ich du er sie es wir ihr mich mir dich dir uns euch ihnen sich mit ohne f\xFCr fuer auf aus bei nach vor \xFCber ueber unter zum zur im am um an in von zu bis durch gegen hier da dort jetzt ja nein doch also man dies diese dieser dieses mach mache machen lass lasst gib geht gehen gut schreib schreibe schreiben bau baue bauen pr\xFCf pr\xFCfe pr\xFCfen pruefen lies lesen starte starten teste testen nutze nutzen brauch brauchen datei dateien zeile zeilen neue neuen neu alte alten erst gleich kurz einfach richtig falsch danke".split(/\s+/)),pP=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(wp,"stem");s(bp,"isNoise");s(l9,"splitParts");s(c9,"normalizeCompound");u9=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(fP,"termsOf");s(d9,"promptForMatching");s(mP,"repoNameWords");p9=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(Vb,"parseConventionLines");s(f9,"profileOf");m9=4.5;s(hP,"matchConventions");h9=/\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts|py|pyi|md|mdx|json|jsonc|ya?ml|toml|sql|css|scss|html|sh|txt|lock|env|log|png|svg|jpe?g|gif|pdf)$/i,g9=new Set(["JavaScript","TypeScript","GitHub","GitLab","PostgreSQL","MySQL","SQLite","NodeJS","NextJS","macOS","iOS","iPhone","iPad","iCloud","OpenAI","YouTube","LinkedIn","PowerShell","VSCode","WebSocket","OAuth","PostHog","DevTools","ChatGPT","DeepSeek","OpenVSX","AgentComposer","ClaudeCode","McpServer","README","TODO","FIXME"].map(e=>e.toLowerCase()));s(y9,"looksLikeCode");s(gP,"extractSymbolCandidates");s(Wb,"clip");kp=class{constructor(t){this.budget=t}static{s(this,"Budgeted")}lines=[];used=0;tryAdd(t){let n=t.length+(this.lines.length>0?1:0);return this.used+n>this.budget?!1:(this.lines.push(t),this.used+=n,!0)}get size(){return this.lines.length}toString(){return this.lines.join(`
1040
- `)}},yP=90;s(_P,"renderPromptContext");_9=2e3;s(b9,"isPartialRead");s(k9,"commonDir");s(w9,"callerLabel");s(bP,"renderReadContext")});import{createHash as v9}from"node:crypto";import{existsSync as wP,mkdirSync as S9,readdirSync as x9,rmSync as E9,statSync as T9,writeFileSync as A9}from"node:fs";import{join as vp}from"node:path";function qb(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function I9(e,t,n=null,r=C9){try{for(let o of x9(e)){let i=vp(e,o);if(i!==n)try{t-T9(i).mtimeMs>r&&E9(i,{recursive:!0,force:!0})}catch{}}}catch{}}var R9,C9,Sl,vP=w(()=>{"use strict";ut();R9=vp(et,"context"),C9=7*24*60*60*1e3;s(qb,"safe");Sl=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=R9){let o=n?`${qb(t)}__${qb(n)}`:qb(t);return new e(r,vp(r,o))}fileFor(t){return vp(this.dir,v9("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return wP(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{wP(this.dir)||(S9(this.dir,{recursive:!0,mode:448}),I9(this.root,n,this.dir));for(let r of t)try{A9(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(I9,"sweepStaleScopes")});var El={};Q(El,{INDEX_RELPATH:()=>dr,SOFT_BUDGET_MS:()=>EP,findRepoRoot:()=>pr,isMachinePrompt:()=>CP,loadCachedConventions:()=>AP,promptContextCore:()=>F9,promptContextFor:()=>OP,promptTextOf:()=>RP,readContextCore:()=>B9,readContextFor:()=>NP,runOnPromptContext:()=>H9,runOnReadContext:()=>G9});import{existsSync as SP,readFileSync as O9,realpathSync as N9,statSync as D9}from"node:fs";import{dirname as P9,isAbsolute as xP,join as xl,relative as M9,sep as $9}from"node:path";function L9(e,t){let n=M9(e,t);return!n||n.startsWith("..")||xP(n)?null:n.split($9).join("/")}function Jb(e){try{let t=D9(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function TP(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Xd(),fb));return t(e)}function AP(e,t={}){let n=t.client??"claude-code";try{let r=t.identity===void 0?vl():t.identity,o=t.identity===void 0&&r!==null?{...r,clientFamily:n}:r;if(e!==null&&o!==null){let i=pu(e,o),a=Ki(i?.result.instructions??null),l=Vb(a);if(l.length>0)return l}}catch{}try{let r=JSON.parse(O9(t.briefingCacheFile??Md(n),"utf8"));if(typeof r.conventions=="string")return Vb(r.conventions)}catch{}return[]}function RP(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function CP(e,t){if(e.is_command===!0)return!0;let n=t.trimStart();return/^\/[A-Za-z][\w:-]*(\s|$)/.test(n)||/^<[a-z][\w-]*[\s>]/.test(n)||n.startsWith("This session is being continued from a previous conversation")}function IP(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";if(!t)return null;let n=typeof e.agent_id=="string"&&e.agent_id.trim()?e.agent_id.trim():null;return{sessionId:t,agentId:n}}async function j9(e,t,n,r){let o;try{o=await r(n)}catch{return[]}try{if(!o.meta().schemaCurrent)return[];let i=o.symbolsNamed(e.map(u=>u.name)),a=o.files([...i.values()].flat().map(u=>u.filePath).slice(0,zb)),l=new Set;for(let[u,d]of a){let p=Jb(xl(t,u));p!==null&&fa(d,p)&&l.add(u)}let c=[];for(let u of e){let d=i.get(u.name)??[],p=u.qualifier===null?[]:d.filter(h=>h.qualifiedName===`${u.qualifier}.${u.name}`),f=p.length>0?p:d,m=f.filter(h=>l.has(h.filePath)).map(h=>({kind:h.kind,qualifiedName:h.qualifiedName,filePath:h.filePath,startLine:h.startLine,signature:h.signature}));m.length>0&&c.push({candidate:u,locations:m,total:f.length})}return c}catch{return[]}finally{try{o.close()}catch{}}}async function OP(e,t={}){let n=t.now??Date.now,r=n(),o=t.env??process.env,i=t.target??Pn(e,o,t.readConfig??re);if(!me(i,{kind:"context",event:"UserPromptSubmit"}))return null;let a=RP(e);if(a.trim().length===0||CP(e,a))return null;let l=IP(e);if(l===null)return null;let c=Sl.forScope(l.sessionId,l.agentId,t.seenRoot),u=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:Vi(i,o)??process.cwd(),d=pr(u),p=l.agentId===null?(t.assignedNotice??((x,T)=>tl(x,T,{hostPids:Fe()})))(l.sessionId,u):null,f=l.agentId===null?(t.threadNotice??((x,T)=>Ed(x,T,{hostPids:Fe()})))(l.sessionId,u):null,m=[p,f].filter(x=>x!==null).map(x=>`[maind] ${x}`),h=m.length===0?null:m.join(`
1036
+ `),0)}function Ub(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var A3,tP,R3,fp,D3,aP,P3,ZD,Lt=w(()=>{"use strict";Eo();Dt();Me();HI();Wt();uu();pn();we();Le();Mn();kd();G_();de();K_();Oo();Ji();tt();Ie();Oe();il();xO();ut();Ti();Nd();Ob();Ui();CD();DD();Xe();_l();pp();A3=process.env.MAIND_THRESHOLDS_ENDPOINT??Ei("get-context-thresholds"),tP=1500,R3=1e4,fp=7*24*60*60*1e3;s(nP,"recordGuardSignals");s(jb,"isCaptureTool");s(rP,"closeTrackedSession");s(C3,"gcState");s(Tr,"effectiveConfig");s(oP,"getOrCreateSession");s(I3,"sessionStartCore");s(O3,"runOnSessionStart");s(N3,"sessionStartBody");D3={"claude-code":"claude-code",codex:"codex",copilot:"copilot",cursor:"cursor",gemini:"gemini-cli",devin:null,unknown:null};s(iP,"hookClientFamily");s(kl,"writeIdentitySideChannel");s(sP,"editRootOf");aP=6e4;s(lP,"grandparentPid");s(Fe,"agentHostPidCandidates");P3=new Set(["sh","bash","zsh","dash","ksh","fish","tcsh","csh","ash"]);s(cP,"isShellCommand");s(M3,"processCommand");s($3,"runOnToolUse");s(Fb,"refreshIdentityOnPrompt");s(L3,"toolUseCore");s(j3,"denyReason");s(F3,"runOnFileWrite");s(Hb,"fileWriteCore");s(H3,"runOnFileEdit");s(hp,"fileEditCore");s(U3,"currentGitBranch");s(B3,"maybeEmitAdvisory");s(G3,"runSessionEndMetrics");s(gp,"closeSessionMetrics");s(yp,"flushSessionMetrics");s(K3,"runFlush");s(uP,"flushPending");s(W3,"runHookStatus");ZD="Re-run `maind-mcp-bridge install --hooks-only` to add the missing hooks \u2014 it is idempotent: it adds only what is absent, asks consent per hook, and rewrites no entry you already have except the SessionStart reminder's old `cat`, which it replaces with on-session-reminder (MAIND-630).";s(V3,"readHookWiring");s(q3,"runSyncConfig");s(Ub,"sessionIdOf")});var Bb={};Q(Bb,{runOnSessionBriefing:()=>J3,sessionBriefingCore:()=>z3});async function z3(e,t){let n="";return await Ld("core",e,{hostHint:t.host,collect:s(r=>void(n+=r),"collect")}),n.length===0?null:{kind:"text",event:"SessionStart",text:n}}async function J3(e=process.argv.slice(2)){return ve(["on-session-briefing"],e)}var Gb=w(()=>{"use strict";Po();Oe();s(z3,"sessionBriefingCore");s(J3,"runOnSessionBriefing")});import{existsSync as Y3}from"node:fs";import{mkdir as X3,readFile as Z3,rename as Q3,writeFile as e9}from"node:fs/promises";import{dirname as t9,join as n9}from"node:path";function vl(e=process.env){let t=ee();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??ll,keyFp:tr(t)}}async function Kb(e,t=Date.now(),n=_p){try{if(!Y3(n))return null;let r=JSON.parse(await Z3(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let o=Date.parse(r.fetched_at);if(Number.isNaN(o))return null;let i=r.policy,a=pd(l_(i)),l=i!==void 0&&Ka.every(c=>c in i);return{policy:a,fetchedAt:r.fetched_at,fresh:l&&t-o<r9}}catch{return null}}async function i9(e,t,n,r){try{await X3(t9(r),{recursive:!0,mode:448});let o={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},i=`${r}.tmp`;await e9(i,JSON.stringify(o,null,2),{mode:384}),await Q3(i,r)}catch{}}async function s9(){let e=ee();if(e===null)return null;let t=null;try{t=Z()}catch{t=null}let n=await Qt("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:a9(),projectKey:t,bridgeVersion:K,timeoutMs:o9});if(n===null)return null;try{return pd(JSON.parse(n))}catch{return null}}async function Ar(e,t={}){let n=t.nowMs??Date.now(),r=t.file??_p,o=t.identity===void 0?vl():t.identity;if(o===null)return Gi;let i=await Kb(o,n,r);if(i?.fresh)return i.policy;if(e){let a=await(t.fetcher??s9)();if(a!==null)return await i9(o,a,n,r),a}return i?.policy??Gi}function a9(){try{return ke()}catch{return null}}var _p,r9,o9,Fo=w(()=>{"use strict";Dt();Wt();we();de();Xe();Ln();Je();_p=n9(he,"trigger-policy.json"),r9=12*60*60*1e3,o9=3e3;s(vl,"currentIdentity");s(Kb,"readCachedPolicy");s(i9,"writeCachedPolicy");s(s9,"fetchTriggerPolicy");s(Ar,"resolveTriggerPolicy");s(a9,"safeDeviceId")});function wp(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&/(sh|ch|x|z|ss)es$/.test(t)||t.length>6&&t.endsWith("ungen")?t.slice(0,-2):t.length>5&&t.endsWith("ing")?t.slice(0,-3):t.length>5&&t.endsWith("en")||t.length>4&&t.endsWith("ed")?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function bp(e){return e.length<3||/^\d+$/.test(e)||dP.has(e)||dP.has(wp(e))}function u9(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function d9(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function fP(e){let t=new Set,n=new Set,r=[];for(let o of e.matchAll(p9)){let i=o[0],a=i.toLowerCase();if(r.push(a),/[._-]/.test(i)){let l=d9(a);l.length>=4&&!pP.has(l)&&n.add(l)}for(let l of u9(i)){let c=l.toLowerCase();bp(c)||t.add(wp(c))}}for(let o=0;o+1<r.length;o++){if(/[._-]/.test(r[o])||/[._-]/.test(r[o+1]))continue;let i=`${r[o]}-${r[o+1]}`;pP.has(i)||n.add(i)}return{words:t,compounds:n}}function f9(e){return e.slice(0,8e3).replace(/<pasted_content\b[\s\S]*?(<\/pasted_content>|$)/g," ").replace(/https?:\/\/\S+/g," ").replace(/(?:~|\.{1,2})?\/[\w.@%+~-]+(?:\/[\w.@%+~-]*)+/g," ").replace(/\b[\w.-]+(?:\/[\w.@%+~-]+)+/g," ")}function mP(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function Vb(e){if(!e)return[];let t=[];for(let n of e.split(`
1037
+ `)){let r=m9.exec(n.trim());r&&t.push({scope:r[1],shortId:r[2],id:`conv_${r[2].replace(/-/g,"_")}`,version:Number.parseInt(r[3],10),summary:r[4].trim()})}return t}function h9(e){let t=e.shortId.split("-"),n=new Set;for(let i of t)bp(i)||n.add(wp(i));let r=new Set;for(let i=0;i+1<t.length;i++)!bp(t[i])&&!bp(t[i+1])&&r.add(`${t[i]}-${t[i+1]}`);let o=fP(e.summary);for(let i of o.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(i)&&r.add(i);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:o.words}}function hP(e,t,n=3,r=[]){if(t.length===0)return[];let o=new Set([...r].map(f=>wp(f.toLowerCase()))),i=t.map(h9),a=new Map,l=new Map;for(let f of i){let m=new Set([...f.keyWords,...f.keyCompounds]);for(let h of m)a.set(h,(a.get(h)??0)+1);for(let h of new Set([...m,...f.summaryWords]))l.set(h,(l.get(h)??0)+1)}let c=i.length,u=s(f=>Math.log(1+c/(l.get(f)??c)),"idf"),d=fP(f9(e));for(let f of o)d.words.delete(f);let p=[];for(let f of i){let m=new Set;for(let k of d.words)f.keyWords.has(k)&&m.add(k);for(let k of d.compounds)f.keyCompounds.has(k)&&m.add(k);let h=new Set;for(let k of d.words)!m.has(k)&&f.summaryWords.has(k)&&h.add(k);if(m.size===0&&h.size===0)continue;let g=0;for(let k of m)g+=2*u(k);for(let k of h)g+=u(k);let _=[...m].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),b=m.size>=1&&m.size+h.size>=2&&g>=g9;!_&&!b||p.push({convention:f.convention,score:g,matched:[...m,...h]})}return p.sort((f,m)=>m.score-f.score||f.convention.id.localeCompare(m.convention.id)).slice(0,n)}function b9(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function gP(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],o=new Set,i=s((l,c)=>{if(r.length>=t)return;let u=l.endsWith("()"),d=u?l.slice(0,-2):l;if(d.includes("/")||y9.test(d)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(d)||!c&&!u&&!b9(d))return;let p=d.split("."),f=p[p.length-1];f.length<(c||u?3:4)||_9.has(f.toLowerCase())||o.has(f)||(o.add(f),r.push({name:f,qualifier:p.length>1?p[p.length-2]:null}))},"consider");for(let l of n.matchAll(/`([^`\n]{1,120})`/g))i(l[1].trim(),!0);let a=n.replace(/`[^`\n]{1,120}`/g," ");for(let l of a.matchAll(/(?<![\w$./\\-])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)(?![\w$/\\-])/g))i(l[1],!1);return r}function Wb(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function _P(e,t=2e3){let n=e.conventions,r=e.symbols.filter(u=>u.locations.length>0);if(n.length===0&&r.length===0)return null;let o=new kp(t-yP);if(!o.tryAdd(`${l9} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let i=[],a=[],l=!1;if(n.length>0&&o.tryAdd("Project conventions whose terms appear in this prompt (full text: get_conventions({id})):"))for(let u of n){let d=`- ${u.convention.id} (v${u.convention.version}): ${Wb(u.convention.summary,320)}`;if(!o.tryAdd(d)){l=!0;break}i.push(u.convention.id)}if(r.length>0&&!l){let u=e.repoRoot?` in ${e.repoRoot}`:"";if(o.tryAdd(`Symbols this prompt names, as the local code index places them${u} (files unchanged since indexing):`))for(let d of r){let p=d.locations.slice(0,3),f=p.map(g=>{let _=g.qualifiedName===d.candidate.name?g.kind:`${g.kind} ${g.qualifiedName}`;return`${g.filePath}:${g.startLine} (${_})${g.signature?` '${Wb(g.signature,70)}'`:""}`}).join("; "),m=d.total-p.length,h=`- ${d.candidate.name} \u2192 ${f}${m>0?` (+${m} more \u2014 codebase_search)`:""}`;if(!o.tryAdd(h)){l=!0;break}a.push(d.candidate.name)}}if(i.length===0&&a.length===0)return null;let c=o.toString();return l&&(c+=`
1038
+ (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:c,conventionIds:i,symbolNames:a}}function w9(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>k9}function v9(e){if(e.length===0)return"";let t=e.map(o=>o.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(o=>o[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function S9(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function bP(e,t=1500){let n=new Map;for(let h of e.callers){let g=n.get(h.calleeKey)??[];g.some(_=>_.caller.nodeKey===h.caller.nodeKey)||g.push(h),n.set(h.calleeKey,g)}let r=s(h=>new Set((n.get(h)??[]).map(g=>g.caller.filePath)).size,"fileCount"),o=e.symbols.filter(h=>n.has(h.nodeKey)).sort((h,g)=>r(g.nodeKey)-r(h.nodeKey)||h.startLine-g.startLine),i=e.symbols.reduce((h,g)=>Math.max(h,g.endLine),0),a=e.symbols.filter(h=>!h.qualifiedName.includes(".")&&h.kind!=="module"),l=w9(e.range,i)&&a.length>0;if(o.length===0&&e.importers.length===0&&!l)return null;let c=v9([e.relPath,...e.callers.map(h=>h.caller.filePath),...e.importers]),u=new kp(t-yP),d=c?` Paths below are relative to ${c}.`:"";if(!u.tryAdd(`${c9} ${e.relPath} as the local code index knows it (the index matches this file on disk).${d}`))return null;let p=!1;if(l&&u.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let h="",g=0;for(let b of a){let k=`${b.qualifiedName} L${b.startLine}`,v=h.length===0?k:`${h} \xB7 ${k}`;if(v.length>500)break;h=v,g++}let _=a.length-g;u.tryAdd(_>0?`${h} \xB7 +${_} more`:h)||(p=!0)}if(o.length>0&&!p&&u.tryAdd("Called from other files (import-resolved call graph):"))for(let h of o){let g=n.get(h.nodeKey)??[],_=g.slice(0,3).map(S=>`${S9(S.caller,c)}${S.kind==="calls"?"":` [${S.kind}]`}`),b=g.length-_.length,k=h.signature?` '${Wb(h.signature,80)}'`:"",v=`- ${h.qualifiedName} L${h.startLine}${k} \u2190 ${_.join(", ")}${b>0?` +${b} more`:""}`;if(!u.tryAdd(v)){p=!0;break}}if(e.importers.length>0&&!p){let h=e.importers.slice(0,5).map(k=>k.slice(c.length)),g=e.importers.length-h.length,_=e.importers.length,b=`Imported by ${_} file${_===1?"":"s"}: ${h.join(", ")}${g>0?` +${g} more`:""}`;u.tryAdd(b)||(p=!0)}e.hidden>0&&!p&&u.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let f=e.unchecked??0;if(f>0&&!p&&u.tryAdd(`(+${f} more reference${f===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),u.size<=1)return null;let m=u.toString();return p&&(m+=`
1039
+ (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),m}var l9,c9,dP,pP,p9,m9,g9,y9,_9,kp,yP,k9,kP=w(()=>{"use strict";l9="[maind context \xB7 prompt]",c9="[maind context \xB7 read]",dP=new Set("a an the and or but if then else when while of to in on at by for with from into onto over under about as is are was were be been being it its this that these those there here we you i me my our your they them their he she his her not no yes do does did done can could should would will shall may might must have has had so too very just also only all any some each every more most less than what which who whom whose why how where please let lets make made use used uses using get got new now one two via per etc out up down off again before after first last next previous other same different main default good bad right wrong both much many few own still even ever never always add added adding build builds built change changes changed check checks checked create created fix fixed fixes update updated updates write writes written read reads run runs running start started stop set show find look need needs want work works working try keep move put give take call called see know think tell say ask help mean like sure ok okay thing things stuff way part step steps case cases time today explicit implicit user users agent agents file files code line lines value values name names list type types data text rule rules policy pattern patterns anti convention conventions maind claude project projects repo repository branch branches feature features task tasks issue issues problem error errors bug bugs test tests verify version versions thanks thank gate gates content note notes org block apply applies render renders object objects title titles comment comments description local remote script scripts sync kind strategy request alternative better open close merge merged action reason lesson lessons word words der die das den dem des ein eine einen einem einer eines und oder aber wenn dann sonst als wie was wer wo warum weil dass ist sind war waren sein bin bist hat haben hatte wird werden wurde kann k\xF6nnen koennen k\xF6nnte soll sollen sollte muss m\xFCssen muessen darf nicht kein keine nur auch noch schon mal bitte ich du er sie es wir ihr mich mir dich dir uns euch ihnen sich mit ohne f\xFCr fuer auf aus bei nach vor \xFCber ueber unter zum zur im am um an in von zu bis durch gegen hier da dort jetzt ja nein doch also man dies diese dieser dieses mach mache machen lass lasst gib geht gehen gut schreib schreibe schreiben bau baue bauen pr\xFCf pr\xFCfe pr\xFCfen pruefen lies lesen starte starten teste testen nutze nutzen brauch brauchen datei dateien zeile zeilen neue neuen neu alte alten erst gleich kurz einfach richtig falsch danke".split(/\s+/)),pP=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);s(wp,"stem");s(bp,"isNoise");s(u9,"splitParts");s(d9,"normalizeCompound");p9=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;s(fP,"termsOf");s(f9,"promptForMatching");s(mP,"repoNameWords");m9=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;s(Vb,"parseConventionLines");s(h9,"profileOf");g9=4.5;s(hP,"matchConventions");y9=/\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts|py|pyi|md|mdx|json|jsonc|ya?ml|toml|sql|css|scss|html|sh|txt|lock|env|log|png|svg|jpe?g|gif|pdf)$/i,_9=new Set(["JavaScript","TypeScript","GitHub","GitLab","PostgreSQL","MySQL","SQLite","NodeJS","NextJS","macOS","iOS","iPhone","iPad","iCloud","OpenAI","YouTube","LinkedIn","PowerShell","VSCode","WebSocket","OAuth","PostHog","DevTools","ChatGPT","DeepSeek","OpenVSX","AgentComposer","ClaudeCode","McpServer","README","TODO","FIXME"].map(e=>e.toLowerCase()));s(b9,"looksLikeCode");s(gP,"extractSymbolCandidates");s(Wb,"clip");kp=class{constructor(t){this.budget=t}static{s(this,"Budgeted")}lines=[];used=0;tryAdd(t){let n=t.length+(this.lines.length>0?1:0);return this.used+n>this.budget?!1:(this.lines.push(t),this.used+=n,!0)}get size(){return this.lines.length}toString(){return this.lines.join(`
1040
+ `)}},yP=90;s(_P,"renderPromptContext");k9=2e3;s(w9,"isPartialRead");s(v9,"commonDir");s(S9,"callerLabel");s(bP,"renderReadContext")});import{createHash as x9}from"node:crypto";import{existsSync as wP,mkdirSync as E9,readdirSync as T9,rmSync as A9,statSync as R9,writeFileSync as C9}from"node:fs";import{join as vp}from"node:path";function qb(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function N9(e,t,n=null,r=O9){try{for(let o of T9(e)){let i=vp(e,o);if(i!==n)try{t-R9(i).mtimeMs>r&&A9(i,{recursive:!0,force:!0})}catch{}}}catch{}}var I9,O9,Sl,vP=w(()=>{"use strict";ut();I9=vp(et,"context"),O9=7*24*60*60*1e3;s(qb,"safe");Sl=class e{constructor(t,n){this.root=t;this.dir=n}static{s(this,"SeenMarks")}static forScope(t,n,r=I9){let o=n?`${qb(t)}__${qb(n)}`:qb(t);return new e(r,vp(r,o))}fileFor(t){return vp(this.dir,x9("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return wP(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{wP(this.dir)||(E9(this.dir,{recursive:!0,mode:448}),N9(this.root,n,this.dir));for(let r of t)try{C9(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};s(N9,"sweepStaleScopes")});var El={};Q(El,{INDEX_RELPATH:()=>dr,SOFT_BUDGET_MS:()=>EP,findRepoRoot:()=>pr,isMachinePrompt:()=>CP,loadCachedConventions:()=>AP,promptContextCore:()=>U9,promptContextFor:()=>OP,promptTextOf:()=>RP,readContextCore:()=>K9,readContextFor:()=>NP,runOnPromptContext:()=>B9,runOnReadContext:()=>W9});import{existsSync as SP,readFileSync as D9,realpathSync as P9,statSync as M9}from"node:fs";import{dirname as $9,isAbsolute as xP,join as xl,relative as L9,sep as j9}from"node:path";function F9(e,t){let n=L9(e,t);return!n||n.startsWith("..")||xP(n)?null:n.split(j9).join("/")}function Jb(e){try{let t=M9(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function TP(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Xd(),fb));return t(e)}function AP(e,t={}){let n=t.client??"claude-code";try{let r=t.identity===void 0?vl():t.identity,o=t.identity===void 0&&r!==null?{...r,clientFamily:n}:r;if(e!==null&&o!==null){let i=pu(e,o),a=Ki(i?.result.instructions??null),l=Vb(a);if(l.length>0)return l}}catch{}try{let r=JSON.parse(D9(t.briefingCacheFile??Md(n),"utf8"));if(typeof r.conventions=="string")return Vb(r.conventions)}catch{}return[]}function RP(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function CP(e,t){if(e.is_command===!0)return!0;let n=t.trimStart();return/^\/[A-Za-z][\w:-]*(\s|$)/.test(n)||/^<[a-z][\w-]*[\s>]/.test(n)||n.startsWith("This session is being continued from a previous conversation")}function IP(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";if(!t)return null;let n=typeof e.agent_id=="string"&&e.agent_id.trim()?e.agent_id.trim():null;return{sessionId:t,agentId:n}}async function H9(e,t,n,r){let o;try{o=await r(n)}catch{return[]}try{if(!o.meta().schemaCurrent)return[];let i=o.symbolsNamed(e.map(u=>u.name)),a=o.files([...i.values()].flat().map(u=>u.filePath).slice(0,zb)),l=new Set;for(let[u,d]of a){let p=Jb(xl(t,u));p!==null&&fa(d,p)&&l.add(u)}let c=[];for(let u of e){let d=i.get(u.name)??[],p=u.qualifier===null?[]:d.filter(h=>h.qualifiedName===`${u.qualifier}.${u.name}`),f=p.length>0?p:d,m=f.filter(h=>l.has(h.filePath)).map(h=>({kind:h.kind,qualifiedName:h.qualifiedName,filePath:h.filePath,startLine:h.startLine,signature:h.signature}));m.length>0&&c.push({candidate:u,locations:m,total:f.length})}return c}catch{return[]}finally{try{o.close()}catch{}}}async function OP(e,t={}){let n=t.now??Date.now,r=n(),o=t.env??process.env,i=t.target??Pn(e,o,t.readConfig??re);if(!me(i,{kind:"context",event:"UserPromptSubmit"}))return null;let a=RP(e);if(a.trim().length===0||CP(e,a))return null;let l=IP(e);if(l===null)return null;let c=Sl.forScope(l.sessionId,l.agentId,t.seenRoot),u=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:Vi(i,o)??process.cwd(),d=pr(u),p=l.agentId===null?(t.assignedNotice??((x,T)=>tl(x,T,{hostPids:Fe()})))(l.sessionId,u):null,f=l.agentId===null?(t.threadNotice??((x,T)=>Ed(x,T,{hostPids:Fe()})))(l.sessionId,u):null,m=[p,f].filter(x=>x!==null).map(x=>`[maind] ${x}`),h=m.length===0?null:m.join(`
1041
1041
 
1042
- `),g=hP(a,(t.loadConventions??AP)(d,{client:$d(i.host)}),6,mP(d)).filter(x=>!c.has(`conv:${x.convention.id}@${x.convention.version}`)).slice(0,3),_=gP(a).filter(x=>!c.has(`sym:${d??""}:${x.name}`)),b=d===null?null:xl(d,dr),k=_.length>0&&b!==null&&d!==null&&SP(b)&&n()-r<EP?await j9(_,d,b,t.openReader??TP):[],v=_P({repoRoot:d,conventions:g,symbols:k});if(v===null)return h;let S=new Map(g.map(x=>[x.convention.id,x.convention.version]));return c.mark([...v.conventionIds.map(x=>`conv:${x}@${S.get(x)??0}`),...v.symbolNames.map(x=>`sym:${d??""}:${x}`)],n()),h===null?v.text:`${h}
1042
+ `),g=hP(a,(t.loadConventions??AP)(d,{client:$d(i.host)}),6,mP(d)).filter(x=>!c.has(`conv:${x.convention.id}@${x.convention.version}`)).slice(0,3),_=gP(a).filter(x=>!c.has(`sym:${d??""}:${x.name}`)),b=d===null?null:xl(d,dr),k=_.length>0&&b!==null&&d!==null&&SP(b)&&n()-r<EP?await H9(_,d,b,t.openReader??TP):[],v=_P({repoRoot:d,conventions:g,symbols:k});if(v===null)return h;let S=new Map(g.map(x=>[x.convention.id,x.convention.version]));return c.mark([...v.conventionIds.map(x=>`conv:${x}@${S.get(x)??0}`),...v.symbolNames.map(x=>`sym:${d??""}:${x}`)],n()),h===null?v.text:`${h}
1043
1043
 
1044
- ${v.text}`}async function F9(e,t){Fb(e);let n=await OP(e,{target:t});return n===null?null:{kind:"context",event:"UserPromptSubmit",text:n}}async function H9(){return ve(["on-prompt-context"])}function U9(e){let t=e.tool_input;if(t===null||typeof t!="object")return null;let n=t,r=s(u=>typeof u=="number"&&Number.isFinite(u)?u:void 0,"num"),o=Array.isArray(n.view_range)?n.view_range:null,i=r(n.startLine)??r(o?.[0]),a=r(n.endLine)??r(o?.[1]);if(i!==void 0)return{offset:i,limit:a!==void 0&&a>=i?a-i+1:void 0};let l=r(n.offset),c=r(n.limit);return l===void 0&&c===void 0?null:{offset:l,limit:c}}async function NP(e,t={}){let n=t.now??Date.now,r=Mt(e).find(h=>h.act==="read");if(r===void 0)return null;let o=t.target??Pn(e,t.env??process.env,t.readConfig??re);if(!me(o,{kind:"context",event:"PreToolUse"}))return null;let i=r.path;if(ui(i)===null||Js(i))return null;let a=IP(e);if(a===null)return null;let l=be(e,o,t.env??process.env),c=xP(i)?i:xl(l,i),u;try{u=N9(c)}catch{return null}let d=pr(P9(u));if(d===null)return null;let p=xl(d,dr);if(!SP(p))return null;let f=L9(d,u);if(f===null)return null;let m=await(t.openReader??TP)(p);try{let h=m.meta();if(!h.schemaCurrent)return null;let g=m.file(f);if(g===null)return null;let _=Jb(u);if(_===null||!fa(g,_))return null;let b=Sl.forScope(a.sessionId,a.agentId,t.seenRoot),k=`read:${d}:${f}@${g.contentHash}`;if(b.has(k))return null;let v=m.symbolsInFile(f),S=h.edgesDirty?[]:m.callersOfFile(f),x=h.edgesDirty?[]:m.importersOf(f),T=[...new Set([...S.map(ae=>ae.caller.filePath),...x])],A=T.slice(0,zb),L=new Set(T.slice(zb)),R=m.files(A),P=new Set;for(let ae of A){let rt=R.get(ae),ge=rt===void 0?null:Jb(xl(d,ae));rt!==void 0&&ge!==null&&fa(rt,ge)&&P.add(ae)}let D=s(ae=>S.filter(rt=>ae.has(rt.caller.filePath)).length+x.filter(rt=>ae.has(rt)).length,"countIn"),E=S.filter(ae=>P.has(ae.caller.filePath)).map(ae=>({calleeKey:ae.calleeKey,kind:ae.kind,caller:{nodeKey:ae.caller.nodeKey,kind:ae.caller.kind,qualifiedName:ae.caller.qualifiedName,filePath:ae.caller.filePath,startLine:ae.caller.startLine}})),F=x.filter(ae=>P.has(ae)),q=D(L),Ue=S.length-E.length+(x.length-F.length)-q,Ht=bP({relPath:f,symbols:v,callers:E,importers:F,hidden:Ue,unchecked:q,range:U9(e)});return Ht===null?null:(b.mark([k],n()),Ht)}finally{m.close()}}async function B9(e,t){let n=await NP(e,{target:t});return n===null?null:{kind:"context",event:"PreToolUse",text:n}}async function G9(){return ve(["on-read-context"])}var EP,zb,Tl=w(()=>{"use strict";Me();Ce();Dd();Po();Fo();Wt();kP();vP();kd();G_();Lt();ld();Oe();tt();Ie();EP=200,zb=200;s(L9,"repoRelative");s(Jb,"diskStat");s(TP,"openReader");s(AP,"loadCachedConventions");s(RP,"promptTextOf");s(CP,"isMachinePrompt");s(IP,"scopeOf");s(j9,"locateSymbols");s(OP,"promptContextFor");s(F9,"promptContextCore");s(H9,"runOnPromptContext");s(U9,"readRangeOf");s(NP,"readContextFor");s(B9,"readContextCore");s(G9,"runOnReadContext")});import{posix as _n}from"node:path";function MP(e,t){let n=[],r="",o=!0,i=!1,a=!1,l=!0,c=s(()=>{a&&n.push({kind:"word",word:{text:r,literal:o,quoted:i}}),r="",o=!0,i=!1,a=!1,l=!0},"endWord"),u=0,d=e;for(;u<d.length;){let p=d[u];if(p===" "||p===" "||p===`
1044
+ ${v.text}`}async function U9(e,t){Fb(e);let n=await OP(e,{target:t});return n===null?null:{kind:"context",event:"UserPromptSubmit",text:n}}async function B9(){return ve(["on-prompt-context"])}function G9(e){let t=e.tool_input;if(t===null||typeof t!="object")return null;let n=t,r=s(u=>typeof u=="number"&&Number.isFinite(u)?u:void 0,"num"),o=Array.isArray(n.view_range)?n.view_range:null,i=r(n.startLine)??r(o?.[0]),a=r(n.endLine)??r(o?.[1]);if(i!==void 0)return{offset:i,limit:a!==void 0&&a>=i?a-i+1:void 0};let l=r(n.offset),c=r(n.limit);return l===void 0&&c===void 0?null:{offset:l,limit:c}}async function NP(e,t={}){let n=t.now??Date.now,r=Mt(e).find(h=>h.act==="read");if(r===void 0)return null;let o=t.target??Pn(e,t.env??process.env,t.readConfig??re);if(!me(o,{kind:"context",event:"PreToolUse"}))return null;let i=r.path;if(ui(i)===null||Js(i))return null;let a=IP(e);if(a===null)return null;let l=be(e,o,t.env??process.env),c=xP(i)?i:xl(l,i),u;try{u=P9(c)}catch{return null}let d=pr($9(u));if(d===null)return null;let p=xl(d,dr);if(!SP(p))return null;let f=F9(d,u);if(f===null)return null;let m=await(t.openReader??TP)(p);try{let h=m.meta();if(!h.schemaCurrent)return null;let g=m.file(f);if(g===null)return null;let _=Jb(u);if(_===null||!fa(g,_))return null;let b=Sl.forScope(a.sessionId,a.agentId,t.seenRoot),k=`read:${d}:${f}@${g.contentHash}`;if(b.has(k))return null;let v=m.symbolsInFile(f),S=h.edgesDirty?[]:m.callersOfFile(f),x=h.edgesDirty?[]:m.importersOf(f),T=[...new Set([...S.map(ae=>ae.caller.filePath),...x])],A=T.slice(0,zb),L=new Set(T.slice(zb)),R=m.files(A),P=new Set;for(let ae of A){let rt=R.get(ae),ge=rt===void 0?null:Jb(xl(d,ae));rt!==void 0&&ge!==null&&fa(rt,ge)&&P.add(ae)}let D=s(ae=>S.filter(rt=>ae.has(rt.caller.filePath)).length+x.filter(rt=>ae.has(rt)).length,"countIn"),E=S.filter(ae=>P.has(ae.caller.filePath)).map(ae=>({calleeKey:ae.calleeKey,kind:ae.kind,caller:{nodeKey:ae.caller.nodeKey,kind:ae.caller.kind,qualifiedName:ae.caller.qualifiedName,filePath:ae.caller.filePath,startLine:ae.caller.startLine}})),F=x.filter(ae=>P.has(ae)),q=D(L),Ue=S.length-E.length+(x.length-F.length)-q,Ht=bP({relPath:f,symbols:v,callers:E,importers:F,hidden:Ue,unchecked:q,range:G9(e)});return Ht===null?null:(b.mark([k],n()),Ht)}finally{m.close()}}async function K9(e,t){let n=await NP(e,{target:t});return n===null?null:{kind:"context",event:"PreToolUse",text:n}}async function W9(){return ve(["on-read-context"])}var EP,zb,Tl=w(()=>{"use strict";Me();Ce();Dd();Po();Fo();Wt();kP();vP();kd();G_();Lt();ld();Oe();tt();Ie();EP=200,zb=200;s(F9,"repoRelative");s(Jb,"diskStat");s(TP,"openReader");s(AP,"loadCachedConventions");s(RP,"promptTextOf");s(CP,"isMachinePrompt");s(IP,"scopeOf");s(H9,"locateSymbols");s(OP,"promptContextFor");s(U9,"promptContextCore");s(B9,"runOnPromptContext");s(G9,"readRangeOf");s(NP,"readContextFor");s(K9,"readContextCore");s(W9,"runOnReadContext")});import{posix as _n}from"node:path";function MP(e,t){let n=[],r="",o=!0,i=!1,a=!1,l=!0,c=s(()=>{a&&n.push({kind:"word",word:{text:r,literal:o,quoted:i}}),r="",o=!0,i=!1,a=!1,l=!0},"endWord"),u=0,d=e;for(;u<d.length;){let p=d[u];if(p===" "||p===" "||p===`
1045
1045
  `||p==="\r"){c(),u+=1;continue}if(p==="'"){let f=d.indexOf("'",u+1);if(f<0){o=!1,r+=d.slice(u+1),a=!0,i=!0;break}r+=d.slice(u+1,f),a=!0,i=!0,l=!1,u=f+1;continue}if(p==='"'){let f=u+1,m=!1;for(;f<d.length;){let h=d[f];if(h==="\\"&&f+1<d.length&&'"\\$`'.includes(d[f+1])){r+=d[f+1],f+=2;continue}if(h==='"'){m=!0;break}(h==="$"||h==="`")&&(o=!1),r+=h,f+=1}m||(o=!1),a=!0,i=!0,l=!1,u=m?f+1:d.length;continue}if(p==="\\"){let f=d[u+1];if(f===`
1046
- `){u+=2;continue}f!==void 0&&(r+=f),a=!0,l=!1,u+=2;continue}if(p==="$"||p==="`"){o=!1,a=!0,l=!1;let f=p==="`"?"`":d[u+1]==="("?")":null;if(f===null){r+=p,u+=1;continue}let m=p==="`"?u+1:u+2,h=1;for(;m<d.length&&h>0;){let g=d[m];f===")"&&g==="("?h+=1:g===f&&(h-=1),m+=1}r+=d.slice(u,m),u=m;continue}if(p==="#"&&!a)break;if(p===">"||p==="<"||p==="&"&&d[u+1]===">"){a&&!(o&&!i&&/^\d+$/.test(r))?c():(r="",a=!1,o=!0,i=!1);let f=d.slice(u),m=["&>>","&>",">>",">|",">&","<<<","<<-","<<","<&","<>",">","<"].find(h=>f.startsWith(h));n.push({kind:"redir",op:m==="<<-"?"<<":m}),u+=m.length,l=!0;continue}if((p==="("||p===")")&&!a){n.push({kind:p==="("?"open":"close"}),u+=1;continue}if(p===")"&&a){c(),n.push({kind:"close"}),u+=1;continue}if(p==="&"){c(),u+=1;continue}if((K9.has(p)||p==="{"||p==="}")&&(a===!1&&(p==="{"||p==="}")&&/[\s;]/.test(d[u+1]??" ")||(o=!1)),p==="~"&&l&&!a){let f=d[u+1];if(f===void 0||f==="/"||/\s/.test(f)){t?r+=t:o=!1,a=!0,l=!1,u+=1;continue}o=!1}r+=p,a=!0,l=!1,u+=1}return c(),n}function Yb(e){return e.text.split("/").pop()??e.text}function $P(e){let t=0;for(;t<e.length;){let n=e[t];if(!n.quoted&&DP.test(n.text)){t+=1;continue}if(!n.quoted&&V9.has(n.text)){t+=1;continue}let r=Yb(n);if(!n.quoted&&r==="env"){for(t+=1;t<e.length&&(e[t].text.startsWith("-")||DP.test(e[t].text));)t+=1;continue}if(!n.quoted&&W9.has(r)){if(t+=1,r==="nice"&&e[t]?.text==="-n")t+=2;else for(;t<e.length&&e[t].text.startsWith("-");)t+=1;continue}return t}return-1}function Al(e,t){let n=[],r=new Map,o=0,i=!1;for(;o<e.length;){let a=e[o];if(!i&&!a.quoted&&a.text==="--"){i=!0,o+=1;continue}if(!i&&a.text.startsWith("-")&&a.text.length>1){let l=a.text.indexOf("=");if(a.text.startsWith("--")&&l>0){r.set(a.text.slice(0,l),{...a,text:a.text.slice(l+1)}),o+=1;continue}if(t.has(a.text)){r.set(a.text,e[o+1]??null),o+=2;continue}r.set(a.text,null),o+=1;continue}n.push(a),o+=1}return{ops:n,opts:r}}function PP(e,t){let n=new Set(t==="install"?["-t","-m","-o","-g","-S"]:["-t","-S"]),{ops:r,opts:o}=Al(e,n);if(t==="install"&&o.has("-d"))return[];let i=[],a=s(d=>{t==="mv"&&i.push({word:d,act:"edit"})},"sourceAct"),l=o.get("-t")??o.get("--target-directory")??null;if(l){for(let d of r)a(d),i.push({word:{...l,text:_n.join(l.text,_n.basename(d.text)),literal:l.literal&&d.literal},act:"write"});return i}if(r.length<2)return[];let c=r[r.length-1],u=r.slice(0,-1);for(let d of u)a(d);if(u.length>1||c.text.endsWith("/"))for(let d of u)i.push({word:{...c,text:_n.join(c.text,_n.basename(d.text)),literal:c.literal&&d.literal},act:"write"});else i.push({word:c,act:"write",intoDirFrom:u[0]});return i}function q9(e){let t=!1,n=!1,r=[],o=0,i=!1;for(;o<e.length;){let l=e[o],c=l.text;if(!i&&!l.quoted&&c==="--"){i=!0,o+=1;continue}if(!i&&!l.quoted&&c.startsWith("-")&&c.length>1){if(c==="-i"||c==="-I"){t=!0;let u=e[o+1];u&&(u.quoted&&u.text===""||/^\.[\w.-]*$/.test(u.text)&&!u.quoted)&&(o+=1),o+=1;continue}if(c.startsWith("--in-place")){t=!0,o+=1;continue}if(/^-[A-Za-z]*i/.test(c)&&!c.startsWith("--")){if(t=!0,/^-[A-Za-z]*[ef]$/.test(c)){n=!0,o+=2;continue}o+=1;continue}if(c==="-e"||c==="-f"||c==="--expression"||c==="--file"){n=!0,o+=2;continue}if(c.startsWith("--expression=")||c.startsWith("--file=")){n=!0,o+=1;continue}if(/^-[A-Za-z]*[ef]$/.test(c)){n=!0,o+=2;continue}if(c==="-l"){o+=2;continue}o+=1;continue}r.push(l),o+=1}return t?(n?r:r.slice(1)).map(l=>({word:l,act:"edit"})):[]}function z9(e){let t=$P(e);if(t<0)return{found:[]};let n=e[t],r=n.quoted?n.text:Yb(n),o=e.slice(t+1);switch(r){case"cd":case"pushd":{let{ops:i}=Al(o,new Set),a=i[0];return a===void 0?{found:[],cd:r==="cd"?"home":"unknown"}:a.text==="-"?{found:[],cd:"unknown"}:{found:[],cd:a}}case"popd":return{found:[],cd:"unknown"};case"tee":{let{ops:i,opts:a}=Al(o,new Set),l=a.has("-a")||a.has("--append");return{found:i.filter(c=>c.text!=="-").map(c=>({word:c,act:l?"edit":"write"}))}}case"sed":return{found:q9(o)};case"cp":case"mv":case"install":return{found:PP(o,r)};case"git":return o[0]?.text==="mv"?{found:PP(o.slice(1),"mv")}:{found:[]};case"touch":{let{ops:i}=Al(o,new Set(["-d","-r","-t"]));return{found:i.map(a=>({word:a,act:"write"}))}}case"rm":{let{ops:i}=Al(o,new Set);return{found:i.map(a=>({word:a,act:"edit"}))}}case"dd":{let i=o.find(a=>a.text.startsWith("of="));return i?{found:[{word:{...i,text:i.text.slice(3)},act:"write"}]}:{found:[]}}default:return{found:[]}}}function LP(e){return e==="-"||e.startsWith("/dev/")||e==="/dev"||e.startsWith("/proc/")}function jP(e,t={}){if(typeof e!="string"||e.length===0)return{targets:[],dirs:[]};let n=t.home??null,r=new Set,o=t.max??32,i="",a=[],l=new Map,c=s(d=>{if(!d.literal||d.text.length===0||d.text.includes("\0"))return null;if(_n.isAbsolute(d.text))return _n.normalize(d.text);if(i===null)return null;let p=_n.normalize(_n.join(i===""?".":i,d.text));return p==="."?"":p.replace(/^\.\//,"")},"resolve"),u=s((d,p,f)=>{if(l.size>=o)return;let m=c(d);if(m===null||m===""||LP(m))return;let h=l.get(m);if(h&&(h.act==="write"||p==="edit"))return;let g={path:m,act:p};f&&f.literal&&(g.intoDirFrom=_n.basename(f.text)),l.set(m,g)},"add");for(let d of Ao(e)){let p=MP(d,n),f=!1,m=0,h=[];for(let b=0;b<p.length;b++){let k=p[b];if(k.kind==="open"){h.length===0&&(f=!0);continue}if(k.kind==="close"){m+=1;continue}if(k.kind==="word"){h.push(k.word);continue}let v=p[b+1],S=v?.kind==="word"?v.word:null;switch(S!==null&&(b+=1),k.op){case">":case">|":case"&>":S&&u(S,"write");break;case">>":case"&>>":S&&u(S,"edit");break;case">&":S&&!/^(\d+|-)$/.test(S.text)&&u(S,"write");break;default:break}}f&&a.push(i);let{found:g,cd:_}=z9(h);for(let b of g)u(b.word,b.act,b.intoDirFrom);if(_!==void 0){if(_==="unknown")i=null;else if(_==="home")i=n?_n.normalize(n):null;else{let b=c(_);i=b===null?null:b}i!==null&&i!==""&&r.add(i)}for(let b=0;b<m&&a.length>0;b++)i=a.pop()}return{targets:[...l.values()],dirs:[...r]}}function FP(e){if(typeof e!="string"||e.trim().length===0)return!1;for(let t of Ao(e)){let n=MP(t,null);for(let l=0;l<n.length;l++){let c=n[l];if(c.kind!=="redir"||!c.op.includes(">")||c.op==="<>")continue;let u=n[l+1];if(u?.kind!=="word")return!0;if(!(c.op===">&"&&/^(\d+|-)$/.test(u.word.text))&&!(u.word.literal&&LP(u.word.text)))return!0}let r=n.flatMap(l=>l.kind==="word"?[l.word]:[]),o=$P(r);if(o<0)continue;let i=Yb(r[o]),a=r.slice(o+1);if(i==="git"){let l=a.find(c=>!c.text.startsWith("-"));if(!l||!Y9.has(l.text))return!0;continue}if(!J9.has(i)||i==="sed"&&a.some(l=>!l.quoted&&(/^-[A-Za-z]*i/.test(l.text)||l.text.startsWith("--in-place")))||i==="find"&&a.some(l=>["-delete","-exec","-execdir","-ok","-okdir","-fprint","-fprintf","-fls"].includes(l.text))||i==="awk"&&a.some(l=>/>/.test(l.text)||l.text.includes("system(")))return!0}return!1}var K9,DP,W9,V9,J9,Y9,HP=w(()=>{"use strict";Dt();K9=new Set(["*","?","["]);s(MP,"lexSegment");DP=/^[A-Za-z_][A-Za-z0-9_]*=/,W9=new Set(["sudo","time","nohup","command","exec","builtin","nice"]),V9=new Set(["do","then","else","elif","if","while","until","!","{"]);s(Yb,"bare");s($P,"programIndex");s(Al,"operands");s(PP,"copyLike");s(q9,"sedTargets");s(z9,"commandTargets");s(LP,"isPseudoPath");s(jP,"shellAnalysis");J9=new Set(["ls","cat","head","tail","less","more","grep","egrep","fgrep","rg","ag","wc","echo","printf","pwd","which","whereis","type","stat","file","du","df","basename","dirname","realpath","readlink","sort","uniq","cut","tr","column","nl","diff","cmp","comm","jq","yq","date","env","printenv","id","whoami","uname","ps","pgrep","lsof","test","true","false","sleep","tree","fd","cd","pushd","popd","export","set","source",".","sed","awk","find"]),Y9=new Set(["log","show","status","diff","grep","cat-file","rev-parse","ls-files","blame","merge-base","describe","reflog","ls-remote","for-each-ref","symbolic-ref","check-ignore","rev-list","shortlog","fetch"]);s(FP,"shellMayWrite")});var tk={};Q(tk,{SHELL_CALLS_DIR:()=>Zb,SHELL_CHANGES_SUBCOMMAND:()=>l5,SHELL_WRITE_SUBCOMMAND:()=>a5,bashCommandOf:()=>Qb,changedSince:()=>YP,parsePorcelainZ:()=>JP,pruneStamps:()=>zP,shellChangesCore:()=>m5,shellWriteCore:()=>p5,stampKey:()=>ek,takeStamp:()=>qP,writeStamp:()=>VP});import{execFileSync as X9}from"node:child_process";import{createHash as Z9}from"node:crypto";import{existsSync as BP,lstatSync as Q9,mkdirSync as e5,readFileSync as t5,readdirSync as n5,renameSync as r5,statSync as Xb,unlinkSync as GP,writeFileSync as o5}from"node:fs";import{homedir as i5}from"node:os";import{isAbsolute as UP,join as Rr,relative as s5}from"node:path";function Qb(e){if(e.tool_name!=="Bash")return null;let t=e.tool_input?.command;return typeof t=="string"&&t.trim().length>0?t:null}function ys(e,t,n,r){return{...e,tool_name:t,tool_input:{file_path:n},...r!==void 0?{cwd:r}:{}}}function WP(){try{return new Set(re()?.declined_hooks??[])}catch{return new Set}}function ek(e,t){let n=typeof e.tool_use_id=="string"&&e.tool_use_id.length>0?`tool:${e.tool_use_id}`:`cmd:${typeof e.session_id=="string"?e.session_id:""}\0${t}`;return Z9("sha256").update(n).digest("hex").slice(0,32)}function VP(e,t,n){e5(e,{recursive:!0,mode:448});let r=Rr(e,`${t}.json`),o=`${r}.${process.pid}.tmp`;o5(o,JSON.stringify(n),{mode:384}),r5(o,r)}function qP(e,t,n){let r=Rr(e,`${t}.json`);try{let o=JSON.parse(t5(r,"utf8"));try{GP(r)}catch{}return o.v!==1||typeof o.at!="number"||n-o.at>KP?null:{v:1,at:o.at,dirs:Array.isArray(o.dirs)?o.dirs.filter(i=>typeof i=="string"):[],reported:Array.isArray(o.reported)?o.reported.filter(i=>typeof i=="string"):[]}}catch{return null}}function zP(e,t){try{for(let n of n5(e)){let r=Rr(e,n);try{t-Xb(r).mtimeMs>KP&&GP(r)}catch{}}}catch{}}function d5(e,t,n){let{targets:r,dirs:o}=jP(e,{home:n});return{targets:r.map(a=>{let l=UP(a.path)?a.path:Rr(t,a.path);if(a.intoDirFrom!==void 0)try{Xb(l).isDirectory()&&(l=Rr(l,a.intoDirFrom))}catch{}return{abs:l,act:a.act}}),dirs:o.map(a=>UP(a)?a:Rr(t,a))}}async function p5(e,t,n={}){let r=Qb(e);if(r===null)return null;let o=n.nowMs??Date.now(),i=be(e,t),{targets:a,dirs:l}=d5(r,i,n.home??i5()),c=n.stampDir??Zb;try{FP(r)&&(VP(c,ek(e,r),{v:1,at:o,dirs:[i,...l],reported:a.map(p=>p.abs)}),Math.random()<.05&&zP(c,o))}catch{}if(a.length===0)return null;let u=n.declined??WP(),d=[];if(!u.has("on-file-write"))for(let p of a){if(p.act!=="write"||BP(p.abs))continue;let f=await Hb(ys(e,"Write",p.abs,jo(p.abs)),t);if(f!==null)return f}if(!u.has("on-file-edit"))for(let p of a){let f=await hp(ys(e,p.act==="write"?"Write":"Edit",p.abs),t);if(f!==null){d.push(f);break}}if(!u.has("on-repo-health"))for(let p of a){let f=await dp(ys(e,"Edit",p.abs),t);f!==null&&d.push(f)}return Sp(d)}function JP(e){let t=e.split("\0"),n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.length<4)continue;let i=o.slice(0,2),a=o.slice(3);(i[0]==="R"||i[0]==="C")&&(r+=1),!i.includes("D")&&n.push({path:a,untracked:i==="??"})}return n}function f5(e){try{return X9("git",["status","--porcelain=v1","-z","--untracked-files=all"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:8*1024*1024})}catch{return null}}function YP(e,t,n=u5){let r=new Set;for(let a of e.dirs)try{let l=mn(a),c=BP(l)&&Xb(l).isDirectory()?l:jo(l);r.add(gt(c))}catch{}let o=new Set(e.reported.map(a=>{try{return mn(a)}catch{return a}})),i=[];for(let a of r){let l=t(a);if(l!==null)for(let c of JP(l)){let u=Rr(a,c.path);if(!o.has(u)){try{let d=Q9(u);if(!d.isFile()||d.mtimeMs<e.at-c5)continue}catch{continue}if(i.push({abs:u,root:a,rel:c.path,untracked:c.untracked}),i.length>=n)return i}}}return i}async function m5(e,t,n={}){let r=Qb(e);if(r===null||!me(t,{kind:"context",event:"PostToolUse"}))return null;let o=qP(n.stampDir??Zb,ek(e,r),n.nowMs??Date.now());if(o===null)return null;let i=YP(o,n.status??f5);if(i.length===0)return null;let a=n.declined??WP(),l=[];if(!a.has("on-file-write")){for(let d of i)if(d.untracked)try{let p=await Tn(d.root,d.rel);if(p.namespace===null)continue;if(!p.taken&&p.outOfOrder!==null){let m=p.outOfOrder;l.push(`'${d.rel}' is older than the newest migration on ${m.sighting.where} (${m.newest}) \u2014 the cloud push after the merge refuses it without --include-all. Rename it to ${p.suggestion} or a fresh timestamp.`);continue}if(!p.taken)continue;let f=p.sightings.map(m=>`${m.path} (${m.where})`).join(", ");l.push(`'${d.rel}' claims ${p.namespace.prefix}${p.number}, which is already taken: ${f}. Next free: ${p.namespace.prefix}${p.suggestion}. Rename it before anything refers to that number.`)}catch{}}let c=s(d=>d!==null&&(d.kind==="context"||d.kind==="text")?d.text:null,"textOf");if(!a.has("on-file-edit"))for(let d of i){let p=c(await hp(ys(e,"Edit",d.abs),t));if(p!==null){l.push(p);break}}if(!a.has("on-repo-health"))for(let d of i){let p=c(await dp(ys(e,"Edit",d.abs),t));p!==null&&l.push(p)}if(!a.has("on-write-health"))for(let d of i){let p=c(await Mb(ys(e,"Edit",d.abs),t));p!==null&&l.push(p)}return l.length===0?null:{kind:"context",event:"PostToolUse",text:`[maind] This Bash call changed files its command line did not name (seen via git status: ${i.map(d=>s5(d.root,d.abs)||d.abs).slice(0,5).join(", ")}${i.length>5?", \u2026":""}):
1046
+ `){u+=2;continue}f!==void 0&&(r+=f),a=!0,l=!1,u+=2;continue}if(p==="$"||p==="`"){o=!1,a=!0,l=!1;let f=p==="`"?"`":d[u+1]==="("?")":null;if(f===null){r+=p,u+=1;continue}let m=p==="`"?u+1:u+2,h=1;for(;m<d.length&&h>0;){let g=d[m];f===")"&&g==="("?h+=1:g===f&&(h-=1),m+=1}r+=d.slice(u,m),u=m;continue}if(p==="#"&&!a)break;if(p===">"||p==="<"||p==="&"&&d[u+1]===">"){a&&!(o&&!i&&/^\d+$/.test(r))?c():(r="",a=!1,o=!0,i=!1);let f=d.slice(u),m=["&>>","&>",">>",">|",">&","<<<","<<-","<<","<&","<>",">","<"].find(h=>f.startsWith(h));n.push({kind:"redir",op:m==="<<-"?"<<":m}),u+=m.length,l=!0;continue}if((p==="("||p===")")&&!a){n.push({kind:p==="("?"open":"close"}),u+=1;continue}if(p===")"&&a){c(),n.push({kind:"close"}),u+=1;continue}if(p==="&"){c(),u+=1;continue}if((V9.has(p)||p==="{"||p==="}")&&(a===!1&&(p==="{"||p==="}")&&/[\s;]/.test(d[u+1]??" ")||(o=!1)),p==="~"&&l&&!a){let f=d[u+1];if(f===void 0||f==="/"||/\s/.test(f)){t?r+=t:o=!1,a=!0,l=!1,u+=1;continue}o=!1}r+=p,a=!0,l=!1,u+=1}return c(),n}function Yb(e){return e.text.split("/").pop()??e.text}function $P(e){let t=0;for(;t<e.length;){let n=e[t];if(!n.quoted&&DP.test(n.text)){t+=1;continue}if(!n.quoted&&z9.has(n.text)){t+=1;continue}let r=Yb(n);if(!n.quoted&&r==="env"){for(t+=1;t<e.length&&(e[t].text.startsWith("-")||DP.test(e[t].text));)t+=1;continue}if(!n.quoted&&q9.has(r)){if(t+=1,r==="nice"&&e[t]?.text==="-n")t+=2;else for(;t<e.length&&e[t].text.startsWith("-");)t+=1;continue}return t}return-1}function Al(e,t){let n=[],r=new Map,o=0,i=!1;for(;o<e.length;){let a=e[o];if(!i&&!a.quoted&&a.text==="--"){i=!0,o+=1;continue}if(!i&&a.text.startsWith("-")&&a.text.length>1){let l=a.text.indexOf("=");if(a.text.startsWith("--")&&l>0){r.set(a.text.slice(0,l),{...a,text:a.text.slice(l+1)}),o+=1;continue}if(t.has(a.text)){r.set(a.text,e[o+1]??null),o+=2;continue}r.set(a.text,null),o+=1;continue}n.push(a),o+=1}return{ops:n,opts:r}}function PP(e,t){let n=new Set(t==="install"?["-t","-m","-o","-g","-S"]:["-t","-S"]),{ops:r,opts:o}=Al(e,n);if(t==="install"&&o.has("-d"))return[];let i=[],a=s(d=>{t==="mv"&&i.push({word:d,act:"edit"})},"sourceAct"),l=o.get("-t")??o.get("--target-directory")??null;if(l){for(let d of r)a(d),i.push({word:{...l,text:_n.join(l.text,_n.basename(d.text)),literal:l.literal&&d.literal},act:"write"});return i}if(r.length<2)return[];let c=r[r.length-1],u=r.slice(0,-1);for(let d of u)a(d);if(u.length>1||c.text.endsWith("/"))for(let d of u)i.push({word:{...c,text:_n.join(c.text,_n.basename(d.text)),literal:c.literal&&d.literal},act:"write"});else i.push({word:c,act:"write",intoDirFrom:u[0]});return i}function J9(e){let t=!1,n=!1,r=[],o=0,i=!1;for(;o<e.length;){let l=e[o],c=l.text;if(!i&&!l.quoted&&c==="--"){i=!0,o+=1;continue}if(!i&&!l.quoted&&c.startsWith("-")&&c.length>1){if(c==="-i"||c==="-I"){t=!0;let u=e[o+1];u&&(u.quoted&&u.text===""||/^\.[\w.-]*$/.test(u.text)&&!u.quoted)&&(o+=1),o+=1;continue}if(c.startsWith("--in-place")){t=!0,o+=1;continue}if(/^-[A-Za-z]*i/.test(c)&&!c.startsWith("--")){if(t=!0,/^-[A-Za-z]*[ef]$/.test(c)){n=!0,o+=2;continue}o+=1;continue}if(c==="-e"||c==="-f"||c==="--expression"||c==="--file"){n=!0,o+=2;continue}if(c.startsWith("--expression=")||c.startsWith("--file=")){n=!0,o+=1;continue}if(/^-[A-Za-z]*[ef]$/.test(c)){n=!0,o+=2;continue}if(c==="-l"){o+=2;continue}o+=1;continue}r.push(l),o+=1}return t?(n?r:r.slice(1)).map(l=>({word:l,act:"edit"})):[]}function Y9(e){let t=$P(e);if(t<0)return{found:[]};let n=e[t],r=n.quoted?n.text:Yb(n),o=e.slice(t+1);switch(r){case"cd":case"pushd":{let{ops:i}=Al(o,new Set),a=i[0];return a===void 0?{found:[],cd:r==="cd"?"home":"unknown"}:a.text==="-"?{found:[],cd:"unknown"}:{found:[],cd:a}}case"popd":return{found:[],cd:"unknown"};case"tee":{let{ops:i,opts:a}=Al(o,new Set),l=a.has("-a")||a.has("--append");return{found:i.filter(c=>c.text!=="-").map(c=>({word:c,act:l?"edit":"write"}))}}case"sed":return{found:J9(o)};case"cp":case"mv":case"install":return{found:PP(o,r)};case"git":return o[0]?.text==="mv"?{found:PP(o.slice(1),"mv")}:{found:[]};case"touch":{let{ops:i}=Al(o,new Set(["-d","-r","-t"]));return{found:i.map(a=>({word:a,act:"write"}))}}case"rm":{let{ops:i}=Al(o,new Set);return{found:i.map(a=>({word:a,act:"edit"}))}}case"dd":{let i=o.find(a=>a.text.startsWith("of="));return i?{found:[{word:{...i,text:i.text.slice(3)},act:"write"}]}:{found:[]}}default:return{found:[]}}}function LP(e){return e==="-"||e.startsWith("/dev/")||e==="/dev"||e.startsWith("/proc/")}function jP(e,t={}){if(typeof e!="string"||e.length===0)return{targets:[],dirs:[]};let n=t.home??null,r=new Set,o=t.max??32,i="",a=[],l=new Map,c=s(d=>{if(!d.literal||d.text.length===0||d.text.includes("\0"))return null;if(_n.isAbsolute(d.text))return _n.normalize(d.text);if(i===null)return null;let p=_n.normalize(_n.join(i===""?".":i,d.text));return p==="."?"":p.replace(/^\.\//,"")},"resolve"),u=s((d,p,f)=>{if(l.size>=o)return;let m=c(d);if(m===null||m===""||LP(m))return;let h=l.get(m);if(h&&(h.act==="write"||p==="edit"))return;let g={path:m,act:p};f&&f.literal&&(g.intoDirFrom=_n.basename(f.text)),l.set(m,g)},"add");for(let d of Ao(e)){let p=MP(d,n),f=!1,m=0,h=[];for(let b=0;b<p.length;b++){let k=p[b];if(k.kind==="open"){h.length===0&&(f=!0);continue}if(k.kind==="close"){m+=1;continue}if(k.kind==="word"){h.push(k.word);continue}let v=p[b+1],S=v?.kind==="word"?v.word:null;switch(S!==null&&(b+=1),k.op){case">":case">|":case"&>":S&&u(S,"write");break;case">>":case"&>>":S&&u(S,"edit");break;case">&":S&&!/^(\d+|-)$/.test(S.text)&&u(S,"write");break;default:break}}f&&a.push(i);let{found:g,cd:_}=Y9(h);for(let b of g)u(b.word,b.act,b.intoDirFrom);if(_!==void 0){if(_==="unknown")i=null;else if(_==="home")i=n?_n.normalize(n):null;else{let b=c(_);i=b===null?null:b}i!==null&&i!==""&&r.add(i)}for(let b=0;b<m&&a.length>0;b++)i=a.pop()}return{targets:[...l.values()],dirs:[...r]}}function FP(e){if(typeof e!="string"||e.trim().length===0)return!1;for(let t of Ao(e)){let n=MP(t,null);for(let l=0;l<n.length;l++){let c=n[l];if(c.kind!=="redir"||!c.op.includes(">")||c.op==="<>")continue;let u=n[l+1];if(u?.kind!=="word")return!0;if(!(c.op===">&"&&/^(\d+|-)$/.test(u.word.text))&&!(u.word.literal&&LP(u.word.text)))return!0}let r=n.flatMap(l=>l.kind==="word"?[l.word]:[]),o=$P(r);if(o<0)continue;let i=Yb(r[o]),a=r.slice(o+1);if(i==="git"){let l=a.find(c=>!c.text.startsWith("-"));if(!l||!Z9.has(l.text))return!0;continue}if(!X9.has(i)||i==="sed"&&a.some(l=>!l.quoted&&(/^-[A-Za-z]*i/.test(l.text)||l.text.startsWith("--in-place")))||i==="find"&&a.some(l=>["-delete","-exec","-execdir","-ok","-okdir","-fprint","-fprintf","-fls"].includes(l.text))||i==="awk"&&a.some(l=>/>/.test(l.text)||l.text.includes("system(")))return!0}return!1}var V9,DP,q9,z9,X9,Z9,HP=w(()=>{"use strict";Dt();V9=new Set(["*","?","["]);s(MP,"lexSegment");DP=/^[A-Za-z_][A-Za-z0-9_]*=/,q9=new Set(["sudo","time","nohup","command","exec","builtin","nice"]),z9=new Set(["do","then","else","elif","if","while","until","!","{"]);s(Yb,"bare");s($P,"programIndex");s(Al,"operands");s(PP,"copyLike");s(J9,"sedTargets");s(Y9,"commandTargets");s(LP,"isPseudoPath");s(jP,"shellAnalysis");X9=new Set(["ls","cat","head","tail","less","more","grep","egrep","fgrep","rg","ag","wc","echo","printf","pwd","which","whereis","type","stat","file","du","df","basename","dirname","realpath","readlink","sort","uniq","cut","tr","column","nl","diff","cmp","comm","jq","yq","date","env","printenv","id","whoami","uname","ps","pgrep","lsof","test","true","false","sleep","tree","fd","cd","pushd","popd","export","set","source",".","sed","awk","find"]),Z9=new Set(["log","show","status","diff","grep","cat-file","rev-parse","ls-files","blame","merge-base","describe","reflog","ls-remote","for-each-ref","symbolic-ref","check-ignore","rev-list","shortlog","fetch"]);s(FP,"shellMayWrite")});var tk={};Q(tk,{SHELL_CALLS_DIR:()=>Zb,SHELL_CHANGES_SUBCOMMAND:()=>u5,SHELL_WRITE_SUBCOMMAND:()=>c5,bashCommandOf:()=>Qb,changedSince:()=>YP,parsePorcelainZ:()=>JP,pruneStamps:()=>zP,shellChangesCore:()=>g5,shellWriteCore:()=>m5,stampKey:()=>ek,takeStamp:()=>qP,writeStamp:()=>VP});import{execFileSync as Q9}from"node:child_process";import{createHash as e5}from"node:crypto";import{existsSync as BP,lstatSync as t5,mkdirSync as n5,readFileSync as r5,readdirSync as o5,renameSync as i5,statSync as Xb,unlinkSync as GP,writeFileSync as s5}from"node:fs";import{homedir as a5}from"node:os";import{isAbsolute as UP,join as Rr,relative as l5}from"node:path";function Qb(e){if(e.tool_name!=="Bash")return null;let t=e.tool_input?.command;return typeof t=="string"&&t.trim().length>0?t:null}function ys(e,t,n,r){return{...e,tool_name:t,tool_input:{file_path:n},...r!==void 0?{cwd:r}:{}}}function WP(){try{return new Set(re()?.declined_hooks??[])}catch{return new Set}}function ek(e,t){let n=typeof e.tool_use_id=="string"&&e.tool_use_id.length>0?`tool:${e.tool_use_id}`:`cmd:${typeof e.session_id=="string"?e.session_id:""}\0${t}`;return e5("sha256").update(n).digest("hex").slice(0,32)}function VP(e,t,n){n5(e,{recursive:!0,mode:448});let r=Rr(e,`${t}.json`),o=`${r}.${process.pid}.tmp`;s5(o,JSON.stringify(n),{mode:384}),i5(o,r)}function qP(e,t,n){let r=Rr(e,`${t}.json`);try{let o=JSON.parse(r5(r,"utf8"));try{GP(r)}catch{}return o.v!==1||typeof o.at!="number"||n-o.at>KP?null:{v:1,at:o.at,dirs:Array.isArray(o.dirs)?o.dirs.filter(i=>typeof i=="string"):[],reported:Array.isArray(o.reported)?o.reported.filter(i=>typeof i=="string"):[]}}catch{return null}}function zP(e,t){try{for(let n of o5(e)){let r=Rr(e,n);try{t-Xb(r).mtimeMs>KP&&GP(r)}catch{}}}catch{}}function f5(e,t,n){let{targets:r,dirs:o}=jP(e,{home:n});return{targets:r.map(a=>{let l=UP(a.path)?a.path:Rr(t,a.path);if(a.intoDirFrom!==void 0)try{Xb(l).isDirectory()&&(l=Rr(l,a.intoDirFrom))}catch{}return{abs:l,act:a.act}}),dirs:o.map(a=>UP(a)?a:Rr(t,a))}}async function m5(e,t,n={}){let r=Qb(e);if(r===null)return null;let o=n.nowMs??Date.now(),i=be(e,t),{targets:a,dirs:l}=f5(r,i,n.home??a5()),c=n.stampDir??Zb;try{FP(r)&&(VP(c,ek(e,r),{v:1,at:o,dirs:[i,...l],reported:a.map(p=>p.abs)}),Math.random()<.05&&zP(c,o))}catch{}if(a.length===0)return null;let u=n.declined??WP(),d=[];if(!u.has("on-file-write"))for(let p of a){if(p.act!=="write"||BP(p.abs))continue;let f=await Hb(ys(e,"Write",p.abs,jo(p.abs)),t);if(f!==null)return f}if(!u.has("on-file-edit"))for(let p of a){let f=await hp(ys(e,p.act==="write"?"Write":"Edit",p.abs),t);if(f!==null){d.push(f);break}}if(!u.has("on-repo-health"))for(let p of a){let f=await dp(ys(e,"Edit",p.abs),t);f!==null&&d.push(f)}return Sp(d)}function JP(e){let t=e.split("\0"),n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.length<4)continue;let i=o.slice(0,2),a=o.slice(3);(i[0]==="R"||i[0]==="C")&&(r+=1),!i.includes("D")&&n.push({path:a,untracked:i==="??"})}return n}function h5(e){try{return Q9("git",["status","--porcelain=v1","-z","--untracked-files=all"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:8*1024*1024})}catch{return null}}function YP(e,t,n=p5){let r=new Set;for(let a of e.dirs)try{let l=mn(a),c=BP(l)&&Xb(l).isDirectory()?l:jo(l);r.add(gt(c))}catch{}let o=new Set(e.reported.map(a=>{try{return mn(a)}catch{return a}})),i=[];for(let a of r){let l=t(a);if(l!==null)for(let c of JP(l)){let u=Rr(a,c.path);if(!o.has(u)){try{let d=t5(u);if(!d.isFile()||d.mtimeMs<e.at-d5)continue}catch{continue}if(i.push({abs:u,root:a,rel:c.path,untracked:c.untracked}),i.length>=n)return i}}}return i}async function g5(e,t,n={}){let r=Qb(e);if(r===null||!me(t,{kind:"context",event:"PostToolUse"}))return null;let o=qP(n.stampDir??Zb,ek(e,r),n.nowMs??Date.now());if(o===null)return null;let i=YP(o,n.status??h5);if(i.length===0)return null;let a=n.declined??WP(),l=[];if(!a.has("on-file-write")){for(let d of i)if(d.untracked)try{let p=await Tn(d.root,d.rel);if(p.namespace===null)continue;if(!p.taken&&p.outOfOrder!==null){let m=p.outOfOrder;l.push(`'${d.rel}' is older than the newest migration on ${m.sighting.where} (${m.newest}) \u2014 the cloud push after the merge refuses it without --include-all. Rename it to ${p.suggestion} or a fresh timestamp.`);continue}if(!p.taken)continue;let f=p.sightings.map(m=>`${m.path} (${m.where})`).join(", ");l.push(`'${d.rel}' claims ${p.namespace.prefix}${p.number}, which is already taken: ${f}. Next free: ${p.namespace.prefix}${p.suggestion}. Rename it before anything refers to that number.`)}catch{}}let c=s(d=>d!==null&&(d.kind==="context"||d.kind==="text")?d.text:null,"textOf");if(!a.has("on-file-edit"))for(let d of i){let p=c(await hp(ys(e,"Edit",d.abs),t));if(p!==null){l.push(p);break}}if(!a.has("on-repo-health"))for(let d of i){let p=c(await dp(ys(e,"Edit",d.abs),t));p!==null&&l.push(p)}if(!a.has("on-write-health"))for(let d of i){let p=c(await Mb(ys(e,"Edit",d.abs),t));p!==null&&l.push(p)}return l.length===0?null:{kind:"context",event:"PostToolUse",text:`[maind] This Bash call changed files its command line did not name (seen via git status: ${i.map(d=>l5(d.root,d.abs)||d.abs).slice(0,5).join(", ")}${i.length>5?", \u2026":""}):
1047
1047
 
1048
1048
  `+l.join(`
1049
1049
 
1050
- `)}}var a5,l5,Zb,KP,c5,u5,nk=w(()=>{"use strict";Me();Ce();Wt();Je();Oe();Ie();Lt();il();_l();HP();pp();a5="on-shell-write",l5="on-shell-changes",Zb=Rr(he,"shell-calls"),KP=60*6e4,c5=1500,u5=12;s(Qb,"bashCommandOf");s(ys,"asFileCall");s(WP,"declinedHooks");s(ek,"stampKey");s(VP,"writeStamp");s(qP,"takeStamp");s(zP,"pruneStamps");s(d5,"resolveTargets");s(p5,"shellWriteCore");s(JP,"parsePorcelainZ");s(f5,"gitStatusZ");s(YP,"changedSince");s(m5,"shellChangesCore")});import{existsSync as XP}from"node:fs";import{appendFile as h5,mkdir as g5,readFile as y5}from"node:fs/promises";import{join as _5}from"node:path";function rk(e,t=xp){return _5(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function _s(e,t=xp){return XP(rk(e,t))}async function Cr(e,t,n=xp){try{await g5(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await h5(rk(e,n),r+`
1051
- `,{mode:384})}catch{}}async function Ho(e,t=xp){try{let n=rk(e,t);if(!XP(n))return[];let r=[];for(let o of(await y5(n,"utf8")).split(`
1052
- `))if(o.trim())try{let i=JSON.parse(o),a=i.t,l=i.k,c=i.v;if(typeof a!="number"||!Number.isFinite(a)||typeof l!="string"||!b5.has(l))continue;r.push(typeof c=="string"?{t:a,k:l,v:c}:{t:a,k:l})}catch{}return r}catch{return[]}}var xp,b5,Rl=w(()=>{"use strict";Je();xp=I_,b5=new Set(["fail","ok","nudge","skip","prompt"]);s(rk,"triggerLogPath");s(_s,"hasTriggerLog");s(Cr,"appendTriggerEvent");s(Ho,"loadTriggerEvents")});var sk={};Q(sk,{bashOutputOf:()=>ik,consultedAtOf:()=>Ir,difficultyCore:()=>v5,exitCodeInText:()=>ok,foreignShellResult:()=>ZP,outcomeFromHook:()=>QP,sensorSessionId:()=>Ep});function ik(e){if(e===null||typeof e!="object")return{output:null,interrupted:!1};let t=e,n=[t.stdout,t.stderr].filter(r=>typeof r=="string"&&r.length>0);return{output:n.length>0?n.join(`
1050
+ `)}}var c5,u5,Zb,KP,d5,p5,nk=w(()=>{"use strict";Me();Ce();Wt();Je();Oe();Ie();Lt();il();_l();HP();pp();c5="on-shell-write",u5="on-shell-changes",Zb=Rr(he,"shell-calls"),KP=60*6e4,d5=1500,p5=12;s(Qb,"bashCommandOf");s(ys,"asFileCall");s(WP,"declinedHooks");s(ek,"stampKey");s(VP,"writeStamp");s(qP,"takeStamp");s(zP,"pruneStamps");s(f5,"resolveTargets");s(m5,"shellWriteCore");s(JP,"parsePorcelainZ");s(h5,"gitStatusZ");s(YP,"changedSince");s(g5,"shellChangesCore")});import{existsSync as XP}from"node:fs";import{appendFile as y5,mkdir as _5,readFile as b5}from"node:fs/promises";import{join as k5}from"node:path";function rk(e,t=xp){return k5(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function _s(e,t=xp){return XP(rk(e,t))}async function Cr(e,t,n=xp){try{await _5(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await y5(rk(e,n),r+`
1051
+ `,{mode:384})}catch{}}async function Ho(e,t=xp){try{let n=rk(e,t);if(!XP(n))return[];let r=[];for(let o of(await b5(n,"utf8")).split(`
1052
+ `))if(o.trim())try{let i=JSON.parse(o),a=i.t,l=i.k,c=i.v;if(typeof a!="number"||!Number.isFinite(a)||typeof l!="string"||!w5.has(l))continue;r.push(typeof c=="string"?{t:a,k:l,v:c}:{t:a,k:l})}catch{}return r}catch{return[]}}var xp,w5,Rl=w(()=>{"use strict";Je();xp=I_,w5=new Set(["fail","ok","nudge","skip","prompt"]);s(rk,"triggerLogPath");s(_s,"hasTriggerLog");s(Cr,"appendTriggerEvent");s(Ho,"loadTriggerEvents")});var sk={};Q(sk,{bashOutputOf:()=>ik,consultedAtOf:()=>Ir,difficultyCore:()=>x5,exitCodeInText:()=>ok,foreignShellResult:()=>ZP,outcomeFromHook:()=>QP,sensorSessionId:()=>Ep});function ik(e){if(e===null||typeof e!="object")return{output:null,interrupted:!1};let t=e,n=[t.stdout,t.stderr].filter(r=>typeof r=="string"&&r.length>0);return{output:n.length>0?n.join(`
1053
1053
  `):null,interrupted:t.interrupted===!0}}function bs(e){if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let t=e.map(n=>typeof n=="string"?n:bs(n?.text)).filter(n=>n!==null);return t.length>0?t.join(`
1054
- `):null}return null}function ok(e,t){if(e===null)return null;let n=t.exec(e.length>8192?e.slice(-8192):e);return n?Number(n[1]):null}function ZP(e,t){switch(e){case"cursor":{let n=t.tool_output,r=null;try{r=typeof n=="string"?JSON.parse(n):null}catch{r=null}let o=typeof r?.exitCode=="number"?r.exitCode:null;return{failed:o!==null&&o!==0,output:r?ik(r).output:null}}case"codex":return{failed:!1,output:bs(t.tool_response)};case"copilot":{let n=t.tool_result;if(n!==null&&typeof n=="object"){let i=n,a=i.result_type;return{failed:a==="failure"||a==="error",output:bs(i.text_result_for_llm)}}let r=bs(t.tool_response),o=ok(r,/Command exited with code (\d+)/);return{failed:o!==null&&o!==0,output:r}}case"gemini":{let n=t.tool_response,r=n!==null&&typeof n=="object"?n:{},o=bs(r.llmContent),i=ok(o,/Exit Code: (\d+)/);return{failed:i!==null&&i!==0||r.error!==void 0&&r.error!==null,output:o}}case"devin":{let n=t.tool_response,r=n!==null&&typeof n=="object"?n:{};return{failed:r.success===!1,output:bs(r.output)}}default:return{failed:!1,output:null}}}function QP(e,t="claude-code"){let n=e.hook_event_name,r=typeof e.tool_name=="string"?e.tool_name:"",o=e.agent_id,i=typeof o=="string"&&o.length>0;if(t==="claude-code"||t==="unknown"){if(n!=="PostToolUse"&&n!=="PostToolUseFailure")return null;let u=n==="PostToolUseFailure",d=!u&&r==="Bash"?ik(e.tool_response):{output:null,interrupted:!1};return{event:n,outcome:{tool:r,input:e.tool_input,failed:u,output:d.output,isInterrupt:e.is_interrupt===!0||d.interrupted,isSubagent:i}}}if(!(n==="PostToolUse"||n==="postToolUse"||n==="AfterTool"))return null;let l=(k5[t]??[]).includes(r);if(!l&&!r.startsWith("mcp__"))return null;let c=l?ZP(t,e):{failed:!1,output:null};return{event:"PostToolUse",outcome:{tool:l?"Bash":r,input:e.tool_input,failed:c.failed,output:c.output,isInterrupt:e.is_interrupt===!0,isSubagent:i}}}function Ir(e,t){let n=e.guard_signals?.[t]?.consulted_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}async function w5(e,t,n){if(!_s(e))return;let r=await Ho(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let o=Bi(r,null,n);await Cr(e,{t:n,k:"ok",v:t});let i=o.chain;i!==null&&i.failures.length>=4&&!o.resolved&&i.lastVerb===t&&await oe({event:"difficulty_resolved",session_id:e,detail:String(i.failures.length)})}function Ep(e){for(let t of[e.session_id,e.conversation_id])if(typeof t=="string"&&t.trim().length>0)return t.trim();return null}async function v5(e,t){let n=Se();if(n.mode==="off"||!n.difficulty&&!n.capture)return null;let r=Ep(e);if(r===null)return null;let o=QP(e,t.host);if(o===null)return null;let i=t_(o.outcome);if(i===null)return null;let a=Date.now();if(i.kind==="ok")return await w5(r,i.verb,a),null;await Cr(r,{t:a,k:"fail",v:i.verb});let l=await Ho(r),c=Bi(l,Ir(await ue(),r),a);if(!o_(c)||c.chain===null)return null;let u=await Ar(!0);return!n.difficulty||!mr(u.difficulty)?null:(await Cr(r,{t:a,k:"nudge"}),await oe({event:"difficulty_nudge",session_id:r,cwd:be(e,t),project_key:Z()??void 0,detail:String(c.chain.failures.length)}),{kind:"context",event:o.event,text:Va(c.chain)})}var k5,ks=w(()=>{"use strict";Dt();Ie();ut();de();Zt();pn();Rl();Fo();s(ik,"bashOutputOf");k5={cursor:["Shell","Bash"],codex:["Bash"],copilot:["run_in_terminal","bash","Bash"],gemini:["run_shell_command"],devin:["exec","Bash"]};s(bs,"textOf");s(ok,"exitCodeInText");s(ZP,"foreignShellResult");s(QP,"outcomeFromHook");s(Ir,"consultedAtOf");s(w5,"recordSuccess");s(Ep,"sensorSessionId");s(v5,"difficultyCore")});var oM={};Q(oM,{PLAN_ACCEPTED_SUBCOMMAND:()=>T5,acceptedPlanOf:()=>nM,planAcceptedCore:()=>P5,planAcceptedText:()=>rM});import{existsSync as S5,readFileSync as x5}from"node:fs";import{homedir as E5}from"node:os";import{join as eM}from"node:path";function ak(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Hn(e){return typeof e=="string"&&e.trim().length>0?e:null}function tM(e){try{return x5(e,"utf8").length}catch{return 0}}function R5(e){let t=A5.exec(e.trim())?.[1]?.trim()??null;return t===null?null:{path:t,length:tM(t)}}function I5(e,t){if(!C5.test(t.trim()))return null;let n=Hn(e.session_id)?.trim(),r=process.env.COPILOT_HOME?.trim()||eM(E5(),".copilot"),o=n?eM(r,"session-state",n,"plan.md"):null;return o!==null&&S5(o)?{path:o,length:tM(o)}:{path:null,length:0}}function nM(e){if(typeof e.tool_name!="string"||!O5.has(e.tool_name)||Hn(e.agent_id)!==null)return null;let t=Hn(ak(e.tool_result)?.text_result_for_llm);if(t!==null)return I5(e,t);let n=ak(e.tool_response),r=Hn(n?.returnDisplay);if(r!==null)return R5(r);if(n?.isAgent===!0)return null;let o=ak(e.tool_input),i=Hn(n?.plan)??Hn(o?.plan),a=Hn(n?.filePath)??Hn(o?.planFilePath);return i===null&&a===null?null:{path:a,length:i?.length??0}}function N5(e){let t=e.key??"the object";return e.title?`${t} \u201C${e.title}\u201D`:t}function lk(e,t){return`maind object plan --object ${e} --file ${t??"<the plan file>"}`}function rM(e){let{target:t,bound:n,path:r,length:o}=e,i=["[maind] The plan was accepted \u2014 it belongs on its MAIND work object, before you build."];if(t.objectId!==null)i.push(`This session is bound to ${N5({key:t.key,title:t.title})}. If the plan belongs to it, attach it now: work_object_attach_plan (object_id "${t.objectId}", plan: the accepted text), or in a shell \`${lk(t.objectId,r)}\`. If it belongs to another object, attach it there once that object exists \u2014 work_object_create takes the plan directly.`);else if(n.length>1)i.push(`This session is bound to ${n.map(a=>a.key??a.id).join(", ")}. Attach the plan to the one it belongs to: work_object_attach_plan (that object's id, plan: the accepted text), or in a shell \`${lk("<uuid>",r)}\`. For new work, work_object_create takes the plan directly.`);else{let a=t.reason==="not_announced"?"maind does not know this session's work object yet.":"This session is bound to no work object.";i.push(`${a} Attach the plan where it belongs: work_object_create takes it as \`plan\` for new work, work_object_attach_plan adds it to an existing object (in a shell \`${lk("<uuid>",r)}\`).`)}return o>mc&&i.push(`The plan has ${o} characters; the server takes at most ${mc}. Shorten it for the attachment and say that you did.`),i.push("If it is already attached, nothing to do."),i.join(" ")}function D5(e,t,n){let r=Hn(e.session_id)?.trim()??null,o=fn(Pt(e)||null,r??""),i=kt(nt(t),{hostPids:Fe(),cwd:n,selfId:o})?.snap;return!i||i.announce_error?null:{boundObjects:i.bound_objects??null,branchObjectId:i.branch_object_id??null}}async function P5(e,t,n={}){let r=nM(e);if(r===null||!me(t,{kind:"context",event:"PostToolUse"}))return null;let o=(n.projectKey??Z)();if(o===null)return null;let i=(n.ownSnapshot??D5)(e,o,be(e,t));if(i===null)return null;let a=yr(i);return{kind:"context",event:"PostToolUse",text:rM({target:a,bound:i.boundObjects??[],path:r.path,length:r.length})}}var T5,A5,C5,O5,iM=w(()=>{"use strict";Et();_r();Mn();de();Ji();Oo();tt();Ie();Lt();T5="on-plan-accepted";s(ak,"record");s(Hn,"text");s(tM,"fileLength");A5=/^Plan approved: (.+)$/;s(R5,"geminiAcceptedPlan");C5=/^Plan approved[!,]/;s(I5,"copilotAcceptedPlan");O5=new Set(["ExitPlanMode","exit_plan_mode"]);s(nM,"acceptedPlanOf");s(N5,"named");s(lk,"shellLine");s(rM,"planAcceptedText");s(D5,"defaultOwnSnapshot");s(P5,"planAcceptedCore")});function sM(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var ck=w(()=>{"use strict";s(sM,"resolveConnection")});function aM(e=$5()){return e?.codex_session_analytics===!0}function lM(e,t){let n=e.own_snapshot_age_ms;return(e.own_snapshot_via==="session"||e.own_snapshot_via==="ppid"||e.own_snapshot_names_session===!0)&&n!==null&&n<=18e5||t?"connected":"unknown"}function $5(){try{return re()}catch{return null}}var uk=w(()=>{"use strict";Ce();ck();s(aM,"codexSessionAnalyticsAllowed");s(lM,"resolveCodexConnection");s($5,"safeReadConfig")});import{execFile as pk}from"node:child_process";import{randomUUID as L5}from"node:crypto";function G5(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return dk.test(t)?t:L5()}function fk(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function K5(e,t){let n=(e.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:t?.auto_working_paths===!0}async function W5(e,t){return await new Promise(n=>{pk("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8",...t?{cwd:t}:{}},(r,o)=>{if(r)return n(null);n(V5(o))})})}function V5(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function q5(e){return await new Promise(t=>{pk("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8",...e?{cwd:e}:{}},(n,r)=>{if(n)return t(null);let o=r.trim();t(o.length>0&&o!=="HEAD"?o:null)})})}function z5(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function J5(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),o=dk.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:o,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(i=>{dk.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}function X5(e){let t=new Set,n=s(o=>Array.isArray(o)?o:[],"rows"),r=e.work_repo!==null&&typeof e.work_repo=="object"?e.work_repo.peers:void 0;for(let o of[...n(e.peers),...n(r)]){if(o===null||typeof o!="object")continue;let i=o;if(i.is_self!==!0)for(let a of n(i.bound_objects)){let l=a!==null&&typeof a=="object"?a.id:null;typeof l=="string"&&t.add(l.toLowerCase())}}return t}function Z5(){let e=null;return()=>(e??=new Promise(t=>{pk("git",["rev-parse","--show-toplevel"],{timeout:2e3,encoding:"utf8"},(n,r)=>{let o=n?"":r.trim();t(o.length>0?o:null)})}),e)}var cM,uM,j5,F5,H5,U5,B5,dk,Tp,Y5,mk=w(()=>{"use strict";_r();Ce();cM=45e3,uM=3e4,j5=5,F5=120,H5=3e4,U5=15*6e4,B5=1500,dk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(G5,"resolveClientSessionId");s(fk,"autoAnnounceDisabled");s(K5,"autoWorkingPathsEnabled");Tp=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;workRepo;lastSentWorkKey=null;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;nestedProjectKeys;onAnnounced;lastBranch=null;lastBranchObjectId=null;lastBoundObjects=null;peerBoundIds=new Set;editRoots;homeRoot;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??re)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??q5,this.gitBranchObject=t.gitBranchObject??W5,this.workRepo=t.workRepo??null,this.editRoots=t.editRoots??(()=>new Set),this.homeRoot=t.homeRoot??Z5(),this.log=t.log??(o=>process.stderr.write(o+`
1055
- `)),this.machineLabel=z5(r?.machine_label),this.enabled=this.projectKey!==null&&!fk(n,r),this.workingPathsEnabled=K5(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??J5(n,G5(n)),this.sessionMeta=t.sessionMeta??null,this.nestedProjectKeys=t.nestedProjectKeys??null,this.onAnnounced=t.onAnnounced??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}boundObjects(){return this.lastBoundObjects}branchObjectId(){return this.lastBranchObjectId}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<cM||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<cM||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<j5||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,B5).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(H5*2**(this.consecutiveFailures-1),U5);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let a=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${a} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r=null;if(t==="active"&&this.workRepo!==null)try{r=await this.workRepo()}catch{r=null}let o={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:F5,announce_source:"bridge"};if(t==="active"){o.identity_source=n.source,n.aliases.length>0&&(o.also_known_as=n.aliases),r!==null&&(r.projectKey!==this.projectKey||this.lastSentWorkKey!==null&&this.lastSentWorkKey!==this.projectKey)&&(o.work_project_key=r.projectKey,this.lastSentWorkKey=r.projectKey);let a=await this.gitBranch(r?.root??null);a&&(o.branch=a),this.lastBranch=a;let l=null;if(a)try{let c=r===null?null:await this.homeRoot(),d=r===null||r.root===c||this.editRoots().has(r.root)?await this.gitBranchObject(a,r?.root??null):null;l=d;let p=this.lastBoundObjects?.map(m=>m.id)??[],f=d?.toLowerCase()??null;d!==null&&d!==this.lastSentObjectId&&!this.peerBoundIds.has(f)&&!p.includes(f)&&(o.object_ids=[...p,d].slice(-Y5),this.lastSentObjectId=d)}catch{}if(this.lastBranchObjectId=l,this.machineLabel&&(o.machine_label=this.machineLabel),this.nestedProjectKeys!==null)try{let c=this.nestedProjectKeys();c.length>0&&(o.nested_project_keys=[...c])}catch{}if(this.sessionMeta!==null)try{let c=await this.sessionMeta();c?.model&&(o.model=c.model),c?.title&&(o.title=c.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let c=await this.deriveWorkingPaths();c&&c.length>0&&(o.working_paths=c)}catch{}}let i=await this.postToolCall("announce_session",o);if(t==="active"&&i!==null&&typeof i=="object"){let a=i;if(a.ok===!0&&typeof a.session_id=="string")try{this.identity.adopt(a.session_id)}catch{}if(a.ok===!0&&a.ended!==!0){try{this.lastBoundObjects=Qa(a.bound_objects)}catch{this.lastBoundObjects=[]}this.peerBoundIds=X5(a)}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let a=this.identity.current(),l={sessionId:a.id,branch:this.lastBranch,branchObjectId:this.lastBranchObjectId,identitySource:a.source,aliases:a.aliases},c=typeof i=="object"?i:null;if(c!==null&&c.ok===!0)this.snapshot.write(i,l),r!==null&&r.projectKey!==this.projectKey&&c.work_repo!==void 0&&c.work_repo!==null?this.snapshot.writeWork?.(c.work_repo,l):this.snapshot.clearWork?.();else if(this.snapshot.markFailed){let u=c!==null&&typeof c.error=="string"?c.error:"announce_failed";this.snapshot.markFailed(u,l)}}}catch{}if(t==="active"&&this.onAnnounced!==null)try{this.onAnnounced()}catch{}}};s(W5,"defaultGitBranchObject");s(V5,"normalizeObjectId");s(q5,"defaultGitBranch");s(z5,"normalizeMachineLabel");s(J5,"staticIdentity");Y5=8;s(X5,"peerBoundIdsOf");s(Z5,"onceHomeRoot")});function pM(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!dM.test(n))return null;let r=n.toLowerCase();return t!==null&&dM.test(t)&&r!==t.toLowerCase()?null:r}var dM,fM=w(()=>{"use strict";dM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(pM,"snapshotSessionId")});import{appendFileSync as Q5,existsSync as Ap,mkdirSync as mM,readFileSync as e8,readdirSync as t8,renameSync as hk,rmdirSync as hM,statSync as gk,unlinkSync as gM,writeFileSync as n8}from"node:fs";import{join as ws}from"node:path";function yk(e){return e&&_M.test(e)?e:"no-session"}function Cl(e,t){return ws(e,`${t}.job.json`)}function _k(e,t){return ws(e,`${t}.running.json`)}function bM(e,t){return ws(e,`${t}.lock`)}function bk(e){Ap(e)||mM(e,{recursive:!0,mode:448})}function kM(e,t){bk(e);let n=yk(t.session_id),r=`${Cl(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;n8(r,JSON.stringify(t),{mode:384}),hk(r,Cl(e,n))}function s8(e){try{let t=JSON.parse(e);if(t&&t.v===1&&typeof t.transcript_path=="string"&&typeof t.cwd=="string")return{v:1,session_id:typeof t.session_id=="string"?t.session_id:null,transcript_path:t.transcript_path,cwd:t.cwd,coord_session_id:typeof t.coord_session_id=="string"?t.coord_session_id:null,project_key:typeof t.project_key=="string"?t.project_key:null,presence:{own_snapshot_age_ms:typeof t.presence?.own_snapshot_age_ms=="number"?t.presence.own_snapshot_age_ms:null,presence_usable:t.presence?.presence_usable===!0,...t.presence?.own_snapshot_via==="session"||t.presence?.own_snapshot_via==="ppid"||t.presence?.own_snapshot_via==="cwd"?{own_snapshot_via:t.presence.own_snapshot_via}:{},...t.presence?.own_snapshot_names_session===!0?{own_snapshot_names_session:!0}:{}},queued_at:typeof t.queued_at=="string"?t.queued_at:new Date(0).toISOString(),...t.client==="codex"?{client:"codex"}:{}}}catch{}return null}function wM(e,t){return Ap(Cl(e,t))}function vM(e,t){let n=Cl(e,t),r=_k(e,t);try{if(Ap(n)&&hk(n,r),!Ap(r))return null;let o=s8(e8(r,"utf8"));return o===null?(gM(r),null):o}catch{return null}}function SM(e,t){try{gM(_k(e,t))}catch{}}function kk(e,t,n=Date.now()){bk(e);let r=bM(e,t);try{if(n-gk(r).mtimeMs<r8)return!1;hM(r)}catch{}try{return mM(r,{recursive:!1}),!0}catch{return!1}}function wk(e,t){try{hM(bM(e,t))}catch{}}function xM(e){try{let t=new Set;for(let n of t8(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&_M.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function EM(e,t){for(let n of[Cl(e,t),_k(e,t)])try{return gk(n).mtimeMs}catch{}return null}function vs(e,t,n=o8){try{bk(e);let r=ws(e,i8);try{gk(r).size>n&&hk(r,ws(e,"runs.1.jsonl"))}catch{}Q5(r,JSON.stringify(t)+`
1056
- `,{mode:384})}catch{}}var Un,r8,yM,o8,i8,_M,vk=w(()=>{"use strict";ut();Un=ws(et,"session-end"),r8=10*6e4,yM=7*24*60*6e4,o8=256*1024,i8="runs.jsonl",_M=/^[A-Za-z0-9_-]{1,80}$/;s(yk,"jobKey");s(Cl,"jobPath");s(_k,"runningPath");s(bM,"lockPath");s(bk,"ensureDir");s(kM,"writeJob");s(s8,"parseJob");s(wM,"hasJob");s(vM,"takeJob");s(SM,"finishJob");s(kk,"acquireLock");s(wk,"releaseLock");s(xM,"pendingKeys");s(EM,"pendingSince");s(vs,"appendRunLog")});function Sk(e,t,n,r=Date.now()){let o=t===null?null:Fi(t),i=typeof n=="object"&&n!==null?n:{repoRoot:n},a=Dy(e,o,{repoRoot:i.repoRoot,...i.relativize?{relativize:i.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:o!==null}}var TM=w(()=>{"use strict";Eo();s(Sk,"buildCostPayload")});function AM(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();a8.test(r)&&!t.includes(r)&&t.push(r)}return t}async function RM(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:o}=await Ma(e.transcriptPath),i=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?td({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:IM(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,l=a?nd(r,a):null,c=l??e.projectKey,u=AM([e.coordSessionId,e.sessionId,...o]),d=performance.now(),[p,f,m]=await Promise.all([Ty(e.transcriptPath,{turns:r}),Uy(e.transcriptPath),e.fetchContext(c,u)]),h={collect_ms:i,parallel_ms:Math.round(performance.now()-d)};if(a&&e.rememberCheckouts)try{e.rememberCheckouts(a.seenLive())}catch{}if(e.sessionId&&(p.session_id=e.sessionId,f.session_id=e.sessionId),p.maind_connected=e.connection(p.maind_connected==="connected",t()),!p.session_id)return{posted:!1,contextOk:m!==null,sentSlices:!1,timings:h};let g=l&&a?rd(l,a):null,_=Sk(r,m,{repoRoot:e.repoRoot,relativize:g},t()),b=m===null?null:Fi(m)?.canonical_session_id??null,k=e.coordSessionId??b,v=Yu(p,f,{client_session_id:k,client:"claude-code",coordination_session_ids:u},"live_bridge",_);return await e.post(v,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:h}}async function CM(e){let t=e.now??Date.now,n=performance.now(),{turns:r}=await ja(e.transcriptPath),o=Math.round(performance.now()-n),i=e.resolveRoot&&e.projectKeyOf?td({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:IM(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,a=i?nd(r,i):null,l=a??e.projectKey,c=performance.now(),u=await Fy(e.transcriptPath,{turns:r});if(u===null)return{posted:!1,contextOk:!1,sentSlices:!1,timings:{collect_ms:o,parallel_ms:Math.round(performance.now()-c)}};let{coordination_ids:d,...p}=u,f=AM([e.coordSessionId,e.sessionId,p.session_id,...d]),m=await e.fetchContext(l,f),h={collect_ms:o,parallel_ms:Math.round(performance.now()-c)};if(i&&e.rememberCheckouts)try{e.rememberCheckouts(i.seenLive())}catch{}if(e.sessionId&&(p.session_id=e.sessionId),p.maind_connected=e.connection(p.maind_connected==="connected",t()),!p.session_id)return{posted:!1,contextOk:m!==null,sentSlices:!1,timings:h};let g=a&&i?rd(a,i):null,_=Sk(r,m,{repoRoot:e.repoRoot,relativize:g},t()),b=m===null?null:Fi(m)?.canonical_session_id??null,k=e.coordSessionId??b,v=Yu(p,null,{client_session_id:k,client:"codex",coordination_session_ids:f},"live_bridge",_);return await e.post(v,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:h}}function IM(e,t){try{return e()}catch{return t}}var a8,OM=w(()=>{"use strict";Eo();TM();a8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(AM,"sessionIdsFor");s(RM,"ingestSessionEnd");s(CM,"ingestCodexSessionEnd");s(IM,"safe")});var UM={};Q(UM,{FLUSH_LOCK_KEY:()=>Ak,INLINE_BUDGET:()=>Ck,SESSION_END_WORKER:()=>Rk,SWEEP_MAX_KEYS:()=>MM,SWEEP_MIN_AGE_MS:()=>PM,WORKER_BUDGET:()=>DM,WORKER_DEADLINE_MS:()=>Ek,drainSession:()=>Ik,fetchCostContext:()=>$M,flushUnderLock:()=>HM,gitResolvers:()=>jM,liveJobDeps:()=>Cp,postIngest:()=>LM,postIngestOnce:()=>Tk,processJob:()=>Rp,runSessionEndWorker:()=>u8,sweepPending:()=>FM});import{execFileSync as l8}from"node:child_process";import{existsSync as NM,statSync as c8}from"node:fs";async function $M(e,t,n,r,o){if(n===null)return null;let[i,...a]=r;try{return await Qt("get_session_cost_context",{project_key:n,...i?{session_id:i}:{},...a.length>0?{also_session_ids:a}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:K,timeoutMs:o})}catch{return null}}async function Tk(e,t,n,r,o,i=fetch){let a=new AbortController,l=setTimeout(()=>a.abort(),r);try{let c=await i(Td,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":K},body:JSON.stringify(n),signal:a.signal}),u=await c.json().catch(()=>null);if(!c.ok)return{outcome:"post_failed",status:c.status};let d=Ry(Ay(u),o);return{outcome:"posted",status:c.status,...d?{verdict:d}:{}}}catch(c){return{outcome:a.signal.aborted||c instanceof Error&&c.name==="AbortError"?"post_timeout":"post_error"}}finally{clearTimeout(l)}}async function LM(e,t,n,r,o,i={}){let a=i.sleep??(d=>new Promise(p=>setTimeout(p,d))),l=await Tk(e,t,n,o.postMs,r,i.fetchImpl),c=1;return(l.outcome==="post_timeout"||l.outcome==="post_error"||l.outcome==="post_failed"&&(l.status??0)>=500)&&o.postRetryDelayMs>0&&(await a(o.postRetryDelayMs),l=await Tk(e,t,n,o.postMs,r,i.fetchImpl),c=2),{...l,attempts:c}}function xk(e,t){try{let n=l8("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function jM(){let e=new Map,t=new Map;return{repoRootOf:s(n=>NM(n)?xk(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let o=xk(["-C",n,"rev-parse","--show-toplevel"]);return e.set(n,o),o},"gitRootOf"),projectKeyOfRoot:s(n=>{let r=t.get(n);if(r!==void 0)return r;let o=xk(["-C",n,"config","--get","remote.origin.url"]),i=o?nr(o):null;return t.set(n,i),i},"projectKeyOfRoot"),isDir:s(n=>{try{return c8(n).isDirectory()}catch{return!1}},"isDir")}}async function Rp(e,t){let n=t.now??Date.now,r=n(),o=Date.parse(e.queued_at),i={queued:Number.isFinite(o)?Math.max(0,r-o):0},a={ts:new Date(r).toISOString(),bridge:K,session_id:e.session_id,outcome:"no_transcript",ms:i,...e.client?{client:e.client}:{}};try{if(e.transcript_path)if(!NM(e.transcript_path))a.outcome="transcript_gone";else{let c=jM(),u=t.memoryPath??Hi,d=null,p=e.client==="codex",m=await(p?CM:RM)({apiKey:t.apiKey,deviceId:t.deviceId,sessionId:e.session_id,transcriptPath:e.transcript_path,projectKey:e.project_key,coordSessionId:e.coord_session_id,repoRoot:c.repoRootOf(e.cwd),resolveRoot:c.gitRootOf,projectKeyOf:c.projectKeyOfRoot,isDir:c.isDir,...t.memoryAllowed?{knownCheckouts:s(()=>$a(u),"knownCheckouts"),rememberCheckouts:s(g=>La(u,g),"rememberCheckouts")}:{},fetchContext:s(async(g,_)=>{let b=n();try{return await t.fetchContext(g,_)}finally{i.context=n()-b}},"fetchContext"),post:s(async(g,_)=>{let b=n();d=await t.post(g,_),i.post=n()-b},"post"),connection:s(g=>p?lM(e.presence,g):sM({ownSnapshotAgeMs:e.presence.own_snapshot_age_ms,sawMaindCall:g,presenceUsable:e.presence.presence_usable}),"connection"),now:n});a.context_ok=m.contextOk,a.sent_slices=m.sentSlices,m.timings&&(i.collect=m.timings.collect_ms,i.parallel=m.timings.parallel_ms);let h=d;!m.posted||h===null?a.outcome="not_posted":(a.outcome=h.outcome,a.attempts=h.attempts,h.status!==void 0&&(a.http_status=h.status),h.verdict&&(a.verdict=h.verdict))}}catch(c){a.outcome="error",a.error=(c instanceof Error?c.message:String(c)).slice(0,200)}let l=n();try{let c=await t.flush();a.flush=c===null?"unpaired":c.ok?`ok:${c.flushed}`:`failed:${c.error??"unknown"}`}catch(c){a.flush=`failed:${(c instanceof Error?c.message:String(c)).slice(0,80)}`}return i.flush=n()-l,i.total=n()-r,a}async function Ik(e,t,n,r={}){let o=r.now??Date.now,i=r.maxRounds??20,a=0;for(;a<i&&kk(e,t,o());){try{let l=vM(e,t);if(l===null)break;let c=Date.parse(l.queued_at),u=Number.isFinite(c)&&o()-c>yM?{ts:new Date(o()).toISOString(),bridge:K,session_id:l.session_id,outcome:"expired",ms:{queued:o()-c}}:await n(l);vs(e,u),SM(e,t),a++}finally{wk(e,t)}if(!wM(e,t))break}return a}async function FM(e,t,n,r={}){let o=r.now??Date.now,i=0;for(let a of xM(e)){if(i>=MM)break;if(a===t)continue;let l=EM(e,a);l===null||o()-l<PM||await Ik(e,a,n,{...r,maxRounds:1})>0&&i++}return i}async function HM(e,t,n=Date.now){if(!kk(e,Ak,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{wk(e,Ak)}}function Cp(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,o)=>$M(e,t,r,o,n.contextMs),"fetchContext"),post:s((r,o)=>LM(e,t,r,o,n),"post"),flush:s(()=>HM(Un,()=>yp(n.flushMs)),"flush"),memoryAllowed:sd()}}async function u8(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{vs(Un,{ts:new Date().toISOString(),bridge:K,session_id:t,outcome:"deadline",ms:{total:Ek}}),process.exit(0)},Ek);n.unref();try{let r=ee();if(!r)return 0;let o=ke(),i=s(a=>Rp(a,Cp(r,o,DM)),"run");await Ik(Un,t,i),await FM(Un,t,i)}catch(r){vs(Un,{ts:new Date().toISOString(),bridge:K,session_id:t,outcome:"error",ms:{},error:(r instanceof Error?r.message:String(r)).slice(0,200)})}finally{clearTimeout(n)}return 0}var Rk,DM,Ck,Ek,PM,MM,Ak,Ok=w(()=>{"use strict";Eo();we();Ln();K_();Lt();de();Xe();ad();ck();uk();OM();vk();Rk="session-end-run",DM={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},Ck={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},Ek=3*6e4,PM=2*6e4,MM=3;s($M,"fetchCostContext");s(Tk,"postIngestOnce");s(LM,"postIngest");s(xk,"git");s(jM,"gitResolvers");s(Rp,"processJob");s(Ik,"drainSession");s(FM,"sweepPending");Ak="metrics-flush";s(HM,"flushUnderLock");s(Cp,"liveJobDeps");s(u8,"runSessionEndWorker")});var Nk={};Q(Nk,{buildJob:()=>WM,enqueueAndSpawn:()=>VM,ingestSourceOf:()=>KM,presenceLookup:()=>BM,runOnSessionEnd:()=>y8,sessionEndCore:()=>_8,transcriptToIngest:()=>GM});import{spawn as d8}from"node:child_process";import{existsSync as p8,unlinkSync as f8}from"node:fs";import{join as m8}from"node:path";function BM(e,t,n,r){let o=null,i={own_snapshot_age_ms:null,presence_usable:!1};try{if(i.presence_usable=e!==null&&!fk(process.env,re()),e!==null){let a=kt(nt(e),{hostPids:r,cwd:process.cwd(),selfId:t});if(o=pM(a?.snap,t),a){let l=Date.parse(a.snap.written_at);i={...i,own_snapshot_age_ms:Number.isFinite(l)?Math.max(0,n-l):null,own_snapshot_via:a.via,...t!==null&&o!==null?{own_snapshot_names_session:!0}:{}}}}}catch{i={own_snapshot_age_ms:null,presence_usable:!1},o=null}if(o===null){let a=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(a)&&(o=a)}return{coordSessionId:o,evidence:i}}function GM(e,t=process.env,n=null){let r=Pt(e),o=n?.host??hr(e,t);return r&&!Ro(o)?r:""}function KM(e,t=process.env,n=null,r=aM){if((n?.host??hr(e,t))==="codex"){let i=Pt(e);return i&&S_(i)&&r()?{path:i,client:"codex"}:{path:""}}return{path:GM(e,t,n)}}function WM(e,t){let n=typeof e.session_id=="string"&&e.session_id?e.session_id:null,r={v:1,session_id:n,transcript_path:t.transcriptPath,cwd:t.cwd,coord_session_id:null,project_key:null,presence:{own_snapshot_age_ms:null,presence_usable:!1},queued_at:new Date(t.nowMs).toISOString(),...t.client&&t.transcriptPath?{client:t.client}:{}};if(!t.transcriptPath)return r;let o=t.projectKey(),i=t.presence(o,fn(t.transcriptPath,n),t.nowMs);return{...r,project_key:o,coord_session_id:i.coordSessionId,presence:i.evidence}}function VM(e,t={}){let n=t.dir??Un,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let o=yk(e.session_id);try{kM(n,e)}catch{return!1}try{return(t.spawnWorker??h8)(r,o,e.cwd),!0}catch{try{f8(m8(n,`${o}.job.json`))}catch{}return!1}}function h8(e,t,n){d8(process.execPath,[e,Rk,t],{detached:!0,stdio:"ignore",cwd:p8(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function g8(e,t){try{let n=await Rp(e,Cp(t,ke(),Ck));vs(Un,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
1057
- `)}}async function y8(){return ve(["on-session-end"])}async function _8(e,t){let n=[];try{n=Fe()}catch{n=[]}try{for(let a of n)_O(kr(),a)}catch{}let r=ee();if(!r)return null;let o=typeof e.session_id=="string"&&e.session_id?e.session_id:null;await gp(o);let i;try{let a=KM(e,process.env,t);i=WM(e,{...a.client?{client:a.client}:{},transcriptPath:a.path,cwd:process.cwd(),nowMs:Date.now(),projectKey:Z,presence:s((l,c,u)=>BM(l,c,u,n),"presence")})}catch{return null}return VM(i)||await g8(i,r),null}var Dk=w(()=>{"use strict";Ce();we();Oo();Oe();tt();Ie();uk();Lt();mk();Mn();de();Ji();fM();vk();Ok();s(BM,"presenceLookup");s(GM,"transcriptToIngest");s(KM,"ingestSourceOf");s(WM,"buildJob");s(VM,"enqueueAndSpawn");s(h8,"spawnDetachedWorker");s(g8,"runInline");s(y8,"runOnSessionEnd");s(_8,"sessionEndCore")});import{mkdirSync as qM,rmdirSync as zM,statSync as b8}from"node:fs";import{join as JM}from"node:path";import{setTimeout as k8}from"node:timers/promises";function YM(e){return JM(e,".maind","index-refresh.lock")}function Ip(e,t=Date.now()){let n=YM(e);try{if(t-b8(n).mtimeMs<w8)return!1;zM(n)}catch{}try{return qM(n,{recursive:!1}),!0}catch{return!1}}function Il(e){try{zM(YM(e))}catch{}}async function XM(e,t,n={}){let r=n.now??Date.now,o=n.sleep??(a=>k8(a).then(()=>{})),i=r()+(n.waitMs??3e4);try{qM(JM(e,".maind"),{recursive:!0})}catch{}for(;!Ip(e,r());){if(r()>=i)return{locked:!1};await o(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Il(e)}}var w8,Pk=w(()=>{"use strict";w8=30*6e4;s(YM,"lockPath");s(Ip,"acquireLock");s(Il,"releaseLock");s(XM,"withIndexLock")});var Op={};Q(Op,{INDEX_REFRESH_WORKER:()=>ZM,acquireLock:()=>Ip,indexRefreshCore:()=>A8,releaseLock:()=>Il,runIndexRefreshWorker:()=>R8,runOnIndexRefresh:()=>T8});import{spawn as v8}from"node:child_process";import{existsSync as S8}from"node:fs";import{join as x8}from"node:path";function E8(e){return x8(e,".maind","code-index.sqlite")}async function T8(){return ve(["on-index-refresh"])}async function A8(e,t){try{let n=pt(be(e,t));if(!S8(E8(n))||!Ip(n))return null;let r=process.argv[1];if(r===void 0)return Il(n),null;v8(process.execPath,[r,ZM,n],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return null}async function R8(){let e=process.argv[3]??pt();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Xd(),fb)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Il(e)}return 0}var ZM,Np=w(()=>{"use strict";Oe();Ie();xr();Pk();ZM="index-refresh-run";s(E8,"indexDbPath");s(T8,"runOnIndexRefresh");s(A8,"indexRefreshCore");s(R8,"runIndexRefreshWorker")});var p$={};Q(p$,{decideDocDutyReminder:()=>t$,decideLocally:()=>Lk,docDutyCore:()=>L8,lessonFindingOf:()=>s$,lessonStateDir:()=>Pp,lessonThenDoc:()=>l$,localDocFacts:()=>r$,ownBoundObject:()=>$p,readServerDocState:()=>u$,readServerLessonCheck:()=>c$,reminderStateDir:()=>jk,saidByCli:()=>d$,stampLessonAsked:()=>Mp,workTreeFor:()=>o$,writeLessonTeam:()=>a$});import{execFileSync as C8}from"node:child_process";import{existsSync as QM,mkdirSync as Mk,readdirSync as I8,readFileSync as Dp,writeFileSync as $k}from"node:fs";import{homedir as e$}from"node:os";import{join as Ft,resolve as O8}from"node:path";function Lk(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.ownTree?e.hasWork?e.locallySatisfied?{remind:!1,why:"locally_satisfied"}:null:{remind:!1,why:"no_work"}:{remind:!1,why:"no_own_tree"}:{remind:!1,why:"no_object"}}function t$(e){let t=Lk(e);if(t)return t;let n=e.object.key;if(e.server?.finished)return{remind:!1,why:"finished"};if(e.server?.inReview)return{remind:!1,why:"in_review"};if(e.server?.docDuty==="off")return{remind:!1,why:"duty_off"};if(e.server?.heldByOther)return{remind:!1,why:"held_by_other"};if(e.server&&!e.server.docMissing)return{remind:!1,why:"documented_elsewhere"};let r=e.server?.docDuty==="require";return{remind:!0,reason:lm(n,r)+` This reminder comes once per session for ${n}.`}}function jt(e,t){try{return C8("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:8*1024*1024})}catch{return null}}function n$(e){let t=jt(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=jt(e,["merge-base",r,"HEAD"])?.trim();if(o)return o}return null}function r$(e,t){let n=n$(e),r=n?(jt(e,["-c","core.quotepath=off","diff","--name-only",`${n}`,"HEAD"])??"").split(`
1054
+ `):null}return null}function ok(e,t){if(e===null)return null;let n=t.exec(e.length>8192?e.slice(-8192):e);return n?Number(n[1]):null}function ZP(e,t){switch(e){case"cursor":{let n=t.tool_output,r=null;try{r=typeof n=="string"?JSON.parse(n):null}catch{r=null}let o=typeof r?.exitCode=="number"?r.exitCode:null;return{failed:o!==null&&o!==0,output:r?ik(r).output:null}}case"codex":return{failed:!1,output:bs(t.tool_response)};case"copilot":{let n=t.tool_result;if(n!==null&&typeof n=="object"){let i=n,a=i.result_type;return{failed:a==="failure"||a==="error",output:bs(i.text_result_for_llm)}}let r=bs(t.tool_response),o=ok(r,/Command exited with code (\d+)/);return{failed:o!==null&&o!==0,output:r}}case"gemini":{let n=t.tool_response,r=n!==null&&typeof n=="object"?n:{},o=bs(r.llmContent),i=ok(o,/Exit Code: (\d+)/);return{failed:i!==null&&i!==0||r.error!==void 0&&r.error!==null,output:o}}case"devin":{let n=t.tool_response,r=n!==null&&typeof n=="object"?n:{};return{failed:r.success===!1,output:bs(r.output)}}default:return{failed:!1,output:null}}}function QP(e,t="claude-code"){let n=e.hook_event_name,r=typeof e.tool_name=="string"?e.tool_name:"",o=e.agent_id,i=typeof o=="string"&&o.length>0;if(t==="claude-code"||t==="unknown"){if(n!=="PostToolUse"&&n!=="PostToolUseFailure")return null;let u=n==="PostToolUseFailure",d=!u&&r==="Bash"?ik(e.tool_response):{output:null,interrupted:!1};return{event:n,outcome:{tool:r,input:e.tool_input,failed:u,output:d.output,isInterrupt:e.is_interrupt===!0||d.interrupted,isSubagent:i}}}if(!(n==="PostToolUse"||n==="postToolUse"||n==="AfterTool"))return null;let l=(v5[t]??[]).includes(r);if(!l&&!r.startsWith("mcp__"))return null;let c=l?ZP(t,e):{failed:!1,output:null};return{event:"PostToolUse",outcome:{tool:l?"Bash":r,input:e.tool_input,failed:c.failed,output:c.output,isInterrupt:e.is_interrupt===!0,isSubagent:i}}}function Ir(e,t){let n=e.guard_signals?.[t]?.consulted_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}async function S5(e,t,n){if(!_s(e))return;let r=await Ho(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let o=Bi(r,null,n);await Cr(e,{t:n,k:"ok",v:t});let i=o.chain;i!==null&&i.failures.length>=4&&!o.resolved&&i.lastVerb===t&&await oe({event:"difficulty_resolved",session_id:e,detail:String(i.failures.length)})}function Ep(e){for(let t of[e.session_id,e.conversation_id])if(typeof t=="string"&&t.trim().length>0)return t.trim();return null}async function x5(e,t){let n=Se();if(n.mode==="off"||!n.difficulty&&!n.capture)return null;let r=Ep(e);if(r===null)return null;let o=QP(e,t.host);if(o===null)return null;let i=t_(o.outcome);if(i===null)return null;let a=Date.now();if(i.kind==="ok")return await S5(r,i.verb,a),null;await Cr(r,{t:a,k:"fail",v:i.verb});let l=await Ho(r),c=Bi(l,Ir(await ue(),r),a);if(!o_(c)||c.chain===null)return null;let u=await Ar(!0);return!n.difficulty||!mr(u.difficulty)?null:(await Cr(r,{t:a,k:"nudge"}),await oe({event:"difficulty_nudge",session_id:r,cwd:be(e,t),project_key:Z()??void 0,detail:String(c.chain.failures.length)}),{kind:"context",event:o.event,text:Va(c.chain)})}var v5,ks=w(()=>{"use strict";Dt();Ie();ut();de();Zt();pn();Rl();Fo();s(ik,"bashOutputOf");v5={cursor:["Shell","Bash"],codex:["Bash"],copilot:["run_in_terminal","bash","Bash"],gemini:["run_shell_command"],devin:["exec","Bash"]};s(bs,"textOf");s(ok,"exitCodeInText");s(ZP,"foreignShellResult");s(QP,"outcomeFromHook");s(Ir,"consultedAtOf");s(S5,"recordSuccess");s(Ep,"sensorSessionId");s(x5,"difficultyCore")});var oM={};Q(oM,{PLAN_ACCEPTED_SUBCOMMAND:()=>R5,acceptedPlanOf:()=>nM,planAcceptedCore:()=>$5,planAcceptedText:()=>rM});import{existsSync as E5,readFileSync as T5}from"node:fs";import{homedir as A5}from"node:os";import{join as eM}from"node:path";function ak(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Hn(e){return typeof e=="string"&&e.trim().length>0?e:null}function tM(e){try{return T5(e,"utf8").length}catch{return 0}}function I5(e){let t=C5.exec(e.trim())?.[1]?.trim()??null;return t===null?null:{path:t,length:tM(t)}}function N5(e,t){if(!O5.test(t.trim()))return null;let n=Hn(e.session_id)?.trim(),r=process.env.COPILOT_HOME?.trim()||eM(A5(),".copilot"),o=n?eM(r,"session-state",n,"plan.md"):null;return o!==null&&E5(o)?{path:o,length:tM(o)}:{path:null,length:0}}function nM(e){if(typeof e.tool_name!="string"||!D5.has(e.tool_name)||Hn(e.agent_id)!==null)return null;let t=Hn(ak(e.tool_result)?.text_result_for_llm);if(t!==null)return N5(e,t);let n=ak(e.tool_response),r=Hn(n?.returnDisplay);if(r!==null)return I5(r);if(n?.isAgent===!0)return null;let o=ak(e.tool_input),i=Hn(n?.plan)??Hn(o?.plan),a=Hn(n?.filePath)??Hn(o?.planFilePath);return i===null&&a===null?null:{path:a,length:i?.length??0}}function P5(e){let t=e.key??"the object";return e.title?`${t} \u201C${e.title}\u201D`:t}function lk(e,t){return`maind object plan --object ${e} --file ${t??"<the plan file>"}`}function rM(e){let{target:t,bound:n,path:r,length:o}=e,i=["[maind] The plan was accepted \u2014 it belongs on its MAIND work object, before you build."];if(t.objectId!==null)i.push(`This session is bound to ${P5({key:t.key,title:t.title})}. If the plan belongs to it, attach it now: work_object_attach_plan (object_id "${t.objectId}", plan: the accepted text), or in a shell \`${lk(t.objectId,r)}\`. If it belongs to another object, attach it there once that object exists \u2014 work_object_create takes the plan directly.`);else if(n.length>1)i.push(`This session is bound to ${n.map(a=>a.key??a.id).join(", ")}. Attach the plan to the one it belongs to: work_object_attach_plan (that object's id, plan: the accepted text), or in a shell \`${lk("<uuid>",r)}\`. For new work, work_object_create takes the plan directly.`);else{let a=t.reason==="not_announced"?"maind does not know this session's work object yet.":"This session is bound to no work object.";i.push(`${a} Attach the plan where it belongs: work_object_create takes it as \`plan\` for new work, work_object_attach_plan adds it to an existing object (in a shell \`${lk("<uuid>",r)}\`).`)}return o>mc&&i.push(`The plan has ${o} characters; the server takes at most ${mc}. Shorten it for the attachment and say that you did.`),i.push("If it is already attached, nothing to do."),i.join(" ")}function M5(e,t,n){let r=Hn(e.session_id)?.trim()??null,o=fn(Pt(e)||null,r??""),i=kt(nt(t),{hostPids:Fe(),cwd:n,selfId:o})?.snap;return!i||i.announce_error?null:{boundObjects:i.bound_objects??null,branchObjectId:i.branch_object_id??null}}async function $5(e,t,n={}){let r=nM(e);if(r===null||!me(t,{kind:"context",event:"PostToolUse"}))return null;let o=(n.projectKey??Z)();if(o===null)return null;let i=(n.ownSnapshot??M5)(e,o,be(e,t));if(i===null)return null;let a=yr(i);return{kind:"context",event:"PostToolUse",text:rM({target:a,bound:i.boundObjects??[],path:r.path,length:r.length})}}var R5,C5,O5,D5,iM=w(()=>{"use strict";Et();_r();Mn();de();Ji();Oo();tt();Ie();Lt();R5="on-plan-accepted";s(ak,"record");s(Hn,"text");s(tM,"fileLength");C5=/^Plan approved: (.+)$/;s(I5,"geminiAcceptedPlan");O5=/^Plan approved[!,]/;s(N5,"copilotAcceptedPlan");D5=new Set(["ExitPlanMode","exit_plan_mode"]);s(nM,"acceptedPlanOf");s(P5,"named");s(lk,"shellLine");s(rM,"planAcceptedText");s(M5,"defaultOwnSnapshot");s($5,"planAcceptedCore")});function sM(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var ck=w(()=>{"use strict";s(sM,"resolveConnection")});function aM(e=j5()){return e?.codex_session_analytics===!0}function lM(e,t){let n=e.own_snapshot_age_ms;return(e.own_snapshot_via==="session"||e.own_snapshot_via==="ppid"||e.own_snapshot_names_session===!0)&&n!==null&&n<=18e5||t?"connected":"unknown"}function j5(){try{return re()}catch{return null}}var uk=w(()=>{"use strict";Ce();ck();s(aM,"codexSessionAnalyticsAllowed");s(lM,"resolveCodexConnection");s(j5,"safeReadConfig")});import{execFile as pk}from"node:child_process";import{randomUUID as F5}from"node:crypto";function W5(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return dk.test(t)?t:F5()}function fk(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function V5(e,t){let n=(e.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:t?.auto_working_paths===!0}async function q5(e,t){return await new Promise(n=>{pk("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8",...t?{cwd:t}:{}},(r,o)=>{if(r)return n(null);n(z5(o))})})}function z5(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function J5(e){return await new Promise(t=>{pk("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8",...e?{cwd:e}:{}},(n,r)=>{if(n)return t(null);let o=r.trim();t(o.length>0&&o!=="HEAD"?o:null)})})}function Y5(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function X5(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),o=dk.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:o,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(i=>{dk.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}function Q5(e){let t=new Set,n=s(o=>Array.isArray(o)?o:[],"rows"),r=e.work_repo!==null&&typeof e.work_repo=="object"?e.work_repo.peers:void 0;for(let o of[...n(e.peers),...n(r)]){if(o===null||typeof o!="object")continue;let i=o;if(i.is_self!==!0)for(let a of n(i.bound_objects)){let l=a!==null&&typeof a=="object"?a.id:null;typeof l=="string"&&t.add(l.toLowerCase())}}return t}function e8(){let e=null;return()=>(e??=new Promise(t=>{pk("git",["rev-parse","--show-toplevel"],{timeout:2e3,encoding:"utf8"},(n,r)=>{let o=n?"":r.trim();t(o.length>0?o:null)})}),e)}var cM,uM,H5,U5,B5,G5,K5,dk,Tp,Z5,mk=w(()=>{"use strict";_r();Ce();cM=45e3,uM=3e4,H5=5,U5=120,B5=3e4,G5=15*6e4,K5=1500,dk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(W5,"resolveClientSessionId");s(fk,"autoAnnounceDisabled");s(V5,"autoWorkingPathsEnabled");Tp=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;workRepo;lastSentWorkKey=null;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;nestedProjectKeys;onAnnounced;lastBranch=null;lastBranchObjectId=null;lastBoundObjects=null;peerBoundIds=new Set;editRoots;homeRoot;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??re)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??J5,this.gitBranchObject=t.gitBranchObject??q5,this.workRepo=t.workRepo??null,this.editRoots=t.editRoots??(()=>new Set),this.homeRoot=t.homeRoot??e8(),this.log=t.log??(o=>process.stderr.write(o+`
1055
+ `)),this.machineLabel=Y5(r?.machine_label),this.enabled=this.projectKey!==null&&!fk(n,r),this.workingPathsEnabled=V5(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??X5(n,W5(n)),this.sessionMeta=t.sessionMeta??null,this.nestedProjectKeys=t.nestedProjectKeys??null,this.onAnnounced=t.onAnnounced??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}boundObjects(){return this.lastBoundObjects}branchObjectId(){return this.lastBranchObjectId}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<cM||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<cM||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<H5||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,K5).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(B5*2**(this.consecutiveFailures-1),G5);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let a=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${a} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r=null;if(t==="active"&&this.workRepo!==null)try{r=await this.workRepo()}catch{r=null}let o={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:U5,announce_source:"bridge"};if(t==="active"){o.identity_source=n.source,n.aliases.length>0&&(o.also_known_as=n.aliases),r!==null&&(r.projectKey!==this.projectKey||this.lastSentWorkKey!==null&&this.lastSentWorkKey!==this.projectKey)&&(o.work_project_key=r.projectKey,this.lastSentWorkKey=r.projectKey);let a=await this.gitBranch(r?.root??null);a&&(o.branch=a),this.lastBranch=a;let l=null;if(a)try{let c=r===null?null:await this.homeRoot(),d=r===null||r.root===c||this.editRoots().has(r.root)?await this.gitBranchObject(a,r?.root??null):null;l=d;let p=this.lastBoundObjects?.map(m=>m.id)??[],f=d?.toLowerCase()??null;d!==null&&d!==this.lastSentObjectId&&!this.peerBoundIds.has(f)&&!p.includes(f)&&(o.object_ids=[...p,d].slice(-Z5),this.lastSentObjectId=d)}catch{}if(this.lastBranchObjectId=l,this.machineLabel&&(o.machine_label=this.machineLabel),this.nestedProjectKeys!==null)try{let c=this.nestedProjectKeys();c.length>0&&(o.nested_project_keys=[...c])}catch{}if(this.sessionMeta!==null)try{let c=await this.sessionMeta();c?.model&&(o.model=c.model),c?.title&&(o.title=c.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let c=await this.deriveWorkingPaths();c&&c.length>0&&(o.working_paths=c)}catch{}}let i=await this.postToolCall("announce_session",o);if(t==="active"&&i!==null&&typeof i=="object"){let a=i;if(a.ok===!0&&typeof a.session_id=="string")try{this.identity.adopt(a.session_id)}catch{}if(a.ok===!0&&a.ended!==!0){try{this.lastBoundObjects=Qa(a.bound_objects)}catch{this.lastBoundObjects=[]}this.peerBoundIds=Q5(a)}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let a=this.identity.current(),l={sessionId:a.id,branch:this.lastBranch,branchObjectId:this.lastBranchObjectId,identitySource:a.source,aliases:a.aliases},c=typeof i=="object"?i:null;if(c!==null&&c.ok===!0)this.snapshot.write(i,l),r!==null&&r.projectKey!==this.projectKey&&c.work_repo!==void 0&&c.work_repo!==null?this.snapshot.writeWork?.(c.work_repo,l):this.snapshot.clearWork?.();else if(this.snapshot.markFailed){let u=c!==null&&typeof c.error=="string"?c.error:"announce_failed";this.snapshot.markFailed(u,l)}}}catch{}if(t==="active"&&this.onAnnounced!==null)try{this.onAnnounced()}catch{}}};s(q5,"defaultGitBranchObject");s(z5,"normalizeObjectId");s(J5,"defaultGitBranch");s(Y5,"normalizeMachineLabel");s(X5,"staticIdentity");Z5=8;s(Q5,"peerBoundIdsOf");s(e8,"onceHomeRoot")});function pM(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!dM.test(n))return null;let r=n.toLowerCase();return t!==null&&dM.test(t)&&r!==t.toLowerCase()?null:r}var dM,fM=w(()=>{"use strict";dM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(pM,"snapshotSessionId")});import{appendFileSync as t8,existsSync as Ap,mkdirSync as mM,readFileSync as n8,readdirSync as r8,renameSync as hk,rmdirSync as hM,statSync as gk,unlinkSync as gM,writeFileSync as o8}from"node:fs";import{join as ws}from"node:path";function yk(e){return e&&_M.test(e)?e:"no-session"}function Cl(e,t){return ws(e,`${t}.job.json`)}function _k(e,t){return ws(e,`${t}.running.json`)}function bM(e,t){return ws(e,`${t}.lock`)}function bk(e){Ap(e)||mM(e,{recursive:!0,mode:448})}function kM(e,t){bk(e);let n=yk(t.session_id),r=`${Cl(e,n)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;o8(r,JSON.stringify(t),{mode:384}),hk(r,Cl(e,n))}function l8(e){try{let t=JSON.parse(e);if(t&&t.v===1&&typeof t.transcript_path=="string"&&typeof t.cwd=="string")return{v:1,session_id:typeof t.session_id=="string"?t.session_id:null,transcript_path:t.transcript_path,cwd:t.cwd,coord_session_id:typeof t.coord_session_id=="string"?t.coord_session_id:null,project_key:typeof t.project_key=="string"?t.project_key:null,presence:{own_snapshot_age_ms:typeof t.presence?.own_snapshot_age_ms=="number"?t.presence.own_snapshot_age_ms:null,presence_usable:t.presence?.presence_usable===!0,...t.presence?.own_snapshot_via==="session"||t.presence?.own_snapshot_via==="ppid"||t.presence?.own_snapshot_via==="cwd"?{own_snapshot_via:t.presence.own_snapshot_via}:{},...t.presence?.own_snapshot_names_session===!0?{own_snapshot_names_session:!0}:{}},queued_at:typeof t.queued_at=="string"?t.queued_at:new Date(0).toISOString(),...t.client==="codex"?{client:"codex"}:{}}}catch{}return null}function wM(e,t){return Ap(Cl(e,t))}function vM(e,t){let n=Cl(e,t),r=_k(e,t);try{if(Ap(n)&&hk(n,r),!Ap(r))return null;let o=l8(n8(r,"utf8"));return o===null?(gM(r),null):o}catch{return null}}function SM(e,t){try{gM(_k(e,t))}catch{}}function kk(e,t,n=Date.now()){bk(e);let r=bM(e,t);try{if(n-gk(r).mtimeMs<i8)return!1;hM(r)}catch{}try{return mM(r,{recursive:!1}),!0}catch{return!1}}function wk(e,t){try{hM(bM(e,t))}catch{}}function xM(e){try{let t=new Set;for(let n of r8(e)){let r=/^(.+)\.(job|running)\.json$/.exec(n);r&&_M.test(r[1])&&t.add(r[1])}return[...t].sort()}catch{return[]}}function EM(e,t){for(let n of[Cl(e,t),_k(e,t)])try{return gk(n).mtimeMs}catch{}return null}function vs(e,t,n=s8){try{bk(e);let r=ws(e,a8);try{gk(r).size>n&&hk(r,ws(e,"runs.1.jsonl"))}catch{}t8(r,JSON.stringify(t)+`
1056
+ `,{mode:384})}catch{}}var Un,i8,yM,s8,a8,_M,vk=w(()=>{"use strict";ut();Un=ws(et,"session-end"),i8=10*6e4,yM=7*24*60*6e4,s8=256*1024,a8="runs.jsonl",_M=/^[A-Za-z0-9_-]{1,80}$/;s(yk,"jobKey");s(Cl,"jobPath");s(_k,"runningPath");s(bM,"lockPath");s(bk,"ensureDir");s(kM,"writeJob");s(l8,"parseJob");s(wM,"hasJob");s(vM,"takeJob");s(SM,"finishJob");s(kk,"acquireLock");s(wk,"releaseLock");s(xM,"pendingKeys");s(EM,"pendingSince");s(vs,"appendRunLog")});function Sk(e,t,n,r=Date.now()){let o=t===null?null:Fi(t),i=typeof n=="object"&&n!==null?n:{repoRoot:n},a=Dy(e,o,{repoRoot:i.repoRoot,...i.relativize?{relativize:i.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:o!==null}}var TM=w(()=>{"use strict";Eo();s(Sk,"buildCostPayload")});function AM(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();c8.test(r)&&!t.includes(r)&&t.push(r)}return t}async function RM(e){let t=e.now??Date.now,n=performance.now(),{turns:r,coordination_ids:o}=await Ma(e.transcriptPath),i=Math.round(performance.now()-n),a=e.resolveRoot&&e.projectKeyOf?td({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:IM(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,l=a?nd(r,a):null,c=l??e.projectKey,u=AM([e.coordSessionId,e.sessionId,...o]),d=performance.now(),[p,f,m]=await Promise.all([Ty(e.transcriptPath,{turns:r}),Uy(e.transcriptPath),e.fetchContext(c,u)]),h={collect_ms:i,parallel_ms:Math.round(performance.now()-d)};if(a&&e.rememberCheckouts)try{e.rememberCheckouts(a.seenLive())}catch{}if(e.sessionId&&(p.session_id=e.sessionId,f.session_id=e.sessionId),p.maind_connected=e.connection(p.maind_connected==="connected",t()),!p.session_id)return{posted:!1,contextOk:m!==null,sentSlices:!1,timings:h};let g=l&&a?rd(l,a):null,_=Sk(r,m,{repoRoot:e.repoRoot,relativize:g},t()),b=m===null?null:Fi(m)?.canonical_session_id??null,k=e.coordSessionId??b,v=Yu(p,f,{client_session_id:k,client:"claude-code",coordination_session_ids:u},"live_bridge",_);return await e.post(v,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:h}}async function CM(e){let t=e.now??Date.now,n=performance.now(),{turns:r}=await ja(e.transcriptPath),o=Math.round(performance.now()-n),i=e.resolveRoot&&e.projectKeyOf?td({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:IM(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,a=i?nd(r,i):null,l=a??e.projectKey,c=performance.now(),u=await Fy(e.transcriptPath,{turns:r});if(u===null)return{posted:!1,contextOk:!1,sentSlices:!1,timings:{collect_ms:o,parallel_ms:Math.round(performance.now()-c)}};let{coordination_ids:d,...p}=u,f=AM([e.coordSessionId,e.sessionId,p.session_id,...d]),m=await e.fetchContext(l,f),h={collect_ms:o,parallel_ms:Math.round(performance.now()-c)};if(i&&e.rememberCheckouts)try{e.rememberCheckouts(i.seenLive())}catch{}if(e.sessionId&&(p.session_id=e.sessionId),p.maind_connected=e.connection(p.maind_connected==="connected",t()),!p.session_id)return{posted:!1,contextOk:m!==null,sentSlices:!1,timings:h};let g=a&&i?rd(a,i):null,_=Sk(r,m,{repoRoot:e.repoRoot,relativize:g},t()),b=m===null?null:Fi(m)?.canonical_session_id??null,k=e.coordSessionId??b,v=Yu(p,null,{client_session_id:k,client:"codex",coordination_session_ids:f},"live_bridge",_);return await e.post(v,_!==null),{posted:!0,contextOk:_?.context_ok??m!==null,sentSlices:_!==null,timings:h}}function IM(e,t){try{return e()}catch{return t}}var c8,OM=w(()=>{"use strict";Eo();TM();c8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(AM,"sessionIdsFor");s(RM,"ingestSessionEnd");s(CM,"ingestCodexSessionEnd");s(IM,"safe")});var UM={};Q(UM,{FLUSH_LOCK_KEY:()=>Ak,INLINE_BUDGET:()=>Ck,SESSION_END_WORKER:()=>Rk,SWEEP_MAX_KEYS:()=>MM,SWEEP_MIN_AGE_MS:()=>PM,WORKER_BUDGET:()=>DM,WORKER_DEADLINE_MS:()=>Ek,drainSession:()=>Ik,fetchCostContext:()=>$M,flushUnderLock:()=>HM,gitResolvers:()=>jM,liveJobDeps:()=>Cp,postIngest:()=>LM,postIngestOnce:()=>Tk,processJob:()=>Rp,runSessionEndWorker:()=>p8,sweepPending:()=>FM});import{execFileSync as u8}from"node:child_process";import{existsSync as NM,statSync as d8}from"node:fs";async function $M(e,t,n,r,o){if(n===null)return null;let[i,...a]=r;try{return await Qt("get_session_cost_context",{project_key:n,...i?{session_id:i}:{},...a.length>0?{also_session_ids:a}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:K,timeoutMs:o})}catch{return null}}async function Tk(e,t,n,r,o,i=fetch){let a=new AbortController,l=setTimeout(()=>a.abort(),r);try{let c=await i(Td,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":K},body:JSON.stringify(n),signal:a.signal}),u=await c.json().catch(()=>null);if(!c.ok)return{outcome:"post_failed",status:c.status};let d=Ry(Ay(u),o);return{outcome:"posted",status:c.status,...d?{verdict:d}:{}}}catch(c){return{outcome:a.signal.aborted||c instanceof Error&&c.name==="AbortError"?"post_timeout":"post_error"}}finally{clearTimeout(l)}}async function LM(e,t,n,r,o,i={}){let a=i.sleep??(d=>new Promise(p=>setTimeout(p,d))),l=await Tk(e,t,n,o.postMs,r,i.fetchImpl),c=1;return(l.outcome==="post_timeout"||l.outcome==="post_error"||l.outcome==="post_failed"&&(l.status??0)>=500)&&o.postRetryDelayMs>0&&(await a(o.postRetryDelayMs),l=await Tk(e,t,n,o.postMs,r,i.fetchImpl),c=2),{...l,attempts:c}}function xk(e,t){try{let n=u8("git",e,{...t?{cwd:t}:{},encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return n.length>0?n:null}catch{return null}}function jM(){let e=new Map,t=new Map;return{repoRootOf:s(n=>NM(n)?xk(["rev-parse","--show-toplevel"],n):null,"repoRootOf"),gitRootOf:s(n=>{let r=e.get(n);if(r!==void 0)return r;let o=xk(["-C",n,"rev-parse","--show-toplevel"]);return e.set(n,o),o},"gitRootOf"),projectKeyOfRoot:s(n=>{let r=t.get(n);if(r!==void 0)return r;let o=xk(["-C",n,"config","--get","remote.origin.url"]),i=o?nr(o):null;return t.set(n,i),i},"projectKeyOfRoot"),isDir:s(n=>{try{return d8(n).isDirectory()}catch{return!1}},"isDir")}}async function Rp(e,t){let n=t.now??Date.now,r=n(),o=Date.parse(e.queued_at),i={queued:Number.isFinite(o)?Math.max(0,r-o):0},a={ts:new Date(r).toISOString(),bridge:K,session_id:e.session_id,outcome:"no_transcript",ms:i,...e.client?{client:e.client}:{}};try{if(e.transcript_path)if(!NM(e.transcript_path))a.outcome="transcript_gone";else{let c=jM(),u=t.memoryPath??Hi,d=null,p=e.client==="codex",m=await(p?CM:RM)({apiKey:t.apiKey,deviceId:t.deviceId,sessionId:e.session_id,transcriptPath:e.transcript_path,projectKey:e.project_key,coordSessionId:e.coord_session_id,repoRoot:c.repoRootOf(e.cwd),resolveRoot:c.gitRootOf,projectKeyOf:c.projectKeyOfRoot,isDir:c.isDir,...t.memoryAllowed?{knownCheckouts:s(()=>$a(u),"knownCheckouts"),rememberCheckouts:s(g=>La(u,g),"rememberCheckouts")}:{},fetchContext:s(async(g,_)=>{let b=n();try{return await t.fetchContext(g,_)}finally{i.context=n()-b}},"fetchContext"),post:s(async(g,_)=>{let b=n();d=await t.post(g,_),i.post=n()-b},"post"),connection:s(g=>p?lM(e.presence,g):sM({ownSnapshotAgeMs:e.presence.own_snapshot_age_ms,sawMaindCall:g,presenceUsable:e.presence.presence_usable}),"connection"),now:n});a.context_ok=m.contextOk,a.sent_slices=m.sentSlices,m.timings&&(i.collect=m.timings.collect_ms,i.parallel=m.timings.parallel_ms);let h=d;!m.posted||h===null?a.outcome="not_posted":(a.outcome=h.outcome,a.attempts=h.attempts,h.status!==void 0&&(a.http_status=h.status),h.verdict&&(a.verdict=h.verdict))}}catch(c){a.outcome="error",a.error=(c instanceof Error?c.message:String(c)).slice(0,200)}let l=n();try{let c=await t.flush();a.flush=c===null?"unpaired":c.ok?`ok:${c.flushed}`:`failed:${c.error??"unknown"}`}catch(c){a.flush=`failed:${(c instanceof Error?c.message:String(c)).slice(0,80)}`}return i.flush=n()-l,i.total=n()-r,a}async function Ik(e,t,n,r={}){let o=r.now??Date.now,i=r.maxRounds??20,a=0;for(;a<i&&kk(e,t,o());){try{let l=vM(e,t);if(l===null)break;let c=Date.parse(l.queued_at),u=Number.isFinite(c)&&o()-c>yM?{ts:new Date(o()).toISOString(),bridge:K,session_id:l.session_id,outcome:"expired",ms:{queued:o()-c}}:await n(l);vs(e,u),SM(e,t),a++}finally{wk(e,t)}if(!wM(e,t))break}return a}async function FM(e,t,n,r={}){let o=r.now??Date.now,i=0;for(let a of xM(e)){if(i>=MM)break;if(a===t)continue;let l=EM(e,a);l===null||o()-l<PM||await Ik(e,a,n,{...r,maxRounds:1})>0&&i++}return i}async function HM(e,t,n=Date.now){if(!kk(e,Ak,n()))return{ok:!1,flushed:0,remaining:0,error:"busy"};try{return await t()}finally{wk(e,Ak)}}function Cp(e,t,n){return{apiKey:e,deviceId:t,fetchContext:s((r,o)=>$M(e,t,r,o,n.contextMs),"fetchContext"),post:s((r,o)=>LM(e,t,r,o,n),"post"),flush:s(()=>HM(Un,()=>yp(n.flushMs)),"flush"),memoryAllowed:sd()}}async function p8(e=process.argv){let t=e[3]??"no-session",n=setTimeout(()=>{vs(Un,{ts:new Date().toISOString(),bridge:K,session_id:t,outcome:"deadline",ms:{total:Ek}}),process.exit(0)},Ek);n.unref();try{let r=ee();if(!r)return 0;let o=ke(),i=s(a=>Rp(a,Cp(r,o,DM)),"run");await Ik(Un,t,i),await FM(Un,t,i)}catch(r){vs(Un,{ts:new Date().toISOString(),bridge:K,session_id:t,outcome:"error",ms:{},error:(r instanceof Error?r.message:String(r)).slice(0,200)})}finally{clearTimeout(n)}return 0}var Rk,DM,Ck,Ek,PM,MM,Ak,Ok=w(()=>{"use strict";Eo();we();Ln();K_();Lt();de();Xe();ad();ck();uk();OM();vk();Rk="session-end-run",DM={contextMs:1e4,postMs:15e3,flushMs:1e4,postRetryDelayMs:3e3},Ck={contextMs:2e3,postMs:1500,flushMs:1500,postRetryDelayMs:0},Ek=3*6e4,PM=2*6e4,MM=3;s($M,"fetchCostContext");s(Tk,"postIngestOnce");s(LM,"postIngest");s(xk,"git");s(jM,"gitResolvers");s(Rp,"processJob");s(Ik,"drainSession");s(FM,"sweepPending");Ak="metrics-flush";s(HM,"flushUnderLock");s(Cp,"liveJobDeps");s(p8,"runSessionEndWorker")});var Nk={};Q(Nk,{buildJob:()=>WM,enqueueAndSpawn:()=>VM,ingestSourceOf:()=>KM,presenceLookup:()=>BM,runOnSessionEnd:()=>b8,sessionEndCore:()=>k8,transcriptToIngest:()=>GM});import{spawn as f8}from"node:child_process";import{existsSync as m8,unlinkSync as h8}from"node:fs";import{join as g8}from"node:path";function BM(e,t,n,r){let o=null,i={own_snapshot_age_ms:null,presence_usable:!1};try{if(i.presence_usable=e!==null&&!fk(process.env,re()),e!==null){let a=kt(nt(e),{hostPids:r,cwd:process.cwd(),selfId:t});if(o=pM(a?.snap,t),a){let l=Date.parse(a.snap.written_at);i={...i,own_snapshot_age_ms:Number.isFinite(l)?Math.max(0,n-l):null,own_snapshot_via:a.via,...t!==null&&o!==null?{own_snapshot_names_session:!0}:{}}}}}catch{i={own_snapshot_age_ms:null,presence_usable:!1},o=null}if(o===null){let a=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(a)&&(o=a)}return{coordSessionId:o,evidence:i}}function GM(e,t=process.env,n=null){let r=Pt(e),o=n?.host??hr(e,t);return r&&!Ro(o)?r:""}function KM(e,t=process.env,n=null,r=aM){if((n?.host??hr(e,t))==="codex"){let i=Pt(e);return i&&S_(i)&&r()?{path:i,client:"codex"}:{path:""}}return{path:GM(e,t,n)}}function WM(e,t){let n=typeof e.session_id=="string"&&e.session_id?e.session_id:null,r={v:1,session_id:n,transcript_path:t.transcriptPath,cwd:t.cwd,coord_session_id:null,project_key:null,presence:{own_snapshot_age_ms:null,presence_usable:!1},queued_at:new Date(t.nowMs).toISOString(),...t.client&&t.transcriptPath?{client:t.client}:{}};if(!t.transcriptPath)return r;let o=t.projectKey(),i=t.presence(o,fn(t.transcriptPath,n),t.nowMs);return{...r,project_key:o,coord_session_id:i.coordSessionId,presence:i.evidence}}function VM(e,t={}){let n=t.dir??Un,r="entry"in t?t.entry:process.argv[1];if(r===void 0)return!1;let o=yk(e.session_id);try{kM(n,e)}catch{return!1}try{return(t.spawnWorker??y8)(r,o,e.cwd),!0}catch{try{h8(g8(n,`${o}.job.json`))}catch{}return!1}}function y8(e,t,n){f8(process.execPath,[e,Rk,t],{detached:!0,stdio:"ignore",cwd:m8(n)?n:process.cwd(),env:process.env,windowsHide:!0}).unref()}async function _8(e,t){try{let n=await Rp(e,Cp(t,ke(),Ck));vs(Un,{...n,outcome:`inline:${n.outcome}`})}catch(n){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${n instanceof Error?n.message:String(n)}
1057
+ `)}}async function b8(){return ve(["on-session-end"])}async function k8(e,t){let n=[];try{n=Fe()}catch{n=[]}try{for(let a of n)_O(kr(),a)}catch{}let r=ee();if(!r)return null;let o=typeof e.session_id=="string"&&e.session_id?e.session_id:null;await gp(o);let i;try{let a=KM(e,process.env,t);i=WM(e,{...a.client?{client:a.client}:{},transcriptPath:a.path,cwd:process.cwd(),nowMs:Date.now(),projectKey:Z,presence:s((l,c,u)=>BM(l,c,u,n),"presence")})}catch{return null}return VM(i)||await _8(i,r),null}var Dk=w(()=>{"use strict";Ce();we();Oo();Oe();tt();Ie();uk();Lt();mk();Mn();de();Ji();fM();vk();Ok();s(BM,"presenceLookup");s(GM,"transcriptToIngest");s(KM,"ingestSourceOf");s(WM,"buildJob");s(VM,"enqueueAndSpawn");s(y8,"spawnDetachedWorker");s(_8,"runInline");s(b8,"runOnSessionEnd");s(k8,"sessionEndCore")});import{mkdirSync as qM,rmdirSync as zM,statSync as w8}from"node:fs";import{join as JM}from"node:path";import{setTimeout as v8}from"node:timers/promises";function YM(e){return JM(e,".maind","index-refresh.lock")}function Ip(e,t=Date.now()){let n=YM(e);try{if(t-w8(n).mtimeMs<S8)return!1;zM(n)}catch{}try{return qM(n,{recursive:!1}),!0}catch{return!1}}function Il(e){try{zM(YM(e))}catch{}}async function XM(e,t,n={}){let r=n.now??Date.now,o=n.sleep??(a=>v8(a).then(()=>{})),i=r()+(n.waitMs??3e4);try{qM(JM(e,".maind"),{recursive:!0})}catch{}for(;!Ip(e,r());){if(r()>=i)return{locked:!1};await o(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Il(e)}}var S8,Pk=w(()=>{"use strict";S8=30*6e4;s(YM,"lockPath");s(Ip,"acquireLock");s(Il,"releaseLock");s(XM,"withIndexLock")});var Op={};Q(Op,{INDEX_REFRESH_WORKER:()=>ZM,acquireLock:()=>Ip,indexRefreshCore:()=>C8,releaseLock:()=>Il,runIndexRefreshWorker:()=>I8,runOnIndexRefresh:()=>R8});import{spawn as x8}from"node:child_process";import{existsSync as E8}from"node:fs";import{join as T8}from"node:path";function A8(e){return T8(e,".maind","code-index.sqlite")}async function R8(){return ve(["on-index-refresh"])}async function C8(e,t){try{let n=pt(be(e,t));if(!E8(A8(n))||!Ip(n))return null;let r=process.argv[1];if(r===void 0)return Il(n),null;x8(process.execPath,[r,ZM,n],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return null}async function I8(){let e=process.argv[3]??pt();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Xd(),fb)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Il(e)}return 0}var ZM,Np=w(()=>{"use strict";Oe();Ie();xr();Pk();ZM="index-refresh-run";s(A8,"indexDbPath");s(R8,"runOnIndexRefresh");s(C8,"indexRefreshCore");s(I8,"runIndexRefreshWorker")});var p$={};Q(p$,{decideDocDutyReminder:()=>t$,decideLocally:()=>Lk,docDutyCore:()=>F8,lessonFindingOf:()=>s$,lessonStateDir:()=>Pp,lessonThenDoc:()=>l$,localDocFacts:()=>r$,ownBoundObject:()=>$p,readServerDocState:()=>u$,readServerLessonCheck:()=>c$,reminderStateDir:()=>jk,saidByCli:()=>d$,stampLessonAsked:()=>Mp,workTreeFor:()=>o$,writeLessonTeam:()=>a$});import{execFileSync as O8}from"node:child_process";import{existsSync as QM,mkdirSync as Mk,readdirSync as N8,readFileSync as Dp,writeFileSync as $k}from"node:fs";import{homedir as e$}from"node:os";import{join as Ft,resolve as D8}from"node:path";function Lk(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.ownTree?e.hasWork?e.locallySatisfied?{remind:!1,why:"locally_satisfied"}:null:{remind:!1,why:"no_work"}:{remind:!1,why:"no_own_tree"}:{remind:!1,why:"no_object"}}function t$(e){let t=Lk(e);if(t)return t;let n=e.object.key;if(e.server?.finished)return{remind:!1,why:"finished"};if(e.server?.inReview)return{remind:!1,why:"in_review"};if(e.server?.docDuty==="off")return{remind:!1,why:"duty_off"};if(e.server?.heldByOther)return{remind:!1,why:"held_by_other"};if(e.server&&!e.server.docMissing)return{remind:!1,why:"documented_elsewhere"};let r=e.server?.docDuty==="require";return{remind:!0,reason:lm(n,r)+` This reminder comes once per session for ${n}.`}}function jt(e,t){try{return O8("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:8*1024*1024})}catch{return null}}function n$(e){let t=jt(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=jt(e,["merge-base",r,"HEAD"])?.trim();if(o)return o}return null}function r$(e,t){let n=n$(e),r=n?(jt(e,["-c","core.quotepath=off","diff","--name-only",`${n}`,"HEAD"])??"").split(`
1058
1058
  `):[],i=(jt(e,["-c","core.quotepath=off","status","--porcelain","--untracked-files=all"])??"").split(`
1059
- `).filter(d=>d.length>3).map(d=>d.slice(3).replace(/^.* -> /,"").replace(/^"|"$/g,"")),a=[...new Set([...r,...i].map(d=>d.trim()).filter(Boolean))],l=a.length>0;if(!l)return{hasWork:l,locallySatisfied:!1};if(Bs(a.filter(li),d=>{try{return Dp(Ft(e,d),"utf8")}catch{return null}},t).length>0)return{hasWork:l,locallySatisfied:!0};let u=n?(jt(e,["log","--reverse","--format=%B%x00",`${n}..HEAD`])??"").split("\0"):[];return{hasWork:l,locallySatisfied:Gs(u).kind==="ok"}}function o$(e,t){let n=jt(e,["rev-parse","--show-toplevel"])?.trim();if(!n)return null;let r=jt(e,["rev-parse","--abbrev-ref","HEAD"])?.trim();if(r&&jt(e,["config","--get",`branch.${r}.maindObject`])?.trim()===t)return e;let o=new Set;for(let i of[n,...N8(n)]){let a=jt(i,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!a||o.has(a))continue;o.add(a);let l=D8(i,t);if(l)return l}return null}function N8(e){try{return I8(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>Ft(e,t.name)).filter(t=>QM(Ft(t,".git")))}catch{return[]}}function D8(e,t){let n=jt(e,["config","--get-regexp","^branch\\..*\\.maindobject$"])??"",r=new Set(n.split(`
1059
+ `).filter(d=>d.length>3).map(d=>d.slice(3).replace(/^.* -> /,"").replace(/^"|"$/g,"")),a=[...new Set([...r,...i].map(d=>d.trim()).filter(Boolean))],l=a.length>0;if(!l)return{hasWork:l,locallySatisfied:!1};if(Bs(a.filter(li),d=>{try{return Dp(Ft(e,d),"utf8")}catch{return null}},t).length>0)return{hasWork:l,locallySatisfied:!0};let u=n?(jt(e,["log","--reverse","--format=%B%x00",`${n}..HEAD`])??"").split("\0"):[];return{hasWork:l,locallySatisfied:Gs(u).kind==="ok"}}function o$(e,t){let n=jt(e,["rev-parse","--show-toplevel"])?.trim();if(!n)return null;let r=jt(e,["rev-parse","--abbrev-ref","HEAD"])?.trim();if(r&&jt(e,["config","--get",`branch.${r}.maindObject`])?.trim()===t)return e;let o=new Set;for(let i of[n,...P8(n)]){let a=jt(i,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!a||o.has(a))continue;o.add(a);let l=M8(i,t);if(l)return l}return null}function P8(e){try{return N8(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")&&t.name!=="node_modules").map(t=>Ft(e,t.name)).filter(t=>QM(Ft(t,".git")))}catch{return[]}}function M8(e,t){let n=jt(e,["config","--get-regexp","^branch\\..*\\.maindobject$"])??"",r=new Set(n.split(`
1060
1060
  `).map(i=>/^branch\.(.+)\.maindobject\s+(\S+)$/.exec(i.trim())).filter(i=>i!==null&&i[2]===t).map(i=>i[1]));if(r.size===0)return null;let o=jt(e,["worktree","list","--porcelain"])??"";for(let i of o.split(`
1061
1061
 
1062
- `)){let a=/^worktree (.+)$/m.exec(i)?.[1],l=/^branch refs\/heads\/(.+)$/m.exec(i)?.[1];if(a&&l&&r.has(l))return O8(a)}return null}function jk(){return Ft(e$(),".maind","doc-duty")}function P8(e){return e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}function M8(e){try{let t=JSON.parse(Dp(e,"utf8"));return Array.isArray(t.reminded)?t.reminded.filter(n=>typeof n=="string"):[]}catch{return[]}}function Pp(){return Ft(e$(),".maind",Hs)}function i$(e){try{return Dp(e,"utf8")}catch{return null}}function s$(e,t){let n=n$(e);if(!n)return null;let r=Gf(jt(e,["log",`--format=${Bf}`,`${n}..HEAD`])??""),o=Kf(r);if(o.length===0)return null;let i=fc(i$(Ft(Pp(),pc,Qr(t))));return Wf(o,i)}function Mp(e,t,n){let r=Ft(Pp(),pc),o=Ft(r,Qr(e)),i=fc(i$(o));Mk(r,{recursive:!0}),$k(o,JSON.stringify({key:t,asked:[...i,n]}))}function a$(e,t){let n=Ft(Pp(),Us);Mk(n,{recursive:!0}),$k(Ft(n,Qr(e)),Vf(t,new Date))}function l$(e,t){let n=[e,t].filter(r=>r!==null&&r!=="");return n.length>0?n.join(`
1062
+ `)){let a=/^worktree (.+)$/m.exec(i)?.[1],l=/^branch refs\/heads\/(.+)$/m.exec(i)?.[1];if(a&&l&&r.has(l))return D8(a)}return null}function jk(){return Ft(e$(),".maind","doc-duty")}function $8(e){return e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}function L8(e){try{let t=JSON.parse(Dp(e,"utf8"));return Array.isArray(t.reminded)?t.reminded.filter(n=>typeof n=="string"):[]}catch{return[]}}function Pp(){return Ft(e$(),".maind",Hs)}function i$(e){try{return Dp(e,"utf8")}catch{return null}}function s$(e,t){let n=n$(e);if(!n)return null;let r=Gf(jt(e,["log",`--format=${Bf}`,`${n}..HEAD`])??""),o=Kf(r);if(o.length===0)return null;let i=fc(i$(Ft(Pp(),pc,Qr(t))));return Wf(o,i)}function Mp(e,t,n){let r=Ft(Pp(),pc),o=Ft(r,Qr(e)),i=fc(i$(o));Mk(r,{recursive:!0}),$k(o,JSON.stringify({key:t,asked:[...i,n]}))}function a$(e,t){let n=Ft(Pp(),Us);Mk(n,{recursive:!0}),$k(Ft(n,Qr(e)),Vf(t,new Date))}function l$(e,t){let n=[e,t].filter(r=>r!==null&&r!=="");return n.length>0?n.join(`
1063
1063
 
1064
- `):null}function c$(e,t){if(!e)return null;try{let n=JSON.parse(e),o=(Array.isArray(n.resolved)?n.resolved:[]).find(i=>i?.key===t);return o===void 0||typeof o.lesson_check!="string"?null:o.lesson_check==="on"}catch{return null}}function u$(e,t){if(!e)return null;try{let n=JSON.parse(e),o=(Array.isArray(n.resolved)?n.resolved:[]).find(u=>u?.key===t);if(!o)return null;let i=o.doc_duty;if(i!=="off"&&i!=="remind"&&i!=="require")return null;let a=typeof o.take=="object"&&o.take!==null?o.take:null,l=a!==null&&a.state==="held"&&a.by_this_session===!1,c=o.status==="passed"||o.status==="canceled";return{docDuty:i,docMissing:o.doc_missing===!0,...l?{heldByOther:l}:{},...c?{finished:c}:{},...o.doc_in_review===!0?{inReview:!0}:{}}}catch{return null}}function d$(e,t=Date.now()){let n=Ft(jk(),cm,um(e)),r=null;try{r=Dp(n,"utf8")}catch{r=null}return dm(r,t)}function $8(e){for(let t of[e.session_id,e.conversation_id])if(typeof t=="string"&&t.trim())return t.trim();return null}function $p(e,t,n,r){let o=fn(Pt(e)||null,r),i=kt(nt(t),{hostPids:Fe(),cwd:n,selfId:o})?.snap;if(!i||i.announce_error)return null;let a=yr({branchObjectId:i.branch_object_id??null,boundObjects:i.bound_objects??null});return a.objectId===null||!a.key?null:{own:i,object:{id:a.objectId,key:a.key}}}async function L8(e,t){let n=$8(e),r=be(e,t),o=!me(t,{kind:"stop"}),i=yd(e);if(o||i||n===null)return null;let a=Z();if(a===null)return null;let l=$p(e,a,r,n);if(l===null)return null;let{own:c,object:u}=l,d=jk(),p=Ft(d,`${P8(n)}.json`),f=QM(p)?M8(p):[],m=o$(r,u.id),h=m===null?{hasWork:!1,locallySatisfied:!1}:r$(m,u.key),g=Lk({standsDown:o,stopHookActive:i,object:u,alreadyReminded:f.includes(u.id)||d$(u.id),ownTree:m!==null,...h}),_=null;try{_=m===null?null:s$(m,u.id)}catch{_=null}if(g&&_===null)return null;let b=ee(),k=b?await Qt("get_my_work_objects",{project_key:a,session_id:c.own_session_id,keys:[u.key]},{apiKey:b,deviceId:ke(),projectKey:a,bridgeVersion:K,timeoutMs:3e3}):null,v=null,S=null,x=c$(k,u.key);try{x!==null&&a$(u.id,x),_!==null&&x===!0&&(Mp(u.id,u.key,ai(_.source)),v=Fs(_.source,_.check))}catch{}if(!g){let A=t$({standsDown:o,stopHookActive:i,object:u,alreadyReminded:!1,ownTree:!0,...h,server:u$(k,u.key)});A.remind&&(Mk(d,{recursive:!0}),$k(p,JSON.stringify({reminded:[...f,u.id]})),S=A.reason)}let T=l$(v,S);return T===null?null:{kind:"stop",reason:T}}var Fk=w(()=>{"use strict";Et();_r();we();Ln();Mn();Ji();de();Xe();Oo();tt();Ie();Lt();s(Lk,"decideLocally");s(t$,"decideDocDutyReminder");s(jt,"git");s(n$,"mergeBase");s(r$,"localDocFacts");s(o$,"workTreeFor");s(N8,"nestedCheckouts");s(D8,"boundWorktree");s(jk,"reminderStateDir");s(P8,"safeName");s(M8,"readReminded");s(Pp,"lessonStateDir");s(i$,"readOr");s(s$,"lessonFindingOf");s(Mp,"stampLessonAsked");s(a$,"writeLessonTeam");s(l$,"lessonThenDoc");s(c$,"readServerLessonCheck");s(u$,"readServerDocState");s(d$,"saidByCli");s($8,"sessionIdOf");s($p,"ownBoundObject");s(L8,"docDutyCore")});var y$={};Q(y$,{captureCore:()=>B8,capturedAtOf:()=>f$,decideCapture:()=>m$,episodeSource:()=>h$,lessonEpisodeReason:()=>g$});import{readFileSync as j8}from"node:fs";import{homedir as F8}from"node:os";import{join as H8}from"node:path";function f$(e,t){let n=e.guard_signals?.[t]?.captured_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}function m$(e){if(e.stopHookActive||!mr(e.policy.capture))return null;let t=i_(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:h_(t)}}function h$(e){return{kind:"episode",start:e.start,failures:e.failures.length,minutes:Math.max(1,Math.round((e.end-e.start)/6e4)),verbs:e.failures.map(t=>t.v??"?"),solvedBy:e.lastVerb}}function g$(e,t,n,r){if(t===null||!qf(n,r))return null;let o=h$(e),i=uc(o);return dc(i)?{reason:Fs(o,i),findingId:ai(o)}:null}function U8(e){try{return j8(H8(F8(),".maind",Hs,Us,Qr(e)),"utf8")}catch{return null}}async function B8(e,t){let n=Se();if(n.mode==="off"||!n.capture||!me(t,{kind:"stop"}))return null;let r=Ep(e);if(r===null||!_s(r))return null;let o=m$({events:await Ho(r),capturedAtMs:f$(await ue(),r),policy:await Ar(!1),stopHookActive:yd(e)});if(o===null)return null;let i=o.reason;try{let a=Z(),l=a===null?null:$p(e,a,be(e,t),r)?.object??null,c=g$(o.candidate,l,l?U8(l.id):null,Date.now());c!==null&&l!==null&&(Mp(l.id,l.key,c.findingId),i=c.reason)}catch{}return await Cr(r,{t:Date.now(),k:"prompt"}),await oe({event:"capture_prompt",session_id:r,detail:String(o.candidate.failures.length)}),{kind:"stop",reason:i}}var _$=w(()=>{"use strict";Dt();Et();Fk();Ie();de();ut();Zt();pn();Rl();ks();Fo();s(f$,"capturedAtOf");s(m$,"decideCapture");s(h$,"episodeSource");s(g$,"lessonEpisodeReason");s(U8,"teamCacheOf");s(B8,"captureCore")});var Uo={};Q(Uo,{CORE_HOOK_NAMES:()=>Hk,MULTI_HOOK_SUBCOMMAND:()=>hn,hooksFromArgv:()=>K8,mergeHookOutputs:()=>Sp,runHooks:()=>ve});import{homedir as G8}from"node:os";function K8(e){let t=new Set(e.filter(n=>!n.startsWith("-")));return Hk.filter(n=>t.has(n))}function Sp(e){let t=e.find(r=>r.kind==="deny");if(t!==void 0)return t;let n=e[0];if(n===void 0)return null;if(e.length===1)return n;if(n.kind==="text")return{kind:"text",event:"SessionStart",text:e.filter(o=>o.kind==="text").map(o=>o.text.replace(/\s+$/,"")).filter(o=>o.length>0).join(`
1064
+ `):null}function c$(e,t){if(!e)return null;try{let n=JSON.parse(e),o=(Array.isArray(n.resolved)?n.resolved:[]).find(i=>i?.key===t);return o===void 0||typeof o.lesson_check!="string"?null:o.lesson_check==="on"}catch{return null}}function u$(e,t){if(!e)return null;try{let n=JSON.parse(e),o=(Array.isArray(n.resolved)?n.resolved:[]).find(u=>u?.key===t);if(!o)return null;let i=o.doc_duty;if(i!=="off"&&i!=="remind"&&i!=="require")return null;let a=typeof o.take=="object"&&o.take!==null?o.take:null,l=a!==null&&a.state==="held"&&a.by_this_session===!1,c=o.status==="passed"||o.status==="canceled";return{docDuty:i,docMissing:o.doc_missing===!0,...l?{heldByOther:l}:{},...c?{finished:c}:{},...o.doc_in_review===!0?{inReview:!0}:{}}}catch{return null}}function d$(e,t=Date.now()){let n=Ft(jk(),cm,um(e)),r=null;try{r=Dp(n,"utf8")}catch{r=null}return dm(r,t)}function j8(e){for(let t of[e.session_id,e.conversation_id])if(typeof t=="string"&&t.trim())return t.trim();return null}function $p(e,t,n,r){let o=fn(Pt(e)||null,r),i=kt(nt(t),{hostPids:Fe(),cwd:n,selfId:o})?.snap;if(!i||i.announce_error)return null;let a=yr({branchObjectId:i.branch_object_id??null,boundObjects:i.bound_objects??null});return a.objectId===null||!a.key?null:{own:i,object:{id:a.objectId,key:a.key}}}async function F8(e,t){let n=j8(e),r=be(e,t),o=!me(t,{kind:"stop"}),i=yd(e);if(o||i||n===null)return null;let a=Z();if(a===null)return null;let l=$p(e,a,r,n);if(l===null)return null;let{own:c,object:u}=l,d=jk(),p=Ft(d,`${$8(n)}.json`),f=QM(p)?L8(p):[],m=o$(r,u.id),h=m===null?{hasWork:!1,locallySatisfied:!1}:r$(m,u.key),g=Lk({standsDown:o,stopHookActive:i,object:u,alreadyReminded:f.includes(u.id)||d$(u.id),ownTree:m!==null,...h}),_=null;try{_=m===null?null:s$(m,u.id)}catch{_=null}if(g&&_===null)return null;let b=ee(),k=b?await Qt("get_my_work_objects",{project_key:a,session_id:c.own_session_id,keys:[u.key]},{apiKey:b,deviceId:ke(),projectKey:a,bridgeVersion:K,timeoutMs:3e3}):null,v=null,S=null,x=c$(k,u.key);try{x!==null&&a$(u.id,x),_!==null&&x===!0&&(Mp(u.id,u.key,ai(_.source)),v=Fs(_.source,_.check))}catch{}if(!g){let A=t$({standsDown:o,stopHookActive:i,object:u,alreadyReminded:!1,ownTree:!0,...h,server:u$(k,u.key)});A.remind&&(Mk(d,{recursive:!0}),$k(p,JSON.stringify({reminded:[...f,u.id]})),S=A.reason)}let T=l$(v,S);return T===null?null:{kind:"stop",reason:T}}var Fk=w(()=>{"use strict";Et();_r();we();Ln();Mn();Ji();de();Xe();Oo();tt();Ie();Lt();s(Lk,"decideLocally");s(t$,"decideDocDutyReminder");s(jt,"git");s(n$,"mergeBase");s(r$,"localDocFacts");s(o$,"workTreeFor");s(P8,"nestedCheckouts");s(M8,"boundWorktree");s(jk,"reminderStateDir");s($8,"safeName");s(L8,"readReminded");s(Pp,"lessonStateDir");s(i$,"readOr");s(s$,"lessonFindingOf");s(Mp,"stampLessonAsked");s(a$,"writeLessonTeam");s(l$,"lessonThenDoc");s(c$,"readServerLessonCheck");s(u$,"readServerDocState");s(d$,"saidByCli");s(j8,"sessionIdOf");s($p,"ownBoundObject");s(F8,"docDutyCore")});var y$={};Q(y$,{captureCore:()=>K8,capturedAtOf:()=>f$,decideCapture:()=>m$,episodeSource:()=>h$,lessonEpisodeReason:()=>g$});import{readFileSync as H8}from"node:fs";import{homedir as U8}from"node:os";import{join as B8}from"node:path";function f$(e,t){let n=e.guard_signals?.[t]?.captured_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}function m$(e){if(e.stopHookActive||!mr(e.policy.capture))return null;let t=i_(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:h_(t)}}function h$(e){return{kind:"episode",start:e.start,failures:e.failures.length,minutes:Math.max(1,Math.round((e.end-e.start)/6e4)),verbs:e.failures.map(t=>t.v??"?"),solvedBy:e.lastVerb}}function g$(e,t,n,r){if(t===null||!qf(n,r))return null;let o=h$(e),i=uc(o);return dc(i)?{reason:Fs(o,i),findingId:ai(o)}:null}function G8(e){try{return H8(B8(U8(),".maind",Hs,Us,Qr(e)),"utf8")}catch{return null}}async function K8(e,t){let n=Se();if(n.mode==="off"||!n.capture||!me(t,{kind:"stop"}))return null;let r=Ep(e);if(r===null||!_s(r))return null;let o=m$({events:await Ho(r),capturedAtMs:f$(await ue(),r),policy:await Ar(!1),stopHookActive:yd(e)});if(o===null)return null;let i=o.reason;try{let a=Z(),l=a===null?null:$p(e,a,be(e,t),r)?.object??null,c=g$(o.candidate,l,l?G8(l.id):null,Date.now());c!==null&&l!==null&&(Mp(l.id,l.key,c.findingId),i=c.reason)}catch{}return await Cr(r,{t:Date.now(),k:"prompt"}),await oe({event:"capture_prompt",session_id:r,detail:String(o.candidate.failures.length)}),{kind:"stop",reason:i}}var _$=w(()=>{"use strict";Dt();Et();Fk();Ie();de();ut();Zt();pn();Rl();ks();Fo();s(f$,"capturedAtOf");s(m$,"decideCapture");s(h$,"episodeSource");s(g$,"lessonEpisodeReason");s(G8,"teamCacheOf");s(K8,"captureCore")});var Uo={};Q(Uo,{CORE_HOOK_NAMES:()=>Hk,MULTI_HOOK_SUBCOMMAND:()=>hn,hooksFromArgv:()=>V8,mergeHookOutputs:()=>Sp,runHooks:()=>ve});import{homedir as W8}from"node:os";function V8(e){let t=new Set(e.filter(n=>!n.startsWith("-")));return Hk.filter(n=>t.has(n))}function Sp(e){let t=e.find(r=>r.kind==="deny");if(t!==void 0)return t;let n=e[0];if(n===void 0)return null;if(e.length===1)return n;if(n.kind==="text")return{kind:"text",event:"SessionStart",text:e.filter(o=>o.kind==="text").map(o=>o.text.replace(/\s+$/,"")).filter(o=>o.length>0).join(`
1065
1065
 
1066
1066
  `)+`
1067
1067
  `};if(n.kind==="context"){let r=e.filter(o=>o.kind==="context"&&o.event===n.event);return{kind:"context",event:n.event,text:r.map(o=>o.text).join(`
1068
1068
 
1069
1069
  `)}}return n.kind==="stop"?{kind:"stop",reason:e.filter(o=>o.kind==="stop").map(o=>o.reason).join(`
1070
1070
 
1071
- `)}:n}async function W8(e){let t=b$.find(([n])=>n===e);return t===void 0?null:t[1]()}async function ve(e,t=process.argv.slice(2),n={}){try{let r=n.input??await je(),o=za(t),i=n.target??Pn(r,process.env,re,o),a=Hk.filter(d=>e.includes(d));if(i.host==="copilot"&&o!=="copilot"){let{copilotRunsHook:d}=await Promise.resolve().then(()=>(ds(),YN)),p=n.homeDir??G8();a=a.filter(f=>!d(p,f))}let l=[];for(let d of a)try{let p=await(n.core??W8)(d),f=p===null?null:await p(r,i);f!==null&&l.push(f)}catch{}let c=Sp(l),u=c===null?null:Co(i,c);u!==null?await(n.write??Ja)(u):PI(i)&&await(n.write??Ja)(`{}
1072
- `)}catch{}return 0}var b$,hn,Hk,Oe=w(()=>{"use strict";Ce();tt();Ie();b$=[["on-session-reminder",async()=>(await Promise.resolve().then(()=>(E_(),x_))).sessionReminderCore],["on-session-start",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).sessionStartCore],["on-session-briefing",async()=>(await Promise.resolve().then(()=>(Gb(),Bb))).sessionBriefingCore],["on-prompt-context",async()=>(await Promise.resolve().then(()=>(Tl(),El))).promptContextCore],["on-tool-use",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).toolUseCore],["on-file-write",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).fileWriteCore],["on-file-edit",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).fileEditCore],["on-repo-health",async()=>(await Promise.resolve().then(()=>(_l(),UD))).repoHealthCore],["on-shell-write",async()=>(await Promise.resolve().then(()=>(nk(),tk))).shellWriteCore],["on-read-context",async()=>(await Promise.resolve().then(()=>(Tl(),El))).readContextCore],["on-write-health",async()=>(await Promise.resolve().then(()=>(pp(),XD))).writeHealthCore],["guard-difficulty",async()=>(await Promise.resolve().then(()=>(ks(),sk))).difficultyCore],["guard-outcome",async()=>(await Promise.resolve().then(()=>(ks(),sk))).difficultyCore],["on-shell-changes",async()=>(await Promise.resolve().then(()=>(nk(),tk))).shellChangesCore],["on-plan-accepted",async()=>(await Promise.resolve().then(()=>(iM(),oM))).planAcceptedCore],["on-session-end",async()=>(await Promise.resolve().then(()=>(Dk(),Nk))).sessionEndCore],["on-index-refresh",async()=>(await Promise.resolve().then(()=>(Np(),Op))).indexRefreshCore],["on-doc-duty",async()=>(await Promise.resolve().then(()=>(Fk(),p$))).docDutyCore],["guard-capture",async()=>(await Promise.resolve().then(()=>(_$(),y$))).captureCore]],hn="on-hook",Hk=b$.map(([e])=>e);s(K8,"hooksFromArgv");s(Sp,"mergeHookOutputs");s(W8,"loadCore");s(ve,"runHooks")});import*as Or from"node:path";import*as v$ from"node:readline";function z8(e,t,n){let r=Or.relative(t,e),o=r!==""&&!r.startsWith("..")&&!Or.isAbsolute(r)?`~/${r.split(Or.sep).join("/")}`:e;return`hook(${n}):${o}`}function x$(e,t,n){let r=[];for(let o of[e,t]){let i=Ss(o)&&Ss(o.hooks)?o.hooks[n]:void 0;if(Array.isArray(i))for(let a of i){let l=Ss(a)&&Array.isArray(a.hooks)?a.hooks:[];for(let c of l)Ss(c)&&typeof c.command=="string"&&r.push(c.command)}}return r}function Ss(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Ol(e){let t=bo(e.presence.ctx),n=s(b=>z8(t,e.homeDir,b),"target"),r=s((b,k,v="skip",S)=>[{target:n(hn).replace(`hook(${hn})`,"hooks"),action:v,status:b,detail:k,...S?{manual:S}:{}}],"one"),{hooks:o,gaps:i}=jn("codex",e.pack??"core"),a=i.map(b=>({target:n(b.subcommand).replace(/^hook\(/,"gap("),action:"gap",status:"skipped",detail:`${b.extent==="none"?"not wired":"in part"} \u2014 ${b.reason}`}));if(e.skip)return r("skipped","--no-hook");if(e.skipCodex)return r("skipped","--skip-codex");if(!e.explicit&&!Te(Ci(e.presence.ctx),e.presence.probe))return r("skipped",Ci(e.presence.ctx).skipDetail);let l;try{l=await W(t)}catch(b){return r("failed",`read: ${w$(b)}`,"merge")}let c=l===null,u=Nt(l??"");if(!("value"in u))return r("failed",`${t} ${u.reason} \u2014 left untouched`,"merge",["Fix the file, then run install again."]);let d=u.value.features;if(Ss(d)&&d.hooks===!1)return r("skipped",`hooks are switched off in ${t} ([features] hooks = false) \u2014 left as it is`);if(Ss(d)&&d.codex_hooks===!1)return r("skipped",`hooks are switched off in ${t} ([features] codex_hooks = false) \u2014 left as it is`);let p=await J8(e.presence.ctx),f=e.launchFor??(b=>Ee({entryPath:se(),nodePath:process.execPath,extraArgs:[hn,S$,...b],isElectron:process.versions.electron!==void 0})),m=[],h=[];for(let b of o){let k=x$(u.value,p,b.event).find(v=>v.includes(b.subcommand));if(k!==void 0){let v=`Codex already runs maind ${b.subcommand}`;m.push({target:n(b.subcommand),action:"skip",status:"skipped",detail:It(k)?`${v}, but via \`npx\` \u2014 PATH decides which bridge that is`:v});continue}if(!e.full){if(!e.isInteractive){m.push({target:n(b.subcommand),action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"});continue}if(e.dryRun){m.push({target:n(b.subcommand),action:"merge",status:c?"would-create":"would-merge",detail:`${t} (would prompt for consent in real run)`});continue}if(!await(e.prompt??Y8)(e.out,`
1071
+ `)}:n}async function q8(e){let t=b$.find(([n])=>n===e);return t===void 0?null:t[1]()}async function ve(e,t=process.argv.slice(2),n={}){try{let r=n.input??await je(),o=za(t),i=n.target??Pn(r,process.env,re,o),a=Hk.filter(d=>e.includes(d));if(i.host==="copilot"&&o!=="copilot"){let{copilotRunsHook:d}=await Promise.resolve().then(()=>(ds(),YN)),p=n.homeDir??W8();a=a.filter(f=>!d(p,f))}let l=[];for(let d of a)try{let p=await(n.core??q8)(d),f=p===null?null:await p(r,i);f!==null&&l.push(f)}catch{}let c=Sp(l),u=c===null?null:Co(i,c);u!==null?await(n.write??Ja)(u):PI(i)&&await(n.write??Ja)(`{}
1072
+ `)}catch{}return 0}var b$,hn,Hk,Oe=w(()=>{"use strict";Ce();tt();Ie();b$=[["on-session-reminder",async()=>(await Promise.resolve().then(()=>(E_(),x_))).sessionReminderCore],["on-session-start",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).sessionStartCore],["on-session-briefing",async()=>(await Promise.resolve().then(()=>(Gb(),Bb))).sessionBriefingCore],["on-prompt-context",async()=>(await Promise.resolve().then(()=>(Tl(),El))).promptContextCore],["on-tool-use",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).toolUseCore],["on-file-write",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).fileWriteCore],["on-file-edit",async()=>(await Promise.resolve().then(()=>(Lt(),gs))).fileEditCore],["on-repo-health",async()=>(await Promise.resolve().then(()=>(_l(),UD))).repoHealthCore],["on-shell-write",async()=>(await Promise.resolve().then(()=>(nk(),tk))).shellWriteCore],["on-read-context",async()=>(await Promise.resolve().then(()=>(Tl(),El))).readContextCore],["on-write-health",async()=>(await Promise.resolve().then(()=>(pp(),XD))).writeHealthCore],["guard-difficulty",async()=>(await Promise.resolve().then(()=>(ks(),sk))).difficultyCore],["guard-outcome",async()=>(await Promise.resolve().then(()=>(ks(),sk))).difficultyCore],["on-shell-changes",async()=>(await Promise.resolve().then(()=>(nk(),tk))).shellChangesCore],["on-plan-accepted",async()=>(await Promise.resolve().then(()=>(iM(),oM))).planAcceptedCore],["on-session-end",async()=>(await Promise.resolve().then(()=>(Dk(),Nk))).sessionEndCore],["on-index-refresh",async()=>(await Promise.resolve().then(()=>(Np(),Op))).indexRefreshCore],["on-doc-duty",async()=>(await Promise.resolve().then(()=>(Fk(),p$))).docDutyCore],["guard-capture",async()=>(await Promise.resolve().then(()=>(_$(),y$))).captureCore]],hn="on-hook",Hk=b$.map(([e])=>e);s(V8,"hooksFromArgv");s(Sp,"mergeHookOutputs");s(q8,"loadCore");s(ve,"runHooks")});import*as Or from"node:path";import*as v$ from"node:readline";function Y8(e,t,n){let r=Or.relative(t,e),o=r!==""&&!r.startsWith("..")&&!Or.isAbsolute(r)?`~/${r.split(Or.sep).join("/")}`:e;return`hook(${n}):${o}`}function x$(e,t,n){let r=[];for(let o of[e,t]){let i=Ss(o)&&Ss(o.hooks)?o.hooks[n]:void 0;if(Array.isArray(i))for(let a of i){let l=Ss(a)&&Array.isArray(a.hooks)?a.hooks:[];for(let c of l)Ss(c)&&typeof c.command=="string"&&r.push(c.command)}}return r}function Ss(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Ol(e){let t=bo(e.presence.ctx),n=s(b=>Y8(t,e.homeDir,b),"target"),r=s((b,k,v="skip",S)=>[{target:n(hn).replace(`hook(${hn})`,"hooks"),action:v,status:b,detail:k,...S?{manual:S}:{}}],"one"),{hooks:o,gaps:i}=jn("codex",e.pack??"core"),a=i.map(b=>({target:n(b.subcommand).replace(/^hook\(/,"gap("),action:"gap",status:"skipped",detail:`${b.extent==="none"?"not wired":"in part"} \u2014 ${b.reason}`}));if(e.skip)return r("skipped","--no-hook");if(e.skipCodex)return r("skipped","--skip-codex");if(!e.explicit&&!Te(Ci(e.presence.ctx),e.presence.probe))return r("skipped",Ci(e.presence.ctx).skipDetail);let l;try{l=await W(t)}catch(b){return r("failed",`read: ${w$(b)}`,"merge")}let c=l===null,u=Nt(l??"");if(!("value"in u))return r("failed",`${t} ${u.reason} \u2014 left untouched`,"merge",["Fix the file, then run install again."]);let d=u.value.features;if(Ss(d)&&d.hooks===!1)return r("skipped",`hooks are switched off in ${t} ([features] hooks = false) \u2014 left as it is`);if(Ss(d)&&d.codex_hooks===!1)return r("skipped",`hooks are switched off in ${t} ([features] codex_hooks = false) \u2014 left as it is`);let p=await X8(e.presence.ctx),f=e.launchFor??(b=>Ee({entryPath:se(),nodePath:process.execPath,extraArgs:[hn,S$,...b],isElectron:process.versions.electron!==void 0})),m=[],h=[];for(let b of o){let k=x$(u.value,p,b.event).find(v=>v.includes(b.subcommand));if(k!==void 0){let v=`Codex already runs maind ${b.subcommand}`;m.push({target:n(b.subcommand),action:"skip",status:"skipped",detail:It(k)?`${v}, but via \`npx\` \u2014 PATH decides which bridge that is`:v});continue}if(!e.full){if(!e.isInteractive){m.push({target:n(b.subcommand),action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"});continue}if(e.dryRun){m.push({target:n(b.subcommand),action:"merge",status:c?"would-create":"would-merge",detail:`${t} (would prompt for consent in real run)`});continue}if(!await(e.prompt??Z8)(e.out,`
1073
1073
  Add Codex's ${b.label.replace(/ hook$/,"")} hook to ${t}?
1074
- ${as("codex",b)} ${q8}
1075
- [Y/n]: `)){m.push({target:n(b.subcommand),action:"skip",status:"skipped",detail:"user declined"});continue}}h.push(b)}if(h.length===0)return[...m,...a];let g=l??"";for(let{event:b,hooks:k}of is(h)){let v=at(f(k.map(x=>x.subcommand))),S=MC(g,{command:v,timeout:ss(k),...b==="SessionStart"?{additionalContextLimit:V8}:{}},v,{event:b,matcher:os("codex",k)});if(S.kind==="refuse")return[...m,...r("failed",`${t} ${S.reason} \u2014 left untouched`,"merge",S.manual),...a];if(S.kind==="off")return r("skipped",`hooks are switched off in ${t} ([features] ${S.key} = false) \u2014 left as it is`);S.kind==="write"&&(g=S.next)}let _=s((b,k)=>[...m,...h.map(v=>({target:n(v.subcommand),action:c?"write":"merge",status:b,detail:k})),...a],"done");if(e.dryRun)return _(c?"would-create":"would-merge",`${t} \u2014 ${k$}`);try{if(!await Au(t,l,g))return[...m,...r("failed",`${t} changed while install ran \u2014 left untouched; run install again`,"merge"),...a]}catch(b){return[...m,...r("failed",`write: ${w$(b)}`,"merge"),...a]}return _(c?"created":"merged",`${t} \u2014 ${k$}`)}function up(e,t){let n=e===null?null:Nt(e),r=n!==null&&"value"in n?n.value:null,o=null;try{o=t===null?null:JSON.parse(t)}catch{o=null}let{hooks:i,gaps:a}=jn("codex"),l=i.filter(c=>x$(r,o,c.event).some(u=>u.includes(c.subcommand))).map(c=>c.subcommand);return{wired:l,missing:i.map(c=>c.subcommand).filter(c=>!l.includes(c)),gaps:a.filter(c=>c.extent==="none").map(c=>c.subcommand)}}async function J8(e){try{let t=await W(Or.join(rr(e),"hooks.json"));return t===null?null:JSON.parse(t)}catch{return null}}function lD(e){return e.includes(`${hn} ${S$}`)||e.includes(ce)}async function Y8(e,t){e.write(t);let n=v$.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function w$(e){return e instanceof Error?e.message:String(e)}var S$,V8,q8,k$,ms=w(()=>{"use strict";Oe();tp();le();Ze();We();Ia();ir();Le();S$="--host=codex",V8=4e3,q8="Everything else in config.toml stays as it is, comments and layout included; `[features] hooks = true` is added if it is not set. Codex runs a new hook only after you trust it: open /hooks in Codex once.",k$="Codex runs them after you trust them once: /hooks in Codex";s(z8,"codexHookTarget");s(x$,"eventCommands");s(Ss,"isTable");s(Ol,"mergeCodexHooks");s(up,"codexHookWiring");s(J8,"hooksJson");s(lD,"isMaindCodexHookCommand");s(Y8,"promptYesNo");s(w$,"errMessage")});import*as T$ from"node:path";import*as A$ from"node:readline";async function Uk(e){if(e.skip)return null;let t=!1;try{let i=await W(bo(e.ctx)),a=await W(T$.join(rr(e.ctx),"hooks.json"));t=up(i,a).wired.includes("on-session-end")}catch{t=!1}if(!t)return null;let n=e.configPath??Re(),r={};try{let i=await W(n);if(i!==null&&i.trim().length>0){let a=JSON.parse(i);typeof a=="object"&&a!==null&&!Array.isArray(a)&&(r=a)}}catch{}if(typeof r.codex_session_analytics=="boolean")return E$(`already decided (${r.codex_session_analytics?"on":"off"}) in ${n}`);let o;if(e.full)o=!0;else if(e.isInteractive){if(e.dryRun)return{target:Nl,action:"merge",status:"would-merge",detail:`${n} (would prompt for consent in real run)`};o=await(e.promptFn??Z8)(e.out,X8)}else return E$("consent-required: Codex session analytics stay off \u2014 pass --full, or run install in a terminal to be asked");if(e.dryRun)return{target:Nl,action:"merge",status:"would-merge",detail:n};try{await G(n,JSON.stringify({...r,codex_session_analytics:o},null,2)+`
1076
- `,384)}catch(i){return{target:Nl,action:"merge",status:"failed",detail:`write: ${i instanceof Error?i.message:String(i)}`}}return{target:Nl,action:"merge",status:"merged",detail:o?`${n} \u2014 Codex session analytics on (off: codex_session_analytics=false)`:`${n} \u2014 Codex session analytics off`}}async function Z8(e,t){e.write(t);let n=A$.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var Nl,X8,E$,R$=w(()=>{"use strict";Ce();le();We();ms();Nl="config:codex_session_analytics",X8=`
1074
+ ${as("codex",b)} ${J8}
1075
+ [Y/n]: `)){m.push({target:n(b.subcommand),action:"skip",status:"skipped",detail:"user declined"});continue}}h.push(b)}if(h.length===0)return[...m,...a];let g=l??"";for(let{event:b,hooks:k}of is(h)){let v=at(f(k.map(x=>x.subcommand))),S=MC(g,{command:v,timeout:ss(k),...b==="SessionStart"?{additionalContextLimit:z8}:{}},v,{event:b,matcher:os("codex",k)});if(S.kind==="refuse")return[...m,...r("failed",`${t} ${S.reason} \u2014 left untouched`,"merge",S.manual),...a];if(S.kind==="off")return r("skipped",`hooks are switched off in ${t} ([features] ${S.key} = false) \u2014 left as it is`);S.kind==="write"&&(g=S.next)}let _=s((b,k)=>[...m,...h.map(v=>({target:n(v.subcommand),action:c?"write":"merge",status:b,detail:k})),...a],"done");if(e.dryRun)return _(c?"would-create":"would-merge",`${t} \u2014 ${k$}`);try{if(!await Au(t,l,g))return[...m,...r("failed",`${t} changed while install ran \u2014 left untouched; run install again`,"merge"),...a]}catch(b){return[...m,...r("failed",`write: ${w$(b)}`,"merge"),...a]}return _(c?"created":"merged",`${t} \u2014 ${k$}`)}function up(e,t){let n=e===null?null:Nt(e),r=n!==null&&"value"in n?n.value:null,o=null;try{o=t===null?null:JSON.parse(t)}catch{o=null}let{hooks:i,gaps:a}=jn("codex"),l=i.filter(c=>x$(r,o,c.event).some(u=>u.includes(c.subcommand))).map(c=>c.subcommand);return{wired:l,missing:i.map(c=>c.subcommand).filter(c=>!l.includes(c)),gaps:a.filter(c=>c.extent==="none").map(c=>c.subcommand)}}async function X8(e){try{let t=await W(Or.join(rr(e),"hooks.json"));return t===null?null:JSON.parse(t)}catch{return null}}function lD(e){return e.includes(`${hn} ${S$}`)||e.includes(ce)}async function Z8(e,t){e.write(t);let n=v$.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function w$(e){return e instanceof Error?e.message:String(e)}var S$,z8,J8,k$,ms=w(()=>{"use strict";Oe();tp();le();Ze();We();Ia();ir();Le();S$="--host=codex",z8=4e3,J8="Everything else in config.toml stays as it is, comments and layout included; `[features] hooks = true` is added if it is not set. Codex runs a new hook only after you trust it: open /hooks in Codex once.",k$="Codex runs them after you trust them once: /hooks in Codex";s(Y8,"codexHookTarget");s(x$,"eventCommands");s(Ss,"isTable");s(Ol,"mergeCodexHooks");s(up,"codexHookWiring");s(X8,"hooksJson");s(lD,"isMaindCodexHookCommand");s(Z8,"promptYesNo");s(w$,"errMessage")});import*as T$ from"node:path";import*as A$ from"node:readline";async function Uk(e){if(e.skip)return null;let t=!1;try{let i=await W(bo(e.ctx)),a=await W(T$.join(rr(e.ctx),"hooks.json"));t=up(i,a).wired.includes("on-session-end")}catch{t=!1}if(!t)return null;let n=e.configPath??Re(),r={};try{let i=await W(n);if(i!==null&&i.trim().length>0){let a=JSON.parse(i);typeof a=="object"&&a!==null&&!Array.isArray(a)&&(r=a)}}catch{}if(typeof r.codex_session_analytics=="boolean")return E$(`already decided (${r.codex_session_analytics?"on":"off"}) in ${n}`);let o;if(e.full)o=!0;else if(e.isInteractive){if(e.dryRun)return{target:Nl,action:"merge",status:"would-merge",detail:`${n} (would prompt for consent in real run)`};o=await(e.promptFn??eZ)(e.out,Q8)}else return E$("consent-required: Codex session analytics stay off \u2014 pass --full, or run install in a terminal to be asked");if(e.dryRun)return{target:Nl,action:"merge",status:"would-merge",detail:n};try{await G(n,JSON.stringify({...r,codex_session_analytics:o},null,2)+`
1076
+ `,384)}catch(i){return{target:Nl,action:"merge",status:"failed",detail:`write: ${i instanceof Error?i.message:String(i)}`}}return{target:Nl,action:"merge",status:"merged",detail:o?`${n} \u2014 Codex session analytics on (off: codex_session_analytics=false)`:`${n} \u2014 Codex session analytics off`}}async function eZ(e,t){e.write(t);let n=A$.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(o=>{n.question("",i=>o(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}var Nl,Q8,E$,R$=w(()=>{"use strict";Ce();le();We();ms();Nl="config:codex_session_analytics",Q8=`
1077
1077
  Send Codex session analytics from Codex's Stop hook?
1078
1078
  With this ON, the Stop hook in Codex also reads the session's ROLLOUT
1079
1079
  (<Codex home>/sessions/\u2026/rollout-\u2026.jsonl) on this machine and sends what the
@@ -1086,23 +1086,23 @@ measuring them. The server stores it only with your Tier-3 consent
1086
1086
  (https://app.maind.dev/consent). Without it, Codex sessions reach MAIND only
1087
1087
  through \`maind sessions backfill\`.
1088
1088
  Off later: {"codex_session_analytics": false} in the bridge config.
1089
- [Y/n]: `,E$=s(e=>({target:Nl,action:"skip",status:"skipped",detail:e}),"skipped");s(Uk,"applyCodexAnalyticsConsent");s(Z8,"promptYesNoDefaultYes")});async function C$(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let o=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),i={};try{i=await o.json()}catch{}return o.ok?i.status!=="exchanged"||typeof i.api_key!="string"||!i.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:i.api_key,plan:i.plan??"unknown"}:{ok:!1,reason:i.error??`http_${o.status}`}}catch(o){return o instanceof Error&&o.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:o instanceof Error?o.message:String(o)}}finally{clearTimeout(r)}}var I$=w(()=>{"use strict";s(C$,"exchangeOneClickToken")});async function D$(e){let t="browser-pair";if(e.token!==null)try{let i=Q8(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(ya(),yo(i),{apiKey:i,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(i){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:O$(i)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let i=yu(e.bridgeVersion),a=await C$({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:DR(),clientMeta:{...i}});if(a.ok)return ya(),yo(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,N$(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
1090
- `)}let r=n===null?"":` (after exchange failure: ${n})`,o=ee();if(o!==null)return{apiKey:o,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let i=await Ai(e.bridgeVersion,N$(e));return i===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:i.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${i.plan})${r}`}}}catch(i){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:O$(i)}}}}function Q8(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}function O$(e){return e instanceof Error?e.message:String(e)}function N$(e){return e.out??process.stdout}var P$=w(()=>{"use strict";Bg();we();I$();s(D$,"pairOrUseToken");s(Q8,"validateTokenShape");s(O$,"errMessage");s(N$,"out")});async function M$(e){if(!e.enabled||e.apiKey===null)return;let t=Ei(eZ),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:rZ(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:nZ(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,o=setTimeout(()=>r.abort(),tZ);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(o)}}function nZ(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}function rZ(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}var eZ,tZ,$$=w(()=>{"use strict";Ti();eZ="install-completed",tZ=3e3;s(M$,"postInstallTelemetry");s(nZ,"countStatuses");s(rZ,"parseNodeMajor")});var K$={};Q(K$,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>B$,AGENTS_MD_REFRESH_INTERVAL_MS:()=>H$,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>U$,AGENTS_MD_REFRESH_STATE_FILE:()=>F$,gitToplevel:()=>Lp,isSet:()=>Dl,isWithin:()=>G$,loadProjectConventions:()=>Bo,realpathOrResolve:()=>Gk,refreshAgentsMdConventions:()=>Bk,refreshAgentsMdForSession:()=>gZ});import{execFileSync as oZ}from"node:child_process";import{createHash as iZ}from"node:crypto";import{mkdir as sZ,readFile as aZ,realpath as lZ,rename as cZ,writeFile as uZ}from"node:fs/promises";import{dirname as dZ,isAbsolute as pZ,join as j$,relative as fZ,resolve as mZ}from"node:path";async function Bo(e,t,n){if(e===null)return null;let r=n.clientFamily??"mcp-bridge",o=await Zi(t,e,{client:HO(r),fetcher:n.allowFetch?i=>Xi({...i,clientFamily:r}):async()=>null,...n.cacheFile!==void 0?{cacheFile:n.cacheFile}:{},...n.repoDir?{stack:Rn(n.repoDir)}:{}});return o.text===null||o.via==="stale-cache"&&o.projectKey!==void 0&&o.projectKey!==t?null:o.conventions??null}async function Bk(e,t){let n=t.err??(r=>process.stderr.write(`${r}
1091
- `));try{let r=t.env??process.env;if(yZ(r))return{status:"skipped",reason:"opt-out"};let o=t.cwd??process.cwd(),i=(t.gitToplevel??Lp)(o);if(i===null)return Kk(r)&&n(`maind: AGENTS.md team block skipped \u2014 ${o} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Gk(i),l=[];for(let S of await(t.findRoots??Eu)(o)){let x=await Gk(S);G$(x,a)&&!l.includes(x)&&l.push(x)}l.includes(a)||l.push(a);let c=null,u=null;for(let S of l){let x=j$(S,"AGENTS.md"),T=await W(x);if(T!==null&&GC(T)){c=x,u=T;break}}if(c===null||u===null)return Kk(r)&&n(`maind: AGENTS.md team block skipped \u2014 no AGENTS.md with a team conventions block between the working directory and ${a} (install --team writes one; the bridge never writes above the repository root)`),{status:"skipped",reason:"no-team-block"};let d=t.nowMs??Date.now(),p=t.stateFile??F$,f=await bZ(p),m=_Z(c),h=f.roots[m]?.checked_at;if(typeof h=="string"&&!Number.isNaN(Date.parse(h))&&d-Date.parse(h)<H$)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((S,x)=>Bo(x,S,{allowFetch:!0,clientFamily:e??void 0,repoDir:i})))(t.projectKey,t.apiKey);if(_===null||_.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=Uu(_,{date:new Date(d).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??K},{team:!0}),k=Bu(u,b,void 0,{replaceOnly:!0});if(k.outcome==="damaged")return n(`maind: AGENTS.md team block not refreshed \u2014 begin marker without end marker in ${c}; remove the <!-- maind:conventions --> lines and run install --team again`),{status:"skipped",reason:"damaged"};if(k.outcome==="no-header"||k.outcome==="inserted")return{status:"skipped",reason:"no-team-block"};if(k.changed&&await G(c,k.next),await kZ(p,f,m,d),!k.changed)return{status:"unchanged",file:c};let v=BC(b);return n(`maind: AGENTS.md team conventions block refreshed (${v} conventions)`),{status:"refreshed",file:c,conventions:v}}catch(r){let o=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md team block not refreshed \u2014 ${o}`),{status:"failed",error:o}}}async function gZ(e,t){let n=await Bk(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-team-block"||t.listRoots===void 0)return n;let r=t.env??process.env,o=t.err??(c=>process.stderr.write(`${c}
1092
- `)),i;try{i=await t.listRoots()}catch{i=null}if(i===null||i.length===0)return Kk(r)&&o("maind: AGENTS.md team block skipped \u2014 the working directory gave no repository with a team block, "+(i===null?"and the client offers no workspace roots (no MCP roots capability, or no answer)":"and the client lists no workspace roots")),n;let a=t.cwd??process.cwd(),l=n;for(let c of i){if(c===a)continue;let u=await Bk(e,{...t,cwd:c,projectKey:(t.projectKeyFor??Ke)(c)??t.projectKey});L$(u)>L$(l)&&(l=u)}return l}function L$(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function Lp(e){try{let t=oZ("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function G$(e,t){let n=fZ(t,e);return n===""||!n.startsWith("..")&&!pZ(n)}async function Gk(e){try{return await lZ(e)}catch{return mZ(e)}}function yZ(e){return Dl(e[U$])}function Kk(e){return Dl(e[B$])}function Dl(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function _Z(e){return iZ("sha256").update(e).digest("hex")}async function bZ(e){let t={version:1,roots:{}};try{let n=JSON.parse(await aZ(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[o,i]of Object.entries(n.roots))i&&typeof i.checked_at=="string"&&(r[o]={checked_at:i.checked_at});return{version:1,roots:r}}catch{return t}}async function kZ(e,t,n,r){let o={};for(let[a,l]of Object.entries(t.roots)){let c=Date.parse(l.checked_at);!Number.isNaN(c)&&r-c<hZ&&(o[a]=l)}o[n]={checked_at:new Date(r).toISOString()},await sZ(dZ(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;await uZ(i,JSON.stringify({version:1,roots:o},null,2),{mode:384}),await cZ(i,e)}var F$,H$,U$,B$,hZ,jp=w(()=>{"use strict";Ln();Po();Me();Je();Pi();le();Yg();de();Xe();F$=j$(he,"agents-md-refresh.json"),H$=12*60*60*1e3,U$="MAIND_NO_AGENTS_MD_REFRESH",B$="MAIND_DEBUG",hZ=30*24*60*60*1e3;s(Bo,"loadProjectConventions");s(Bk,"refreshAgentsMdConventions");s(gZ,"refreshAgentsMdForSession");s(L$,"rank");s(Lp,"gitToplevel");s(G$,"isWithin");s(Gk,"realpathOrResolve");s(yZ,"isOptedOut");s(Kk,"isDebug");s(Dl,"isSet");s(_Z,"fileKey");s(bZ,"readState");s(kZ,"writeState")});var zk={};Q(zk,{REFRESH_RULES_USAGE:()=>Fp,RULES_REFRESH_INTERVAL_MS:()=>W$,RULES_REFRESH_OPT_OUT_ENV:()=>Wk,RULES_REFRESH_STATE_FILE:()=>Vk,recordRulesCheck:()=>Up,refreshRulesForSession:()=>MZ,refreshUserRules:()=>qk,repoDisplayName:()=>V$,repoIdentity:()=>xs,runRefreshRules:()=>$Z});import{execFileSync as wZ}from"node:child_process";import{createHash as vZ}from"node:crypto";import{existsSync as SZ,statSync as xZ}from"node:fs";import{mkdir as EZ,readFile as TZ,rename as AZ,writeFile as RZ}from"node:fs/promises";import{homedir as CZ}from"node:os";import{basename as IZ,dirname as OZ,join as NZ,resolve as DZ}from"node:path";function xs(e){let t=Lp(e);if(t===null)return{root:null,name:null,projectKey:null,key:"none"};let n=null;try{n=wZ("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||null}catch{n=null}let r=n===null?null:nr(n);return{root:t,name:V$(n,t),projectKey:r,key:r??Kg(`path:${t}`)}}function V$(e,t){let n=e===null?null:Wg(e);if(n!==null){let r=n.split("/").filter(o=>o.length>0);if(r.length>=3)return r.slice(-2).join("/");if(r.length>=1)return r[r.length-1]}return IZ(t)}async function qk(e,t={}){let n=t.env??process.env;if(Dl(n[Wk]))return{outcome:"opted_out",repo:null,files:[]};try{let r=t.homeDir??CZ(),o=(t.identity??xs)(e),i=t.channels??$o(qt({projectRoot:e,homeDir:r,platform:process.platform,env:n}),fe),a=t.only===void 0?i:i.filter(k=>t.only?.includes(k.id)),l=[];for(let k of a){let v=await W(k.path);v!==null&&fs(v)&&l.push({channel:k,raw:v})}if(l.length===0)return{outcome:"no_channels",repo:o.name,files:[]};let c=t.nowMs??Date.now(),u=t.stateFile??Vk,d=await q$(u),p=l.filter(({channel:k,raw:v})=>{if(t.force===!0)return!0;let S=d.files[Hp(k.path)];if(S===void 0||S.repo!==o.key)return!0;let x=Date.parse(S.checked_at);return Number.isNaN(x)||c-x>=W$?!0:S.content!==hl(v)});if(p.length===0)return{outcome:"throttled",repo:o.name,files:[]};let f=(t.apiKey??ee)();if(f===null)return{outcome:"failed",repo:o.name,files:[],error:"not paired \u2014 run `maind-mcp-bridge --reauth`"};let h=await(t.loadConventions??((k,v)=>Bo(v,k,{allowFetch:!0,clientFamily:t.clientFamily??"mcp-bridge",repoDir:o.root})))(o.projectKey,f);if(h===null||h.trim().length===0)return{outcome:"failed",repo:o.name,files:[],error:`no conventions for ${o.name??"this directory"} \u2014 the MAIND server was not reachable and nothing is cached for it`};let g=[],_=[],b=0;for(let{channel:k,raw:v}of p){let S=vb(k,{repo:o.name,conventions:h},{nowMs:c,bridgeVersion:t.bridgeVersion??K});try{if(ps(v)===ps(S)){b++,d.files[Hp(k.path)]={repo:o.key,checked_at:new Date(c).toISOString(),content:hl(v)};continue}let x=await W(k.path);if(x===null||!fs(x))continue;await G(k.path,S),g.push(k.path),d.files[Hp(k.path)]={repo:o.key,checked_at:new Date(c).toISOString(),content:hl(S)}}catch(x){_.push(`${k.path}: ${x instanceof Error?x.message:String(x)}`)}}return await z$(u,d,c),g.length>0?{outcome:"refreshed",repo:o.name,files:g}:_.length>0?{outcome:"failed",repo:o.name,files:[],error:_.join("; ")}:{outcome:b>0?"unchanged":"no_channels",repo:o.name,files:[]}}catch(r){return{outcome:"failed",repo:null,files:[],error:r instanceof Error?r.message:String(r)}}}async function Up(e,t,n,r={}){try{let o=r.nowMs??Date.now(),i=r.stateFile??Vk,a=await q$(i);a.files[Hp(e)]={repo:n,checked_at:new Date(o).toISOString(),content:hl(t)},await z$(i,a,o)}catch{}}async function MZ(e,t={}){let n=oD(e);if(n===null)return null;let r=t.err??(o=>process.stderr.write(`${o}
1093
- `));try{let o=t.identity??xs,i=null,a=t.cwd??process.cwd();if(o(a).root!==null)i=a;else if(t.listRoots!==void 0){let c=null;try{c=await t.listRoots()}catch{c=null}i=(c??[]).find(u=>o(u).root!==null)??null}if(i===null)return null;let l=await qk(i,{...t,only:[n],clientFamily:e??void 0});return l.outcome==="refreshed"?r(`maind: user-level rules refreshed with the conventions for ${l.repo??"this directory"} (${l.files.join(", ")})`):l.outcome==="failed"&&r(`maind: user-level rules not refreshed \u2014 ${l.error??"unknown error"}`),l}catch{return null}}async function $Z(e,t={}){let n=t.out??(u=>void process.stdout.write(u)),r=t.errOut??(u=>void process.stderr.write(u)),o=null,i=!1,a=!1;for(let u=0;u<e.length;u++){let d=e[u];if(d==="--json")i=!0;else if(d==="--force")a=!0;else{if(d==="-h"||d==="--help")return n(Fp),0;if(d==="--project-root"||d.startsWith("--project-root=")){let p=d.includes("=")?d.slice(d.indexOf("=")+1):e[u+1];if(d.includes("=")||u++,p===void 0||p.length===0||!d.includes("=")&&p.startsWith("--"))return r(`refresh-rules: --project-root requires a directory
1089
+ [Y/n]: `,E$=s(e=>({target:Nl,action:"skip",status:"skipped",detail:e}),"skipped");s(Uk,"applyCodexAnalyticsConsent");s(eZ,"promptYesNoDefaultYes")});async function C$(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let o=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),i={};try{i=await o.json()}catch{}return o.ok?i.status!=="exchanged"||typeof i.api_key!="string"||!i.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:i.api_key,plan:i.plan??"unknown"}:{ok:!1,reason:i.error??`http_${o.status}`}}catch(o){return o instanceof Error&&o.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:o instanceof Error?o.message:String(o)}}finally{clearTimeout(r)}}var I$=w(()=>{"use strict";s(C$,"exchangeOneClickToken")});async function D$(e){let t="browser-pair";if(e.token!==null)try{let i=tZ(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(ya(),yo(i),{apiKey:i,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(i){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:O$(i)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let i=yu(e.bridgeVersion),a=await C$({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:DR(),clientMeta:{...i}});if(a.ok)return ya(),yo(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,N$(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
1090
+ `)}let r=n===null?"":` (after exchange failure: ${n})`,o=ee();if(o!==null)return{apiKey:o,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let i=await Ai(e.bridgeVersion,N$(e));return i===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:i.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${i.plan})${r}`}}}catch(i){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:O$(i)}}}}function tZ(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}function O$(e){return e instanceof Error?e.message:String(e)}function N$(e){return e.out??process.stdout}var P$=w(()=>{"use strict";Bg();we();I$();s(D$,"pairOrUseToken");s(tZ,"validateTokenShape");s(O$,"errMessage");s(N$,"out")});async function M$(e){if(!e.enabled||e.apiKey===null)return;let t=Ei(nZ),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:iZ(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:oZ(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,o=setTimeout(()=>r.abort(),rZ);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(o)}}function oZ(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}function iZ(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}var nZ,rZ,$$=w(()=>{"use strict";Ti();nZ="install-completed",rZ=3e3;s(M$,"postInstallTelemetry");s(oZ,"countStatuses");s(iZ,"parseNodeMajor")});var K$={};Q(K$,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>B$,AGENTS_MD_REFRESH_INTERVAL_MS:()=>H$,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>U$,AGENTS_MD_REFRESH_STATE_FILE:()=>F$,gitToplevel:()=>Lp,isSet:()=>Dl,isWithin:()=>G$,loadProjectConventions:()=>Bo,realpathOrResolve:()=>Gk,refreshAgentsMdConventions:()=>Bk,refreshAgentsMdForSession:()=>_Z});import{execFileSync as sZ}from"node:child_process";import{createHash as aZ}from"node:crypto";import{mkdir as lZ,readFile as cZ,realpath as uZ,rename as dZ,writeFile as pZ}from"node:fs/promises";import{dirname as fZ,isAbsolute as mZ,join as j$,relative as hZ,resolve as gZ}from"node:path";async function Bo(e,t,n){if(e===null)return null;let r=n.clientFamily??"mcp-bridge",o=await Zi(t,e,{client:HO(r),fetcher:n.allowFetch?i=>Xi({...i,clientFamily:r}):async()=>null,...n.cacheFile!==void 0?{cacheFile:n.cacheFile}:{},...n.repoDir?{stack:Rn(n.repoDir)}:{}});return o.text===null||o.via==="stale-cache"&&o.projectKey!==void 0&&o.projectKey!==t?null:o.conventions??null}async function Bk(e,t){let n=t.err??(r=>process.stderr.write(`${r}
1091
+ `));try{let r=t.env??process.env;if(bZ(r))return{status:"skipped",reason:"opt-out"};let o=t.cwd??process.cwd(),i=(t.gitToplevel??Lp)(o);if(i===null)return Kk(r)&&n(`maind: AGENTS.md team block skipped \u2014 ${o} is not inside a git repository`),{status:"skipped",reason:"no-root"};let a=await Gk(i),l=[];for(let S of await(t.findRoots??Eu)(o)){let x=await Gk(S);G$(x,a)&&!l.includes(x)&&l.push(x)}l.includes(a)||l.push(a);let c=null,u=null;for(let S of l){let x=j$(S,"AGENTS.md"),T=await W(x);if(T!==null&&GC(T)){c=x,u=T;break}}if(c===null||u===null)return Kk(r)&&n(`maind: AGENTS.md team block skipped \u2014 no AGENTS.md with a team conventions block between the working directory and ${a} (install --team writes one; the bridge never writes above the repository root)`),{status:"skipped",reason:"no-team-block"};let d=t.nowMs??Date.now(),p=t.stateFile??F$,f=await wZ(p),m=kZ(c),h=f.roots[m]?.checked_at;if(typeof h=="string"&&!Number.isNaN(Date.parse(h))&&d-Date.parse(h)<H$)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let _=await(t.loadConventions??((S,x)=>Bo(x,S,{allowFetch:!0,clientFamily:e??void 0,repoDir:i})))(t.projectKey,t.apiKey);if(_===null||_.trim().length===0)return{status:"skipped",reason:"no-conventions"};let b=Uu(_,{date:new Date(d).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??K},{team:!0}),k=Bu(u,b,void 0,{replaceOnly:!0});if(k.outcome==="damaged")return n(`maind: AGENTS.md team block not refreshed \u2014 begin marker without end marker in ${c}; remove the <!-- maind:conventions --> lines and run install --team again`),{status:"skipped",reason:"damaged"};if(k.outcome==="no-header"||k.outcome==="inserted")return{status:"skipped",reason:"no-team-block"};if(k.changed&&await G(c,k.next),await vZ(p,f,m,d),!k.changed)return{status:"unchanged",file:c};let v=BC(b);return n(`maind: AGENTS.md team conventions block refreshed (${v} conventions)`),{status:"refreshed",file:c,conventions:v}}catch(r){let o=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md team block not refreshed \u2014 ${o}`),{status:"failed",error:o}}}async function _Z(e,t){let n=await Bk(e,t);if(n.status!=="skipped"||n.reason!=="no-root"&&n.reason!=="no-team-block"||t.listRoots===void 0)return n;let r=t.env??process.env,o=t.err??(c=>process.stderr.write(`${c}
1092
+ `)),i;try{i=await t.listRoots()}catch{i=null}if(i===null||i.length===0)return Kk(r)&&o("maind: AGENTS.md team block skipped \u2014 the working directory gave no repository with a team block, "+(i===null?"and the client offers no workspace roots (no MCP roots capability, or no answer)":"and the client lists no workspace roots")),n;let a=t.cwd??process.cwd(),l=n;for(let c of i){if(c===a)continue;let u=await Bk(e,{...t,cwd:c,projectKey:(t.projectKeyFor??Ke)(c)??t.projectKey});L$(u)>L$(l)&&(l=u)}return l}function L$(e){switch(e.status){case"refreshed":return 3;case"unchanged":return 2;case"failed":return 1;default:return 0}}function Lp(e){try{let t=sZ("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function G$(e,t){let n=hZ(t,e);return n===""||!n.startsWith("..")&&!mZ(n)}async function Gk(e){try{return await uZ(e)}catch{return gZ(e)}}function bZ(e){return Dl(e[U$])}function Kk(e){return Dl(e[B$])}function Dl(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function kZ(e){return aZ("sha256").update(e).digest("hex")}async function wZ(e){let t={version:1,roots:{}};try{let n=JSON.parse(await cZ(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[o,i]of Object.entries(n.roots))i&&typeof i.checked_at=="string"&&(r[o]={checked_at:i.checked_at});return{version:1,roots:r}}catch{return t}}async function vZ(e,t,n,r){let o={};for(let[a,l]of Object.entries(t.roots)){let c=Date.parse(l.checked_at);!Number.isNaN(c)&&r-c<yZ&&(o[a]=l)}o[n]={checked_at:new Date(r).toISOString()},await lZ(fZ(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;await pZ(i,JSON.stringify({version:1,roots:o},null,2),{mode:384}),await dZ(i,e)}var F$,H$,U$,B$,yZ,jp=w(()=>{"use strict";Ln();Po();Me();Je();Pi();le();Yg();de();Xe();F$=j$(he,"agents-md-refresh.json"),H$=12*60*60*1e3,U$="MAIND_NO_AGENTS_MD_REFRESH",B$="MAIND_DEBUG",yZ=30*24*60*60*1e3;s(Bo,"loadProjectConventions");s(Bk,"refreshAgentsMdConventions");s(_Z,"refreshAgentsMdForSession");s(L$,"rank");s(Lp,"gitToplevel");s(G$,"isWithin");s(Gk,"realpathOrResolve");s(bZ,"isOptedOut");s(Kk,"isDebug");s(Dl,"isSet");s(kZ,"fileKey");s(wZ,"readState");s(vZ,"writeState")});var zk={};Q(zk,{REFRESH_RULES_USAGE:()=>Fp,RULES_REFRESH_INTERVAL_MS:()=>W$,RULES_REFRESH_OPT_OUT_ENV:()=>Wk,RULES_REFRESH_STATE_FILE:()=>Vk,recordRulesCheck:()=>Up,refreshRulesForSession:()=>LZ,refreshUserRules:()=>qk,repoDisplayName:()=>V$,repoIdentity:()=>xs,runRefreshRules:()=>jZ});import{execFileSync as SZ}from"node:child_process";import{createHash as xZ}from"node:crypto";import{existsSync as EZ,statSync as TZ}from"node:fs";import{mkdir as AZ,readFile as RZ,rename as CZ,writeFile as IZ}from"node:fs/promises";import{homedir as OZ}from"node:os";import{basename as NZ,dirname as DZ,join as PZ,resolve as MZ}from"node:path";function xs(e){let t=Lp(e);if(t===null)return{root:null,name:null,projectKey:null,key:"none"};let n=null;try{n=SZ("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||null}catch{n=null}let r=n===null?null:nr(n);return{root:t,name:V$(n,t),projectKey:r,key:r??Kg(`path:${t}`)}}function V$(e,t){let n=e===null?null:Wg(e);if(n!==null){let r=n.split("/").filter(o=>o.length>0);if(r.length>=3)return r.slice(-2).join("/");if(r.length>=1)return r[r.length-1]}return NZ(t)}async function qk(e,t={}){let n=t.env??process.env;if(Dl(n[Wk]))return{outcome:"opted_out",repo:null,files:[]};try{let r=t.homeDir??OZ(),o=(t.identity??xs)(e),i=t.channels??$o(qt({projectRoot:e,homeDir:r,platform:process.platform,env:n}),fe),a=t.only===void 0?i:i.filter(k=>t.only?.includes(k.id)),l=[];for(let k of a){let v=await W(k.path);v!==null&&fs(v)&&l.push({channel:k,raw:v})}if(l.length===0)return{outcome:"no_channels",repo:o.name,files:[]};let c=t.nowMs??Date.now(),u=t.stateFile??Vk,d=await q$(u),p=l.filter(({channel:k,raw:v})=>{if(t.force===!0)return!0;let S=d.files[Hp(k.path)];if(S===void 0||S.repo!==o.key)return!0;let x=Date.parse(S.checked_at);return Number.isNaN(x)||c-x>=W$?!0:S.content!==hl(v)});if(p.length===0)return{outcome:"throttled",repo:o.name,files:[]};let f=(t.apiKey??ee)();if(f===null)return{outcome:"failed",repo:o.name,files:[],error:"not paired \u2014 run `maind-mcp-bridge --reauth`"};let h=await(t.loadConventions??((k,v)=>Bo(v,k,{allowFetch:!0,clientFamily:t.clientFamily??"mcp-bridge",repoDir:o.root})))(o.projectKey,f);if(h===null||h.trim().length===0)return{outcome:"failed",repo:o.name,files:[],error:`no conventions for ${o.name??"this directory"} \u2014 the MAIND server was not reachable and nothing is cached for it`};let g=[],_=[],b=0;for(let{channel:k,raw:v}of p){let S=vb(k,{repo:o.name,conventions:h},{nowMs:c,bridgeVersion:t.bridgeVersion??K});try{if(ps(v)===ps(S)){b++,d.files[Hp(k.path)]={repo:o.key,checked_at:new Date(c).toISOString(),content:hl(v)};continue}let x=await W(k.path);if(x===null||!fs(x))continue;await G(k.path,S),g.push(k.path),d.files[Hp(k.path)]={repo:o.key,checked_at:new Date(c).toISOString(),content:hl(S)}}catch(x){_.push(`${k.path}: ${x instanceof Error?x.message:String(x)}`)}}return await z$(u,d,c),g.length>0?{outcome:"refreshed",repo:o.name,files:g}:_.length>0?{outcome:"failed",repo:o.name,files:[],error:_.join("; ")}:{outcome:b>0?"unchanged":"no_channels",repo:o.name,files:[]}}catch(r){return{outcome:"failed",repo:null,files:[],error:r instanceof Error?r.message:String(r)}}}async function Up(e,t,n,r={}){try{let o=r.nowMs??Date.now(),i=r.stateFile??Vk,a=await q$(i);a.files[Hp(e)]={repo:n,checked_at:new Date(o).toISOString(),content:hl(t)},await z$(i,a,o)}catch{}}async function LZ(e,t={}){let n=oD(e);if(n===null)return null;let r=t.err??(o=>process.stderr.write(`${o}
1093
+ `));try{let o=t.identity??xs,i=null,a=t.cwd??process.cwd();if(o(a).root!==null)i=a;else if(t.listRoots!==void 0){let c=null;try{c=await t.listRoots()}catch{c=null}i=(c??[]).find(u=>o(u).root!==null)??null}if(i===null)return null;let l=await qk(i,{...t,only:[n],clientFamily:e??void 0});return l.outcome==="refreshed"?r(`maind: user-level rules refreshed with the conventions for ${l.repo??"this directory"} (${l.files.join(", ")})`):l.outcome==="failed"&&r(`maind: user-level rules not refreshed \u2014 ${l.error??"unknown error"}`),l}catch{return null}}async function jZ(e,t={}){let n=t.out??(u=>void process.stdout.write(u)),r=t.errOut??(u=>void process.stderr.write(u)),o=null,i=!1,a=!1;for(let u=0;u<e.length;u++){let d=e[u];if(d==="--json")i=!0;else if(d==="--force")a=!0;else{if(d==="-h"||d==="--help")return n(Fp),0;if(d==="--project-root"||d.startsWith("--project-root=")){let p=d.includes("=")?d.slice(d.indexOf("=")+1):e[u+1];if(d.includes("=")||u++,p===void 0||p.length===0||!d.includes("=")&&p.startsWith("--"))return r(`refresh-rules: --project-root requires a directory
1094
1094
  ${Fp}`),2;o=p}else return r(`refresh-rules: unknown argument ${d}
1095
- ${Fp}`),2}}let l=DZ(t.cwd??process.cwd(),o??".");if(!jZ(l))return r(`refresh-rules: ${l} is not a directory
1095
+ ${Fp}`),2}}let l=MZ(t.cwd??process.cwd(),o??".");if(!HZ(l))return r(`refresh-rules: ${l} is not a directory
1096
1096
  `),2;let c=await qk(l,{...t,force:a});return n(i?JSON.stringify({outcome:c.outcome,repo:c.repo,files:c.files})+`
1097
- `:LZ(c)+`
1097
+ `:FZ(c)+`
1098
1098
  `),c.outcome==="failed"&&i&&r(`refresh-rules: ${c.error??"failed"}
1099
- `),c.outcome==="failed"?1:0}function LZ(e){let t=e.repo??"this directory (no repository)";switch(e.outcome){case"refreshed":return`maind: refreshed ${e.files.length} rule file(s) with the conventions for ${t}: ${e.files.join(", ")}`;case"unchanged":return`maind: rule files already carry the current conventions for ${t}`;case"throttled":return`maind: rule files were checked for ${t} less than 12 h ago (--force to check now)`;case"no_channels":return"maind: no user-level rule files to refresh (install sets them up with your consent)";case"opted_out":return`maind: ${Wk} is set \u2014 nothing refreshed`;case"failed":return`maind: rule files not refreshed \u2014 ${e.error??"unknown error"}`}}function jZ(e){try{return SZ(e)&&xZ(e).isDirectory()}catch{return!1}}function Hp(e){return vZ("sha256").update(e).digest("hex")}async function q$(e){let t={version:1,files:{}};try{let n=JSON.parse(await TZ(e,"utf8"));if(!n||typeof n.files!="object"||n.files===null)return t;let r={};for(let[o,i]of Object.entries(n.files))i&&typeof i.repo=="string"&&typeof i.checked_at=="string"&&typeof i.content=="string"&&(r[o]={repo:i.repo,checked_at:i.checked_at,content:i.content});return{version:1,files:r}}catch{return t}}async function z$(e,t,n){let r={};for(let[i,a]of Object.entries(t.files)){let l=Date.parse(a.checked_at);!Number.isNaN(l)&&n-l<PZ&&(r[i]=a)}await EZ(OZ(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await RZ(o,JSON.stringify({version:1,files:r},null,2),{mode:384}),await AZ(o,e)}var Wk,Vk,W$,PZ,Fp,Bp=w(()=>{"use strict";jp();we();Je();le();We();ap();de();Xe();Wk="MAIND_NO_RULES_REFRESH",Vk=NZ(he,"rules-refresh.json"),W$=12*60*60*1e3,PZ=30*24*60*60*1e3;s(xs,"repoIdentity");s(V$,"repoDisplayName");s(qk,"refreshUserRules");s(Up,"recordRulesCheck");s(MZ,"refreshRulesForSession");Fp=["Usage: maind-mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]","","Refreshes the user-level rule files that exist (GitHub Copilot, Cline, Continue)","with the conventions of the repository at <dir> (default: the current directory;","its git root). Never creates a file. At most once per 12 h per repository and","only when the content changed; --force skips the 12 h. MAIND_NO_RULES_REFRESH=1","makes it a no-op. Exit 0 refreshed/unchanged/throttled/no_channels/opted_out,","2 usage error, 1 failure. --json prints {outcome, repo, files}.",""].join(`
1100
- `);s($Z,"runRefreshRules");s(LZ,"humanLine");s(jZ,"isDirectory");s(Hp,"fileKey");s(q$,"readState");s(z$,"writeState")});import*as J$ from"node:os";async function Y$(e){let t=Date.now(),n;try{n=eC(e)}catch(R){if(R instanceof Ot)return process.stderr.write(`error: ${R.message}
1099
+ `),c.outcome==="failed"?1:0}function FZ(e){let t=e.repo??"this directory (no repository)";switch(e.outcome){case"refreshed":return`maind: refreshed ${e.files.length} rule file(s) with the conventions for ${t}: ${e.files.join(", ")}`;case"unchanged":return`maind: rule files already carry the current conventions for ${t}`;case"throttled":return`maind: rule files were checked for ${t} less than 12 h ago (--force to check now)`;case"no_channels":return"maind: no user-level rule files to refresh (install sets them up with your consent)";case"opted_out":return`maind: ${Wk} is set \u2014 nothing refreshed`;case"failed":return`maind: rule files not refreshed \u2014 ${e.error??"unknown error"}`}}function HZ(e){try{return EZ(e)&&TZ(e).isDirectory()}catch{return!1}}function Hp(e){return xZ("sha256").update(e).digest("hex")}async function q$(e){let t={version:1,files:{}};try{let n=JSON.parse(await RZ(e,"utf8"));if(!n||typeof n.files!="object"||n.files===null)return t;let r={};for(let[o,i]of Object.entries(n.files))i&&typeof i.repo=="string"&&typeof i.checked_at=="string"&&typeof i.content=="string"&&(r[o]={repo:i.repo,checked_at:i.checked_at,content:i.content});return{version:1,files:r}}catch{return t}}async function z$(e,t,n){let r={};for(let[i,a]of Object.entries(t.files)){let l=Date.parse(a.checked_at);!Number.isNaN(l)&&n-l<$Z&&(r[i]=a)}await AZ(DZ(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.tmp`;await IZ(o,JSON.stringify({version:1,files:r},null,2),{mode:384}),await CZ(o,e)}var Wk,Vk,W$,$Z,Fp,Bp=w(()=>{"use strict";jp();we();Je();le();We();ap();de();Xe();Wk="MAIND_NO_RULES_REFRESH",Vk=PZ(he,"rules-refresh.json"),W$=12*60*60*1e3,$Z=30*24*60*60*1e3;s(xs,"repoIdentity");s(V$,"repoDisplayName");s(qk,"refreshUserRules");s(Up,"recordRulesCheck");s(LZ,"refreshRulesForSession");Fp=["Usage: maind-mcp-bridge refresh-rules [--project-root <dir>] [--force] [--json]","","Refreshes the user-level rule files that exist (GitHub Copilot, Cline, Continue)","with the conventions of the repository at <dir> (default: the current directory;","its git root). Never creates a file. At most once per 12 h per repository and","only when the content changed; --force skips the 12 h. MAIND_NO_RULES_REFRESH=1","makes it a no-op. Exit 0 refreshed/unchanged/throttled/no_channels/opted_out,","2 usage error, 1 failure. --json prints {outcome, repo, files}.",""].join(`
1100
+ `);s(jZ,"runRefreshRules");s(FZ,"humanLine");s(HZ,"isDirectory");s(Hp,"fileKey");s(q$,"readState");s(z$,"writeState")});import*as J$ from"node:os";async function Y$(e){let t=Date.now(),n;try{n=eC(e)}catch(R){if(R instanceof Ot)return process.stderr.write(`error: ${R.message}
1101
1101
  `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw R}if(n.help)return tC(),0;for(let R of n.notices)process.stdout.write(`${R}
1102
1102
  `);let o=!!process.stdin.isTTY&&!n.nonInteractive,i=J$.homedir();if(i.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
1103
- `),2;if(n.hooksOnly)return WZ({homeDir:i,isInteractive:o,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:qt({projectRoot:i,homeDir:i,platform:process.platform,env:process.env}),probe:fe,noRules:n.noRules,cwd:process.cwd()});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let R=await Eu(process.cwd());if(R.length===0)a=await sC(process.cwd());else if(R.length===1||!n.team)a=R[0];else{let P=await lC(R,o);if(P===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick the one --team writes into.
1103
+ `),2;if(n.hooksOnly)return qZ({homeDir:i,isInteractive:o,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout},{ctx:qt({projectRoot:i,homeDir:i,platform:process.platform,env:process.env}),probe:fe,noRules:n.noRules,cwd:process.cwd()});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let R=await Eu(process.cwd());if(R.length===0)a=await sC(process.cwd());else if(R.length===1||!n.team)a=R[0];else{let P=await lC(R,o);if(P===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick the one --team writes into.
1104
1104
  `);for(let D of R)process.stderr.write(` candidate: ${D}
1105
- `);return 2}a=P}}let l=new va,c=(process.env.MAIND_MCP_URL??"").trim()||FZ;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1105
+ `);return 2}a=P}}let l=new va,c=(process.env.MAIND_MCP_URL??"").trim()||UZ;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1106
1106
  `),process.stdout.write(`maind install \u2014 project root: ${a}${n.team?" (--team writes AGENTS.md and .mcp.json here)":" (nothing is written here without --team)"}
1107
1107
  `),process.stdout.write(` \u2014 mcp endpoint: ${c}
1108
1108
 
@@ -1111,27 +1111,27 @@ ${Fp}`),2}}let l=DZ(t.cwd??process.cwd(),o??".");if(!jZ(l))return r(`refresh-rul
1111
1111
  `),l.print(process.stdout),2;let p=await D$({bridgeVersion:K,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(l.add(p.result),p.result.status==="failed")return process.stderr.write(`
1112
1112
  pairing failed: ${p.result.detail??"unknown"}
1113
1113
  Skipping remaining steps.
1114
- `),l.print(process.stdout),2;let f=_t(bt(i,process.env,process.platform));for(let R of d){if(R.scope==="project"&&!n.team){l.add({target:R.key,action:"skip",status:"skipped",detail:f.enabled?"a repository file \u2014 install --team writes it (ADR-364); the maind plugin carries the server for you":"a repository file \u2014 install --team writes it (ADR-364); ~/.claude.json carries the server for you"});continue}if(R.key==="claude-code-user"&&f.enabled){l.add({target:R.key,action:"skip",status:"skipped",detail:cI(f)});continue}let P=pC({target:R,explicitFamily:n.client,probe:fe});if(P!==null){l.add(P);continue}let D=UR({mcpUrl:c,clientFamily:R.clientFamilyEnv}),E;R.kind==="json"?E=await gC(R,D,n.dryRun):E=await jC(R,D,n.dryRun),l.add(E)}let m=xs(a),h=Z$(()=>Bo(p.apiKey,m.projectKey,{allowFetch:!n.dryRun,clientFamily:"mcp-bridge",repoDir:m.root}));l.add(await _y(i,n.dryRun)),n.team?l.add(await XC({projectRoot:a,conventions:h,dryRun:n.dryRun})):l.add({target:HZ,action:"skip",status:"skipped",detail:BZ});let g={homeDir:i,isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},_=await X$(g,f);for(let R of _)l.add(R);let b=eI(a,_);b!==null&&l.add(b),l.add(await Vy({isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout})),l.add(await o0({isInteractive:o,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout})),l.add(await a0({isInteractive:o,explicitFlag:n.agentActivity,dryRun:n.dryRun,out:process.stdout}));let k=d.some(R=>R.clientFamilyEnv==="cursor");if(k){let R=await Yy({...g,explicit:n.client==="cursor",presence:{ctx:u,probe:fe}});for(let P of R)l.add(P)}if(n.client===null||n.client==="codex"){let R=await Ol({...g,skipCodex:n.skipCodex,explicit:n.client==="codex",presence:{ctx:u,probe:fe}});for(let D of R)l.add(D);let P=await Uk({...g,ctx:u});P!==null&&l.add(P)}if(n.client===null||n.client==="copilot"){let R=await us({...g,explicit:n.client==="copilot",presence:{ctx:u,probe:fe}});for(let P of R)l.add(P)}if(n.client===null||n.client==="gemini-cli"){let R=await ml({...g,explicit:n.client==="gemini-cli",presence:{ctx:u,probe:fe}});for(let P of R)l.add(P)}let v=$o(u,fe).filter(R=>n.client===null||R.family===n.client);if(v.length>0){let R=await Sb({homeDir:i,isInteractive:o,full:n.full,skip:n.noRules,dryRun:n.dryRun,out:process.stdout,explicitFamily:n.client,probe:fe,content:s(async()=>({repo:m.name,conventions:await h()}),"content"),onChecked:s((P,D)=>Up(P,D,m.key),"onChecked")},v);for(let P of R)l.add(P)}!n.team&&k&&(n.client==="cursor"||Te(Cn(u),fe))&&l.add({target:UZ,action:"advise",status:"skipped",detail:GZ});let S=Qd();S.ok||l.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${S.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await M$({enabled:n.telemetry||n.full,installerVersion:K,summary:l.summary(),steps:l.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),l.print(process.stdout);let x=l.exitCode(),T=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
1114
+ `),l.print(process.stdout),2;let f=_t(bt(i,process.env,process.platform));for(let R of d){if(R.scope==="project"&&!n.team){l.add({target:R.key,action:"skip",status:"skipped",detail:f.enabled?"a repository file \u2014 install --team writes it (ADR-364); the maind plugin carries the server for you":"a repository file \u2014 install --team writes it (ADR-364); ~/.claude.json carries the server for you"});continue}if(R.key==="claude-code-user"&&f.enabled){l.add({target:R.key,action:"skip",status:"skipped",detail:cI(f)});continue}let P=pC({target:R,explicitFamily:n.client,probe:fe});if(P!==null){l.add(P);continue}let D=UR({mcpUrl:c,clientFamily:R.clientFamilyEnv}),E;R.kind==="json"?E=await gC(R,D,n.dryRun):E=await jC(R,D,n.dryRun),l.add(E)}let m=xs(a),h=Z$(()=>Bo(p.apiKey,m.projectKey,{allowFetch:!n.dryRun,clientFamily:"mcp-bridge",repoDir:m.root}));l.add(await _y(i,n.dryRun)),n.team?l.add(await XC({projectRoot:a,conventions:h,dryRun:n.dryRun})):l.add({target:BZ,action:"skip",status:"skipped",detail:KZ});let g={homeDir:i,isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout},_=await X$(g,f);for(let R of _)l.add(R);let b=eI(a,_);b!==null&&l.add(b),l.add(await Vy({isInteractive:o,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout})),l.add(await o0({isInteractive:o,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout})),l.add(await a0({isInteractive:o,explicitFlag:n.agentActivity,dryRun:n.dryRun,out:process.stdout}));let k=d.some(R=>R.clientFamilyEnv==="cursor");if(k){let R=await Yy({...g,explicit:n.client==="cursor",presence:{ctx:u,probe:fe}});for(let P of R)l.add(P)}if(n.client===null||n.client==="codex"){let R=await Ol({...g,skipCodex:n.skipCodex,explicit:n.client==="codex",presence:{ctx:u,probe:fe}});for(let D of R)l.add(D);let P=await Uk({...g,ctx:u});P!==null&&l.add(P)}if(n.client===null||n.client==="copilot"){let R=await us({...g,explicit:n.client==="copilot",presence:{ctx:u,probe:fe}});for(let P of R)l.add(P)}if(n.client===null||n.client==="gemini-cli"){let R=await ml({...g,explicit:n.client==="gemini-cli",presence:{ctx:u,probe:fe}});for(let P of R)l.add(P)}let v=$o(u,fe).filter(R=>n.client===null||R.family===n.client);if(v.length>0){let R=await Sb({homeDir:i,isInteractive:o,full:n.full,skip:n.noRules,dryRun:n.dryRun,out:process.stdout,explicitFamily:n.client,probe:fe,content:s(async()=>({repo:m.name,conventions:await h()}),"content"),onChecked:s((P,D)=>Up(P,D,m.key),"onChecked")},v);for(let P of R)l.add(P)}!n.team&&k&&(n.client==="cursor"||Te(Cn(u),fe))&&l.add({target:GZ,action:"advise",status:"skipped",detail:WZ});let S=Qd();S.ok||l.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${S.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await M$({enabled:n.telemetry||n.full,installerVersion:K,summary:l.summary(),steps:l.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),l.print(process.stdout);let x=l.exitCode(),T=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
1115
1115
  DRY RUN finished in ${T}s. No files were modified. Re-run without --dry-run to apply.
1116
1116
  `):process.stdout.write(`
1117
1117
  Finished in ${T}s. Restart your MCP client so it picks up the new server entry.
1118
1118
  `);let A=Ee({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),L=A.fallbackReason===null?`${at(A)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${L}
1119
1119
  `),x===1&&process.stdout.write(`Note: some steps were skipped or failed \u2014 review the table above. The MCP setup is usable as long as 'browser-pair' and at least one JSON/TOML target succeeded.
1120
- `),x}async function X$(e,t){if(t.enabled&&!e.skip)return[{target:Tb,action:"skip",status:"skipped",detail:cd(t)}];let n=await n0(e);return e.dryRun||await QC($e,n),n}function Z$(e){let t=null;return()=>t??=e()}async function Ab(e,t){let n=[];n.push(await _y(e.homeDir,e.dryRun)),n.push(...await Yy({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(...await Ol({...e,skipCodex:!1,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let r=await Uk({...e,ctx:t.ctx});r!==null&&n.push(r),n.push(...await us({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(...await ml({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let o=(t.identity??xs)(t.cwd),i=(t.apiKey??KZ)(),a=Z$(()=>Bo(i,o.projectKey,{allowFetch:!e.dryRun,clientFamily:"mcp-bridge",repoDir:o.root}));return n.push(...await Sb({...e,skip:t.noRules,explicitFamily:null,probe:t.probe,content:s(async()=>({repo:o.name,conventions:await a()}),"content"),onChecked:s((l,c)=>Up(l,c,o.key),"onChecked")},$o(t.ctx,t.probe))),n}function KZ(){try{return ee()}catch{return null}}async function WZ(e,t){let n=new va;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1120
+ `),x}async function X$(e,t){if(t.enabled&&!e.skip)return[{target:Tb,action:"skip",status:"skipped",detail:cd(t)}];let n=await n0(e);return e.dryRun||await QC($e,n),n}function Z$(e){let t=null;return()=>t??=e()}async function Ab(e,t){let n=[];n.push(await _y(e.homeDir,e.dryRun)),n.push(...await Yy({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(...await Ol({...e,skipCodex:!1,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let r=await Uk({...e,ctx:t.ctx});r!==null&&n.push(r),n.push(...await us({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}})),n.push(...await ml({...e,explicit:!1,presence:{ctx:t.ctx,probe:t.probe}}));let o=(t.identity??xs)(t.cwd),i=(t.apiKey??VZ)(),a=Z$(()=>Bo(i,o.projectKey,{allowFetch:!e.dryRun,clientFamily:"mcp-bridge",repoDir:o.root}));return n.push(...await Sb({...e,skip:t.noRules,explicitFamily:null,probe:t.probe,content:s(async()=>({repo:o.name,conventions:await a()}),"content"),onChecked:s((l,c)=>Up(l,c,o.key),"onChecked")},$o(t.ctx,t.probe))),n}function VZ(){try{return ee()}catch{return null}}async function qZ(e,t){let n=new va;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1121
1121
  `),e.out.write(`maind install --hooks-only \u2014 the user-level channels: Claude Code hooks in ~/.claude/settings.json; Cursor's, Codex's, Copilot's and Gemini CLI's hooks and the Copilot, Cline and Continue rule files where those clients are installed
1122
1122
  `);let r=_t(bt(e.homeDir,process.env,process.platform));for(let o of await X$(e,r))n.add(o);n.add(await Vy({isInteractive:e.isInteractive,full:e.full,skip:e.skip,dryRun:e.dryRun,out:e.out}));for(let o of await Ab(e,t))n.add(o);return n.print(e.out),e.out.write(e.dryRun?`
1123
1123
  DRY RUN finished. No files were modified.
1124
1124
  `:`
1125
1125
  Claude Code reads hooks when a session starts; Cursor reloads ~/.cursor/hooks.json by itself; Codex asks you to trust a new hook once (/hooks); VS Code picks up ~/.copilot/hooks by itself, the Copilot CLI at its next start; Gemini CLI reads ~/.gemini/settings.json at its next start.
1126
- `),n.exitCode()}var FZ,HZ,UZ,BZ,GZ,Tb,Rb=w(()=>{"use strict";Xe();nC();rC();Yg();We();Ze();le();ir();yC();FC();JC();ZC();Ku();ky();Le();i0();l0();Z0();tI();iI();Ui();R$();ms();ds();sp();ap();P$();$$();xr();jp();we();Bp();FZ="https://mcp.maind.dev/mcp",HZ="repository",UZ="team-option",BZ="nothing written into the repository (ADR-364) \u2014 install --team writes the AGENTS.md conventions block and the project .mcp.json",GZ="Cursor can drop the context of its sessionStart hook in a race Cursor confirms \u2014 for teams that work mostly in Cursor, install --team puts the conventions into the repository's AGENTS.md, which Cursor reads reliably";s(Y$,"runInstall");Tb="hooks:~/.claude/settings.json";s(X$,"claudeCodeHooks");s(Z$,"memo");s(Ab,"setUpUserChannels");s(KZ,"safeApiKey");s(WZ,"runHooksOnly")});function Yp(e=process.env,t=re()){let n=(e[Es]??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?{enabled:!0,source:"env"}:n==="off"||n==="0"||n==="false"?{enabled:!1,source:"env"}:typeof t?.agent_activity=="boolean"?{enabled:t.agent_activity,source:"config"}:{enabled:!1,source:"default"}}async function wL(e,t=Re()){let n={};try{let r=await W(t);if(r!==null&&r.trim().length>0){let o=JSON.parse(r);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}await G(t,JSON.stringify({...n,agent_activity:e},null,2)+`
1127
- `,384)}var Es,rw=w(()=>{"use strict";Ce();le();Es="MAIND_AGENT_ACTIVITY";s(Yp,"resolveAgentActivity");s(wL,"writeAgentActivity")});var WL={};Q(WL,{CURSOR_BRIEFING_MARKER:()=>ww,CURSOR_DELIVERY_LOG:()=>jL,CURSOR_UNAVAILABLE_TEXT:()=>HL,appendDelivery:()=>GL,cursorProjectDir:()=>FL,deliverCursorSessionStart:()=>BL,formatCursorBriefing:()=>UL,runOnCursorSessionStart:()=>AQ});import{appendFile as _Q,mkdir as bQ,readFile as kQ,stat as wQ,writeFile as vQ}from"node:fs/promises";import{dirname as SQ,join as xQ}from"node:path";function FL(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let o=r.find(i=>typeof i=="string"&&i.length>0);if(o)return o}return null}function UL(e,t,n){let o=`${ww}${n?" + project conventions":""}, delivered by the bridge's sessionStart hook (ADR-359)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`;return Wi(o,n,e)}async function BL(e,t={}){let n=t.write??KL,r=t.env??process.env,o=(t.apiKey??ee)();if(o===null)return await n(`{}
1126
+ `),n.exitCode()}var UZ,BZ,GZ,KZ,WZ,Tb,Rb=w(()=>{"use strict";Xe();nC();rC();Yg();We();Ze();le();ir();yC();FC();JC();ZC();Ku();ky();Le();i0();l0();Z0();tI();iI();Ui();R$();ms();ds();sp();ap();P$();$$();xr();jp();we();Bp();UZ="https://mcp.maind.dev/mcp",BZ="repository",GZ="team-option",KZ="nothing written into the repository (ADR-364) \u2014 install --team writes the AGENTS.md conventions block and the project .mcp.json",WZ="Cursor can drop the context of its sessionStart hook in a race Cursor confirms \u2014 for teams that work mostly in Cursor, install --team puts the conventions into the repository's AGENTS.md, which Cursor reads reliably";s(Y$,"runInstall");Tb="hooks:~/.claude/settings.json";s(X$,"claudeCodeHooks");s(Z$,"memo");s(Ab,"setUpUserChannels");s(VZ,"safeApiKey");s(qZ,"runHooksOnly")});function Yp(e=process.env,t=re()){let n=(e[Es]??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?{enabled:!0,source:"env"}:n==="off"||n==="0"||n==="false"?{enabled:!1,source:"env"}:typeof t?.agent_activity=="boolean"?{enabled:t.agent_activity,source:"config"}:{enabled:!1,source:"default"}}async function wL(e,t=Re()){let n={};try{let r=await W(t);if(r!==null&&r.trim().length>0){let o=JSON.parse(r);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}await G(t,JSON.stringify({...n,agent_activity:e},null,2)+`
1127
+ `,384)}var Es,rw=w(()=>{"use strict";Ce();le();Es="MAIND_AGENT_ACTIVITY";s(Yp,"resolveAgentActivity");s(wL,"writeAgentActivity")});var WL={};Q(WL,{CURSOR_BRIEFING_MARKER:()=>ww,CURSOR_DELIVERY_LOG:()=>jL,CURSOR_UNAVAILABLE_TEXT:()=>HL,appendDelivery:()=>GL,cursorProjectDir:()=>FL,deliverCursorSessionStart:()=>BL,formatCursorBriefing:()=>UL,runOnCursorSessionStart:()=>CQ});import{appendFile as kQ,mkdir as wQ,readFile as vQ,stat as SQ,writeFile as xQ}from"node:fs/promises";import{dirname as EQ,join as TQ}from"node:path";function FL(e,t){let n=t.CURSOR_PROJECT_DIR?.trim();if(n)return n;let r=e.workspace_roots;if(Array.isArray(r)){let o=r.find(i=>typeof i=="string"&&i.length>0);if(o)return o}return null}function UL(e,t,n){let o=`${ww}${n?" + project conventions":""}, delivered by the bridge's sessionStart hook (ADR-359)${t==="stale-cache"?" \u2014 served from local cache, server unreachable":""} \u2014 the session-start get_session_briefing consultation is satisfied by this block:`;return Wi(o,n,e)}async function BL(e,t={}){let n=t.write??KL,r=t.env??process.env,o=(t.apiKey??ee)();if(o===null)return await n(`{}
1128
1128
  `),0;let i=FL(e,r),a=i===null?null:(t.projectKeyFor??Ke)(i),l=await Zi(a,o,{client:"cursor",fetcher:s(p=>Xi({...p,clientFamily:"cursor"}),"fetcher"),...i!==null?{stack:Rn(i)}:{},...i!==null?{nestedProjectKeys:(t.nestedKeysFor??_d)(i,a)}:{},...t.inject}),c,u,d=!0;if(l.text===null)c=HL,u="none";else{let p=UL(l.text,l.via,l.conventions??null);c=p.text.trimEnd(),u=l.via,d=p.complete}return await n(JSON.stringify({additional_context:c})+`
1129
- `),await GL(t.logFile??jL,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Cs(e.conversation_id)??Cs(e.session_id),transcript_path:Cs(e.transcript_path)??Cs(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Cs(e.cursor_version)??Cs(r.CURSOR_VERSION),chars:l.text===null?0:c.length,via:u,complete:d}),0}async function AQ(){try{return await BL(await je())}catch{try{await KL(`{}
1130
- `)}catch{}return 0}}async function GL(e,t){try{if(await bQ(SQ(e),{recursive:!0,mode:448}),await _Q(e,JSON.stringify(t)+`
1131
- `,{mode:384}),(await wQ(e)).size>EQ){let n=(await kQ(e,"utf8")).split(`
1132
- `).filter(r=>r.trim().length>0);await vQ(e,n.slice(-TQ).join(`
1129
+ `),await GL(t.logFile??jL,{ts:new Date(t.nowMs??Date.now()).toISOString(),conversation_id:Cs(e.conversation_id)??Cs(e.session_id),transcript_path:Cs(e.transcript_path)??Cs(r.CURSOR_TRANSCRIPT_PATH),cursor_version:Cs(e.cursor_version)??Cs(r.CURSOR_VERSION),chars:l.text===null?0:c.length,via:u,complete:d}),0}async function CQ(){try{return await BL(await je())}catch{try{await KL(`{}
1130
+ `)}catch{}return 0}}async function GL(e,t){try{if(await wQ(EQ(e),{recursive:!0,mode:448}),await kQ(e,JSON.stringify(t)+`
1131
+ `,{mode:384}),(await SQ(e)).size>AQ){let n=(await vQ(e,"utf8")).split(`
1132
+ `).filter(r=>r.trim().length>0);await xQ(e,n.slice(-RQ).join(`
1133
1133
  `)+`
1134
- `,{mode:384})}}catch{}}function KL(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var ww,jL,EQ,TQ,Cs,HL,VL=w(()=>{"use strict";we();Po();Ln();Dd();de();Me();tt();ut();Za();ww="[maind] Cursor session briefing",jL=xQ(et,"cursor","deliveries.jsonl"),EQ=512*1024,TQ=2e3,Cs=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(FL,"cursorProjectDir");HL=`${ww} unavailable \u2014 the maind server could not be reached and there is no local copy yet. Call get_session_briefing once the maind tools respond.`;s(UL,"formatCursorBriefing");s(BL,"deliverCursorSessionStart");s(AQ,"runOnCursorSessionStart");s(GL,"appendDelivery");s(KL,"writeStdout")});function RQ(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let o=e[++n];if(o!=="warn"&&o!=="block")return null;t.mode=o;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function qL(e,t,n=process.stdout){let r=RQ(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
1134
+ `,{mode:384})}}catch{}}function KL(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}var ww,jL,AQ,RQ,Cs,HL,VL=w(()=>{"use strict";we();Po();Ln();Dd();de();Me();tt();ut();Za();ww="[maind] Cursor session briefing",jL=TQ(et,"cursor","deliveries.jsonl"),AQ=512*1024,RQ=2e3,Cs=s(e=>typeof e=="string"&&e.length>0?e:null,"str");s(FL,"cursorProjectDir");HL=`${ww} unavailable \u2014 the maind server could not be reached and there is no local copy yet. Call get_session_briefing once the maind tools respond.`;s(UL,"formatCursorBriefing");s(BL,"deliverCursorSessionStart");s(CQ,"runOnCursorSessionStart");s(GL,"appendDelivery");s(KL,"writeStdout")});function IQ(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let o=e[++n];if(o!=="warn"&&o!=="block")return null;t.mode=o;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function qL(e,t,n=process.stdout){let r=IQ(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
1135
1135
  `),1;let o={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},i=[];for(let d of cr)i.push(await Da(o,d));let a=qt({projectRoot:process.cwd(),homeDir:t,platform:process.platform,env:process.env,bridgeEntry:se()}),l={...o,pack:"guard",explicit:!1,presence:{ctx:a,probe:fe}};i.push(...await Ol({...l,skipCodex:!1})),i.push(...await us(l)),i.push(...await ml(l));for(let d of i)n.write(` ${d.status.padEnd(12)} ${d.target}${d.detail?` \u2014 ${d.detail}`:""}
1136
1136
  `);let c=i.some(d=>d.detail==="user declined"),u=i.some(d=>d.status==="failed");return r.dryRun?(n.write(`
1137
1137
  [dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
@@ -1142,7 +1142,7 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
1142
1142
  check: maind-mcp-bridge guard status
1143
1143
  Takes effect for NEW sessions (hooks are read at session start; Codex asks you to trust a new hook once in /hooks).
1144
1144
  `),c&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
1145
- `),u?1:0)}var zL=w(()=>{"use strict";le();Ze();We();ms();ds();sp();Le();Ku();Zt();s(RQ,"parseGuardInstallFlags");s(qL,"runGuardInstall")});import{existsSync as CQ}from"node:fs";import{mkdir as IQ,readFile as OQ,rename as NQ,writeFile as DQ}from"node:fs/promises";import{join as JL}from"node:path";function XL(e){return JL(YL,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function Is(e){try{let t=XL(e);if(!CQ(t))return{};let n=JSON.parse(await OQ(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Mr(e,t){await IQ(YL,{recursive:!0,mode:448});let n=XL(e),r=`${n}.${process.pid}.tmp`,o={...t,pending:(t.pending??[]).slice(-PQ),updated_at:new Date().toISOString()};await DQ(r,JSON.stringify(o,null,2),{mode:384}),await NQ(r,n)}function rf(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}var YL,PQ,vw=w(()=>{"use strict";Je();YL=JL(he,"consult"),PQ=20;s(XL,"consultFile");s(Is,"loadConsultState");s(Mr,"saveConsultState");s(rf,"msOf")});var ej={};Q(ej,{runGuard:()=>FQ});import{existsSync as MQ,readFileSync as $Q}from"node:fs";import{homedir as QL}from"node:os";import{join as LQ}from"node:path";async function FQ(e){let t=e[0],n=e.slice(1);switch(t){case"install":return qL(n,QL());case"status":return UQ();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
1145
+ `),u?1:0)}var zL=w(()=>{"use strict";le();Ze();We();ms();ds();sp();Le();Ku();Zt();s(IQ,"parseGuardInstallFlags");s(qL,"runGuardInstall")});import{existsSync as OQ}from"node:fs";import{mkdir as NQ,readFile as DQ,rename as PQ,writeFile as MQ}from"node:fs/promises";import{join as JL}from"node:path";function XL(e){return JL(YL,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function Is(e){try{let t=XL(e);if(!OQ(t))return{};let n=JSON.parse(await DQ(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Mr(e,t){await NQ(YL,{recursive:!0,mode:448});let n=XL(e),r=`${n}.${process.pid}.tmp`,o={...t,pending:(t.pending??[]).slice(-$Q),updated_at:new Date().toISOString()};await MQ(r,JSON.stringify(o,null,2),{mode:384}),await PQ(r,n)}function rf(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}var YL,$Q,vw=w(()=>{"use strict";Je();YL=JL(he,"consult"),$Q=20;s(XL,"consultFile");s(Is,"loadConsultState");s(Mr,"saveConsultState");s(rf,"msOf")});var ej={};Q(ej,{runGuard:()=>UQ});import{existsSync as LQ,readFileSync as jQ}from"node:fs";import{homedir as QL}from"node:os";import{join as FQ}from"node:path";async function UQ(e){let t=e[0],n=e.slice(1);switch(t){case"install":return qL(n,QL());case"status":return GQ();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
1146
1146
  `),1):(await Do({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
1147
1147
  `),0)}case"off":return await Do({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
1148
1148
  `),0;case"stop-gate":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard stop-gate <on|off>
@@ -1150,38 +1150,38 @@ Takes effect for NEW sessions (hooks are read at session start; Codex asks you t
1150
1150
  `),0)}case"difficulty":case"capture":case"consult":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard ${t} <on|off>
1151
1151
  `),1):(await Do(t==="difficulty"?{guard_difficulty:r==="on"}:t==="capture"?{guard_capture:r==="on"}:{guard_consult:r==="on"}),process.stdout.write(r==="on"?`${t} trigger follows your convention prefs again on this machine.
1152
1152
  `:`${t} trigger disabled on this machine (your convention prefs are unchanged).
1153
- `),0)}case"skip":return HQ(n);default:return process.stdout.write(jQ),t===void 0||t==="--help"||t==="-h"?0:1}}async function HQ(e){let t=null,n=null,r="consult";for(let a=0;a<e.length;a++)e[a]==="--session"?t=e[++a]??null:e[a]==="--reason"?n=e[++a]??null:e[a]==="--kind"&&(r=e[++a]??"");if(!t||!n||n.trim().length===0||!ZL.includes(r))return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why>" [--kind ${ZL.join("|")}]
1153
+ `),0)}case"skip":return BQ(n);default:return process.stdout.write(HQ),t===void 0||t==="--help"||t==="-h"?0:1}}async function BQ(e){let t=null,n=null,r="consult";for(let a=0;a<e.length;a++)e[a]==="--session"?t=e[++a]??null:e[a]==="--reason"?n=e[++a]??null:e[a]==="--kind"&&(r=e[++a]??"");if(!t||!n||n.trim().length===0||!ZL.includes(r))return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why>" [--kind ${ZL.join("|")}]
1154
1154
  `),1;let o=n.trim().slice(0,500);if(fd.includes(r)){let a=r,l=await Is(t);return await Mr(t,{...l,skipped:{...l.skipped,[a]:l.turn??"*"}}),await oe({event:"override",session_id:t,reason:o,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t} \u2014 the trigger opens on the next attempt.
1155
1155
  logged (auditable) in ${gr}
1156
1156
  `),0}if(r!=="consult")return await Cr(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await oe({event:"override",session_id:t,reason:o,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
1157
1157
  logged (auditable) in ${gr}
1158
1158
  `),0;let i=await Xt(t);return await dt(t,{...i,override_reason:o}),await oe({event:"override",session_id:t,reason:o,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
1159
1159
  logged (auditable) in ${gr}
1160
- `),0}async function UQ(){let e=Se(),t=LQ(QL(),".claude","settings.json"),n=null;try{MQ(t)&&(n=$Q(t,"utf8"))}catch{}let r=ct(n,{},cr),o=await KI(),i=vl(),a=i?await Kb(i):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",briefing_channel:sl(n,{guardMode:e.mode}).channel,in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,consult_local:e.consult,policy:a?{difficulty:a.policy.difficulty,capture:a.policy.capture,consult:a.policy.consult,fetched_at:a.fetchedAt,fresh:a.fresh}:null,policy_file:_p},hook_wiring:r.map(c=>({event:c.event,subcommand:c.subcommand,status:c.status,detail:c.detail})),events:o,events_file:gr},null,2)+`
1160
+ `),0}async function GQ(){let e=Se(),t=FQ(QL(),".claude","settings.json"),n=null;try{LQ(t)&&(n=jQ(t,"utf8"))}catch{}let r=ct(n,{},cr),o=await KI(),i=vl(),a=i?await Kb(i):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",briefing_channel:sl(n,{guardMode:e.mode}).channel,in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,consult_local:e.consult,policy:a?{difficulty:a.policy.difficulty,capture:a.policy.capture,consult:a.policy.consult,fetched_at:a.fetchedAt,fresh:a.fresh}:null,policy_file:_p},hook_wiring:r.map(c=>({event:c.event,subcommand:c.subcommand,status:c.status,detail:c.detail})),events:o,events_file:gr},null,2)+`
1161
1161
  `);let l=r.filter(c=>c.status!=="ok");if(e.mode==="off"&&process.stderr.write("\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"),l.length>0&&e.mode!=="off"){process.stderr.write(`
1162
1162
  [maind] guard hook wiring is incomplete:
1163
1163
  `);for(let c of l)process.stderr.write(` \u2022 ${c.detail}
1164
- `);l.some(c=>c.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var ZL,jQ,tj=w(()=>{"use strict";Dt();Rd();Le();Zt();zL();pn();vw();Je();Rl();Fo();ZL=["consult","difficulty","capture",...fd],jQ=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)"," difficulty <on|off>"," in-loop trigger 1 on this machine (ADR-360): repeated failures \u2192 consult maind"," capture <on|off>"," in-loop trigger 2 on this machine (ADR-360): hard-won fix \u2192 ask about a learning"," consult <on|off>"," consultation triggers on this machine (ADR-375): plan mode, agent docs, risky paths"," (on = follow your convention prefs, which are the declared opt-out)",' skip --session <id> --reason "<why>" [--kind consult|difficulty|capture|plan|agent_doc|risk]'," record a logged override for one session (default kind: consult \u2014"," the block-gate exit valve; difficulty closes the open episode;"," capture answers the pending learning question; plan|agent_doc|risk"," lift that consultation trigger for the current turn)",""].join(`
1165
- `);s(FQ,"runGuard");s(HQ,"runGuardSkip");s(UQ,"runGuardStatus")});var ij={};Q(ij,{decideDifficultyGate:()=>oj,decideGate:()=>rj,runGuardGate:()=>KQ});function rj(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:nj(n)}:(n.deny_count??0)>=of?n.warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+nj(n)}:{kind:"deny",reason:BQ(e.sessionId,n)}}function nj(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function BQ(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
1164
+ `);l.some(c=>c.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var ZL,HQ,tj=w(()=>{"use strict";Dt();Rd();Le();Zt();zL();pn();vw();Je();Rl();Fo();ZL=["consult","difficulty","capture",...fd],HQ=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)"," difficulty <on|off>"," in-loop trigger 1 on this machine (ADR-360): repeated failures \u2192 consult maind"," capture <on|off>"," in-loop trigger 2 on this machine (ADR-360): hard-won fix \u2192 ask about a learning"," consult <on|off>"," consultation triggers on this machine (ADR-375): plan mode, agent docs, risky paths"," (on = follow your convention prefs, which are the declared opt-out)",' skip --session <id> --reason "<why>" [--kind consult|difficulty|capture|plan|agent_doc|risk]'," record a logged override for one session (default kind: consult \u2014"," the block-gate exit valve; difficulty closes the open episode;"," capture answers the pending learning question; plan|agent_doc|risk"," lift that consultation trigger for the current turn)",""].join(`
1165
+ `);s(UQ,"runGuard");s(BQ,"runGuardSkip");s(GQ,"runGuardStatus")});var ij={};Q(ij,{decideDifficultyGate:()=>oj,decideGate:()=>rj,runGuardGate:()=>VQ});function rj(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:nj(n)}:(n.deny_count??0)>=of?n.warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+nj(n)}:{kind:"deny",reason:KQ(e.sessionId,n)}}function nj(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function KQ(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
1166
1166
  1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
1167
1167
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
1168
- After ${of} denies this gate downgrades itself to warn.`}function oj(e){let{mode:t,status:n,session:r}=e;return t!=="block"||!e.enabled||!e.denyCapable?{kind:"allow"}:!n.open||n.chain===null?{kind:"allow"}:(r.difficulty_deny_count??0)>=of?r.difficulty_breaker_warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Difficulty-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+Va(n.chain)}:{kind:"deny",reason:GQ(n,e.sessionId)}}function GQ(e,t){return`[maind guard | block] Edit denied \u2014 ${m_(e.chain)}. Two exits:
1168
+ After ${of} denies this gate downgrades itself to warn.`}function oj(e){let{mode:t,status:n,session:r}=e;return t!=="block"||!e.enabled||!e.denyCapable?{kind:"allow"}:!n.open||n.chain===null?{kind:"allow"}:(r.difficulty_deny_count??0)>=of?r.difficulty_breaker_warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Difficulty-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+Va(n.chain)}:{kind:"deny",reason:WQ(n,e.sessionId)}}function WQ(e,t){return`[maind guard | block] Edit denied \u2014 ${m_(e.chain)}. Two exits:
1169
1169
  1. Consult: call search_lessons with the symptom \u2014 error code, tool or library, never paths or secrets \u2014 the gate opens on the next attempt.
1170
1170
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
1171
- After ${of} denies this gate downgrades itself to warn.`}async function KQ(){try{let e=Se();if(e.mode==="off")return 0;let t=await je();if(Yt(t))return 0;let n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let o=await Xt(r),i=Ir(await ue(),r),a=i!==null,l=rj({mode:e.mode,session:o,consulted:a,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),u=Z()??void 0;if(l.kind==="deny")return process.stdout.write(dn(l.reason)),await dt(r,{...o,deny_count:(o.deny_count??0)+1}),await oe({event:"deny",session_id:r,cwd:c,project_key:u}),0;if(l.kind==="warn")return process.stdout.write(Dn(l.context)),await dt(r,{...o,warned:!0,edits_seen:(o.edits_seen??0)+1}),await oe({event:"warn",session_id:r,cwd:c,project_key:u}),0;if(e.mode==="block"&&e.difficulty&&_s(r)){let d=Bi(await Ho(r),i,Date.now()),p=d.open?oj({mode:e.mode,enabled:e.difficulty,denyCapable:Wa((await Ar(!1)).difficulty),status:d,session:o,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(dn(p.reason)),await dt(r,{...o,difficulty_deny_count:(o.difficulty_deny_count??0)+1}),await oe({event:"difficulty_deny",session_id:r,cwd:c,project_key:u,detail:String(d.chain?.failures.length??0)}),0;if(p.kind==="warn")return process.stdout.write(Dn(p.context)),await dt(r,{...o,difficulty_breaker_warned:!0,edits_seen:(o.edits_seen??0)+1}),0}return await dt(r,{...o,edits_seen:(o.edits_seen??0)+1}),0}catch{return 0}}var of,sj=w(()=>{"use strict";Dt();tt();Ie();qa();ut();de();Zt();ks();pn();Je();Rl();Fo();of=3;s(rj,"decideGate");s(nj,"warnText");s(BQ,"denyText");s(oj,"decideDifficultyGate");s(GQ,"difficultyDenyText");s(KQ,"runGuardGate")});var lj={};Q(lj,{decideStopGate:()=>aj,runGuardStop:()=>VQ});function aj(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function VQ(){try{let e=Se();if(e.mode==="off"||!e.stopGate)return 0;let t=await je();if(Yt(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await Xt(n),o=(await ue()).guard_signals?.[n]?.reviewed_at!==void 0;return aj({enabled:!0,editsSeen:r.edits_seen??0,reviewed:o,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:WQ})),await dt(n,{...r,stop_blocked:!0}),await oe({event:"stop_block",session_id:n})),0}catch{return 0}}var WQ,cj=w(()=>{"use strict";tt();Ie();ut();Zt();pn();Je();s(aj,"decideStopGate");WQ="[maind guard] Stop gate (strict, opt-in): this session edited files but no review ran. Run the review over the edit batches \u2014 attest_review_changes (one call, a server verdict; a clean pushed commit is also recorded), or codebase_review_changes then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";s(VQ,"runGuardStop")});import{existsSync as mj}from"node:fs";import{dirname as uj,isAbsolute as dj,join as qQ,relative as pj,resolve as zQ,sep as fj}from"node:path";function Sw(e){return fj==="/"?e:e.split(fj).join("/")}function ZQ(e){let t=Sw(e);return[...gc,...YQ].some(r=>t===r||t.endsWith(`/${r}`))?!0:XQ.some(r=>r.test(t))}function QQ(e,t,n=mj){let r=dj(e)?e:zQ(t,e),o=uj(r);for(let a=0;a<64;a++){if(n(qQ(o,".git")))return Sw(pj(o,r));let l=uj(o);if(l===o)break;o=l}let i=pj(t,r);return Sw(i.startsWith("..")||dj(i)?r:i)}function hj(e,t,n=mj){let r=null;for(let o of e){if(ZQ(o))return{trigger:"agent_doc"};if(r===null){let i=Zh(QQ(o,t,n)).find(a=>JQ.has(a));i!==void 0&&(r={trigger:"risk",flag:i})}}return r}var JQ,YQ,XQ,gj=w(()=>{"use strict";Me();Et();JQ=new Set(["sql_migration_added","auth_config_changed","ci_workflow_changed","env_or_secrets_file"]),YQ=["MEMORY.md","CLAUDE.local.md"],XQ=[/(^|\/)\.claude\/(rules|agents|skills)\/.+\.md$/,/(^|\/)\.cursor\/rules\/[^/]+\.mdc?$/,/(^|\/)\.claude\/projects\/[^/]+\/memory\/[^/]+\.md$/];s(Sw,"posix");s(ZQ,"isAgentDocPath");s(QQ,"repoRelativePath");s(hj,"consultPointOf")});var lf={};Q(lf,{CONSULT_TOOLS:()=>yj,applyDecision:()=>Sj,briefed:()=>kj,consultDenyText:()=>xj,consultStep:()=>wj,decideStep:()=>vj,markPrompt:()=>Ej,marksOf:()=>_j,noteStop:()=>Tj,runGuardConsult:()=>eee,runGuardPromptMark:()=>tee,runGuardSkipNote:()=>nee,turnKeyOf:()=>bj});function xw(e){return typeof e.session_id=="string"&&e.session_id.trim().length>0?e.session_id.trim():null}function sf(e){return typeof e=="string"&&e.length>0?e:null}function _j(e){return{turnStartedAtMs:rf(e.turn_started_at),planStartedAtMs:rf(e.plan_started_at),planSatisfiedAtMs:rf(e.plan_satisfied_at)}}function bj(e,t){return sf(e.prompt_id)??t.turn??"session"}function kj(e,t){return e.injected===!0||e.carryover===!0||typeof e.override_reason=="string"||t!==null}function wj(e){let t=new Date(e.nowMs).toISOString();if(e.tool==="EnterPlanMode")return{kind:"done",next:{...e.state,plan_started_at:t,plan_satisfied_at:void 0}};let n,r;if(e.tool==="ExitPlanMode")n="plan";else if(e.point!==null)n=e.point.trigger,r=e.point.trigger==="risk"?e.point.flag:void 0;else return{kind:"done",next:e.state};let o=e.state.skipped?.[n],i=o==="*"||o===e.turnKey||u_(n,e.consultedAtMs,_j(e.state),e.nowMs);if(n==="plan"){let a=i?{...e.state,plan_satisfied_at:t}:{...e.state,plan_satisfied_at:void 0};return i?{kind:"done",next:a}:{kind:"decide",next:a,trigger:n}}return i?{kind:"done",next:e.state}:{kind:"decide",next:e.state,trigger:n,flag:r}}function vj(e){return d_({active:e.localOn&&mr(e.rule),consulted:!1,denyCapable:e.mode==="block"&&Wa(e.rule),warnedThisTurn:e.state.warned_turn?.[e.trigger]===e.turnKey,warnsThisSession:e.state.warns?.[e.trigger]??0,denyCount:e.state.denies?.[e.trigger]??0,breakerWarned:e.state.breaker_warned?.[e.trigger]===!0})}function Sj(e,t,n,r,o){if(t.kind==="allow")return e;let i={...e,pending:[...e.pending??[],r]};return t.kind==="deny"?i.denies={...e.denies,[n]:(e.denies?.[n]??0)+1}:t.breaker?i.breaker_warned={...e.breaker_warned,[n]:!0}:(i.warned_turn={...e.warned_turn,[n]:o},i.warns={...e.warns,[n]:(e.warns?.[n]??0)+1}),i}function xj(e,t,n,r){let o=`[maind guard | block] ${n} denied \u2014 ${y_(e,t)}.`,i="Consult: call search_lessons with 2-3 key terms of the decision \u2014 never paths or secrets \u2014 the gate opens on the next attempt.",a=`After ${3} denies this trigger downgrades itself to a reminder.`;return e==="plan"?`${o} One exit:
1171
+ After ${of} denies this gate downgrades itself to warn.`}async function VQ(){try{let e=Se();if(e.mode==="off")return 0;let t=await je();if(Yt(t))return 0;let n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let o=await Xt(r),i=Ir(await ue(),r),a=i!==null,l=rj({mode:e.mode,session:o,consulted:a,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),u=Z()??void 0;if(l.kind==="deny")return process.stdout.write(dn(l.reason)),await dt(r,{...o,deny_count:(o.deny_count??0)+1}),await oe({event:"deny",session_id:r,cwd:c,project_key:u}),0;if(l.kind==="warn")return process.stdout.write(Dn(l.context)),await dt(r,{...o,warned:!0,edits_seen:(o.edits_seen??0)+1}),await oe({event:"warn",session_id:r,cwd:c,project_key:u}),0;if(e.mode==="block"&&e.difficulty&&_s(r)){let d=Bi(await Ho(r),i,Date.now()),p=d.open?oj({mode:e.mode,enabled:e.difficulty,denyCapable:Wa((await Ar(!1)).difficulty),status:d,session:o,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(dn(p.reason)),await dt(r,{...o,difficulty_deny_count:(o.difficulty_deny_count??0)+1}),await oe({event:"difficulty_deny",session_id:r,cwd:c,project_key:u,detail:String(d.chain?.failures.length??0)}),0;if(p.kind==="warn")return process.stdout.write(Dn(p.context)),await dt(r,{...o,difficulty_breaker_warned:!0,edits_seen:(o.edits_seen??0)+1}),0}return await dt(r,{...o,edits_seen:(o.edits_seen??0)+1}),0}catch{return 0}}var of,sj=w(()=>{"use strict";Dt();tt();Ie();qa();ut();de();Zt();ks();pn();Je();Rl();Fo();of=3;s(rj,"decideGate");s(nj,"warnText");s(KQ,"denyText");s(oj,"decideDifficultyGate");s(WQ,"difficultyDenyText");s(VQ,"runGuardGate")});var lj={};Q(lj,{decideStopGate:()=>aj,runGuardStop:()=>zQ});function aj(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function zQ(){try{let e=Se();if(e.mode==="off"||!e.stopGate)return 0;let t=await je();if(Yt(t))return 0;let n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await Xt(n),o=(await ue()).guard_signals?.[n]?.reviewed_at!==void 0;return aj({enabled:!0,editsSeen:r.edits_seen??0,reviewed:o,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:qQ})),await dt(n,{...r,stop_blocked:!0}),await oe({event:"stop_block",session_id:n})),0}catch{return 0}}var qQ,cj=w(()=>{"use strict";tt();Ie();ut();Zt();pn();Je();s(aj,"decideStopGate");qQ="[maind guard] Stop gate (strict, opt-in): this session edited files but no review ran. Run the review over the edit batches \u2014 attest_review_changes (one call, a server verdict; a clean pushed commit is also recorded), or codebase_review_changes then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";s(zQ,"runGuardStop")});import{existsSync as mj}from"node:fs";import{dirname as uj,isAbsolute as dj,join as JQ,relative as pj,resolve as YQ,sep as fj}from"node:path";function Sw(e){return fj==="/"?e:e.split(fj).join("/")}function eee(e){let t=Sw(e);return[...gc,...ZQ].some(r=>t===r||t.endsWith(`/${r}`))?!0:QQ.some(r=>r.test(t))}function tee(e,t,n=mj){let r=dj(e)?e:YQ(t,e),o=uj(r);for(let a=0;a<64;a++){if(n(JQ(o,".git")))return Sw(pj(o,r));let l=uj(o);if(l===o)break;o=l}let i=pj(t,r);return Sw(i.startsWith("..")||dj(i)?r:i)}function hj(e,t,n=mj){let r=null;for(let o of e){if(eee(o))return{trigger:"agent_doc"};if(r===null){let i=Zh(tee(o,t,n)).find(a=>XQ.has(a));i!==void 0&&(r={trigger:"risk",flag:i})}}return r}var XQ,ZQ,QQ,gj=w(()=>{"use strict";Me();Et();XQ=new Set(["sql_migration_added","auth_config_changed","ci_workflow_changed","env_or_secrets_file"]),ZQ=["MEMORY.md","CLAUDE.local.md"],QQ=[/(^|\/)\.claude\/(rules|agents|skills)\/.+\.md$/,/(^|\/)\.cursor\/rules\/[^/]+\.mdc?$/,/(^|\/)\.claude\/projects\/[^/]+\/memory\/[^/]+\.md$/];s(Sw,"posix");s(eee,"isAgentDocPath");s(tee,"repoRelativePath");s(hj,"consultPointOf")});var lf={};Q(lf,{CONSULT_TOOLS:()=>yj,applyDecision:()=>Sj,briefed:()=>kj,consultDenyText:()=>xj,consultStep:()=>wj,decideStep:()=>vj,markPrompt:()=>Ej,marksOf:()=>_j,noteStop:()=>Tj,runGuardConsult:()=>nee,runGuardPromptMark:()=>ree,runGuardSkipNote:()=>oee,turnKeyOf:()=>bj});function xw(e){return typeof e.session_id=="string"&&e.session_id.trim().length>0?e.session_id.trim():null}function sf(e){return typeof e=="string"&&e.length>0?e:null}function _j(e){return{turnStartedAtMs:rf(e.turn_started_at),planStartedAtMs:rf(e.plan_started_at),planSatisfiedAtMs:rf(e.plan_satisfied_at)}}function bj(e,t){return sf(e.prompt_id)??t.turn??"session"}function kj(e,t){return e.injected===!0||e.carryover===!0||typeof e.override_reason=="string"||t!==null}function wj(e){let t=new Date(e.nowMs).toISOString();if(e.tool==="EnterPlanMode")return{kind:"done",next:{...e.state,plan_started_at:t,plan_satisfied_at:void 0}};let n,r;if(e.tool==="ExitPlanMode")n="plan";else if(e.point!==null)n=e.point.trigger,r=e.point.trigger==="risk"?e.point.flag:void 0;else return{kind:"done",next:e.state};let o=e.state.skipped?.[n],i=o==="*"||o===e.turnKey||u_(n,e.consultedAtMs,_j(e.state),e.nowMs);if(n==="plan"){let a=i?{...e.state,plan_satisfied_at:t}:{...e.state,plan_satisfied_at:void 0};return i?{kind:"done",next:a}:{kind:"decide",next:a,trigger:n}}return i?{kind:"done",next:e.state}:{kind:"decide",next:e.state,trigger:n,flag:r}}function vj(e){return d_({active:e.localOn&&mr(e.rule),consulted:!1,denyCapable:e.mode==="block"&&Wa(e.rule),warnedThisTurn:e.state.warned_turn?.[e.trigger]===e.turnKey,warnsThisSession:e.state.warns?.[e.trigger]??0,denyCount:e.state.denies?.[e.trigger]??0,breakerWarned:e.state.breaker_warned?.[e.trigger]===!0})}function Sj(e,t,n,r,o){if(t.kind==="allow")return e;let i={...e,pending:[...e.pending??[],r]};return t.kind==="deny"?i.denies={...e.denies,[n]:(e.denies?.[n]??0)+1}:t.breaker?i.breaker_warned={...e.breaker_warned,[n]:!0}:(i.warned_turn={...e.warned_turn,[n]:o},i.warns={...e.warns,[n]:(e.warns?.[n]??0)+1}),i}function xj(e,t,n,r){let o=`[maind guard | block] ${n} denied \u2014 ${y_(e,t)}.`,i="Consult: call search_lessons with 2-3 key terms of the decision \u2014 never paths or secrets \u2014 the gate opens on the next attempt.",a=`After ${3} denies this trigger downgrades itself to a reminder.`;return e==="plan"?`${o} One exit:
1172
1172
  ${i}
1173
1173
  ${a}`:`${o} Two exits:
1174
1174
  1. ${i}
1175
1175
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${r} --kind ${e} --reason "<why no consultation is needed>"\` and retry.
1176
- `+a}function af(e,t,n){return[e,t,n].filter(r=>typeof r=="string").join(":")}async function eee(){try{let e=Se();if(e.mode==="off"||!e.consult)return 0;let t=await je();if(Yt(t))return 0;let n=(t.tool_name??"").toString();if(!yj.includes(n))return 0;let r=xw(t);if(r===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),i=n==="Edit"||n==="Write"?hj(Mt(t).map(_=>_.path),o):null;if((n==="Edit"||n==="Write")&&i===null)return 0;let a=await Is(r),l=Ir(await ue(),r),c=Date.now(),u=bj(t,a),d=wj({tool:n,point:i,state:a,consultedAtMs:l,turnKey:u,nowMs:c});if(d.kind==="done")return d.next!==a&&await Mr(r,d.next),0;if(!kj(await Xt(r),l))return d.next!==a&&await Mr(r,d.next),0;let p=(await Ar(!0)).consult,f=vj({state:d.next,trigger:d.trigger,mode:e.mode,localOn:e.consult,rule:p,turnKey:u}),m={trigger:d.trigger,at:c,...d.flag!==void 0?{flag:d.flag}:{},...sf(t.agent_id)!==null?{agent:!0}:{}},h=Sj(d.next,f,d.trigger,m,u);if(h!==a&&await Mr(r,h),f.kind==="allow")return 0;let g=Z()??void 0;return f.kind==="deny"?process.stdout.write(dn(xj(d.trigger,d.flag,n,r))):process.stdout.write(Dn(g_(d.trigger,d.flag))),await oe({event:f.kind==="deny"?"consult_deny":"consult_warn",session_id:r,cwd:o,project_key:g,detail:af(d.trigger,d.flag,f.kind==="warn"&&f.breaker?"breaker":void 0)}),0}catch{return 0}}function Ej(e){let t=f_(e.state.stop_seen===!0,e.state.last_message_known===!0),{resolved:n,open:r}=md(e.state.pending??[],e.consultedAtMs,[]),o=r.filter(l=>l.agent!==!0).map(l=>({pending:l,how:t})),i=new Date(e.nowMs).toISOString(),a={...e.state,turn:e.promptId??`t:${i}`,turn_started_at:i,pending:[],stop_seen:!1,last_message_known:!1};return e.permissionMode==="plan"?a.plan_started_at===void 0&&(a.plan_started_at=i):e.permissionMode!==null&&(a.plan_started_at=void 0),{next:a,resolved:n,unresolved:o}}async function tee(){try{let e=Se();if(e.mode==="off"||!e.consult)return 0;let t=await je();if(Yt(t))return 0;let n=xw(t);if(n===null)return 0;let r=await Is(n),{next:o,resolved:i,unresolved:a}=Ej({state:r,promptId:sf(t.prompt_id),permissionMode:sf(t.permission_mode),consultedAtMs:(r.pending??[]).length>0?Ir(await ue(),n):null,nowMs:Date.now()});if(await Mr(n,o),i.length===0&&a.length===0)return 0;let l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),c=Z()??void 0;for(let u of i)await oe({event:"consult_resolved",session_id:n,cwd:l,project_key:c,detail:af(u.pending.trigger,u.pending.flag,u.how)});for(let u of a)await oe({event:"consult_unresolved",session_id:n,cwd:l,project_key:c,detail:af(u.pending.trigger,u.pending.flag,u.how)});return 0}catch{return 0}}function Tj(e){let t=p_(e.lastMessage),{resolved:n,open:r}=md(e.state.pending??[],e.consultedAtMs,t??[]);return{next:{...e.state,pending:r,stop_seen:!0,last_message_known:t!==null||e.state.last_message_known===!0},resolved:n,skips:t??[]}}async function nee(){try{let e=Se();if(e.mode==="off"||!e.consult)return 0;let t=await je();if(Yt(t))return 0;let n=xw(t);if(n===null)return 0;let r=await Is(n),{next:o,resolved:i,skips:a}=Tj({state:r,lastMessage:t.last_assistant_message,consultedAtMs:Ir(await ue(),n)});await Mr(n,o);let l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),c=Z()??void 0;for(let u of i)await oe({event:"consult_resolved",session_id:n,cwd:l,project_key:c,detail:af(u.pending.trigger,u.pending.flag,u.how)});for(let u of a)await oe({event:"override",session_id:n,cwd:l,project_key:c,reason:u.reason,detail:`skip-line:${u.trigger??"any"}`});return 0}catch{return 0}}var yj,cf=w(()=>{"use strict";Dt();tt();Ie();qa();ut();de();Zt();vw();gj();ks();pn();Je();Fo();yj=["EnterPlanMode","ExitPlanMode","Edit","Write"];s(xw,"sessionIdOf");s(sf,"str");s(_j,"marksOf");s(bj,"turnKeyOf");s(kj,"briefed");s(wj,"consultStep");s(vj,"decideStep");s(Sj,"applyDecision");s(xj,"consultDenyText");s(af,"detailOf");s(eee,"runGuardConsult");s(Ej,"markPrompt");s(tee,"runGuardPromptMark");s(Tj,"noteStop");s(nee,"runGuardSkipNote")});import{appendFile as ree,mkdir as oee,readFile as Rj,rename as Cj,writeFile as Ij}from"node:fs/promises";import{homedir as Oj}from"node:os";import{join as Nj}from"node:path";function Dj(e,t,n,r){if(t==="off"||e.length===0)return null;let o={},i=new Map,a=1/0,l=-1/0;for(let u of e){u.at<a&&(a=u.at),u.at>l&&(l=u.at);let d=o[u.tool]??={calls:0,warns:0,denies:0};if(u.event==="tool_call"?d.calls+=1:u.event==="policy_warn"||u.event==="sha_warn"?d.warns+=1:d.denies+=1,(u.event==="policy_warn"||u.event==="policy_deny")&&u.convention_id!==void 0&&u.convention_version!==void 0){let p=i.get(u.convention_id);(p===void 0||u.convention_version>p)&&i.set(u.convention_id,u.convention_version)}}let c=Object.entries(o).sort((u,d)=>d[1].calls+d[1].warns+d[1].denies-(u[1].calls+u[1].warns+u[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(l).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(c),event_count:Math.min(e.length,1e5),citations:[...i.entries()].slice(0,32).map(([u,d])=>({convention_id:u,convention_version:d})),...r?{project_key:r}:{}}}function Vo(){return Nj(Oj(),".maind","gateway","attest-spool.jsonl")}async function Ew(e){let t=ee();if(t===null)return!1;let n=await Qt("gateway_attest",{...e},{apiKey:t,deviceId:ke(),projectKey:e.project_key??null,bridgeVersion:K,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function Pj(e){try{await oee(Nj(Oj(),".maind","gateway"),{recursive:!0}),await ree(Vo(),JSON.stringify(e)+`
1177
- `,{mode:384}),await iee()}catch{}}async function iee(){try{let t=(await Rj(Vo(),"utf8")).split(`
1176
+ `+a}function af(e,t,n){return[e,t,n].filter(r=>typeof r=="string").join(":")}async function nee(){try{let e=Se();if(e.mode==="off"||!e.consult)return 0;let t=await je();if(Yt(t))return 0;let n=(t.tool_name??"").toString();if(!yj.includes(n))return 0;let r=xw(t);if(r===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),i=n==="Edit"||n==="Write"?hj(Mt(t).map(_=>_.path),o):null;if((n==="Edit"||n==="Write")&&i===null)return 0;let a=await Is(r),l=Ir(await ue(),r),c=Date.now(),u=bj(t,a),d=wj({tool:n,point:i,state:a,consultedAtMs:l,turnKey:u,nowMs:c});if(d.kind==="done")return d.next!==a&&await Mr(r,d.next),0;if(!kj(await Xt(r),l))return d.next!==a&&await Mr(r,d.next),0;let p=(await Ar(!0)).consult,f=vj({state:d.next,trigger:d.trigger,mode:e.mode,localOn:e.consult,rule:p,turnKey:u}),m={trigger:d.trigger,at:c,...d.flag!==void 0?{flag:d.flag}:{},...sf(t.agent_id)!==null?{agent:!0}:{}},h=Sj(d.next,f,d.trigger,m,u);if(h!==a&&await Mr(r,h),f.kind==="allow")return 0;let g=Z()??void 0;return f.kind==="deny"?process.stdout.write(dn(xj(d.trigger,d.flag,n,r))):process.stdout.write(Dn(g_(d.trigger,d.flag))),await oe({event:f.kind==="deny"?"consult_deny":"consult_warn",session_id:r,cwd:o,project_key:g,detail:af(d.trigger,d.flag,f.kind==="warn"&&f.breaker?"breaker":void 0)}),0}catch{return 0}}function Ej(e){let t=f_(e.state.stop_seen===!0,e.state.last_message_known===!0),{resolved:n,open:r}=md(e.state.pending??[],e.consultedAtMs,[]),o=r.filter(l=>l.agent!==!0).map(l=>({pending:l,how:t})),i=new Date(e.nowMs).toISOString(),a={...e.state,turn:e.promptId??`t:${i}`,turn_started_at:i,pending:[],stop_seen:!1,last_message_known:!1};return e.permissionMode==="plan"?a.plan_started_at===void 0&&(a.plan_started_at=i):e.permissionMode!==null&&(a.plan_started_at=void 0),{next:a,resolved:n,unresolved:o}}async function ree(){try{let e=Se();if(e.mode==="off"||!e.consult)return 0;let t=await je();if(Yt(t))return 0;let n=xw(t);if(n===null)return 0;let r=await Is(n),{next:o,resolved:i,unresolved:a}=Ej({state:r,promptId:sf(t.prompt_id),permissionMode:sf(t.permission_mode),consultedAtMs:(r.pending??[]).length>0?Ir(await ue(),n):null,nowMs:Date.now()});if(await Mr(n,o),i.length===0&&a.length===0)return 0;let l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),c=Z()??void 0;for(let u of i)await oe({event:"consult_resolved",session_id:n,cwd:l,project_key:c,detail:af(u.pending.trigger,u.pending.flag,u.how)});for(let u of a)await oe({event:"consult_unresolved",session_id:n,cwd:l,project_key:c,detail:af(u.pending.trigger,u.pending.flag,u.how)});return 0}catch{return 0}}function Tj(e){let t=p_(e.lastMessage),{resolved:n,open:r}=md(e.state.pending??[],e.consultedAtMs,t??[]);return{next:{...e.state,pending:r,stop_seen:!0,last_message_known:t!==null||e.state.last_message_known===!0},resolved:n,skips:t??[]}}async function oee(){try{let e=Se();if(e.mode==="off"||!e.consult)return 0;let t=await je();if(Yt(t))return 0;let n=xw(t);if(n===null)return 0;let r=await Is(n),{next:o,resolved:i,skips:a}=Tj({state:r,lastMessage:t.last_assistant_message,consultedAtMs:Ir(await ue(),n)});await Mr(n,o);let l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),c=Z()??void 0;for(let u of i)await oe({event:"consult_resolved",session_id:n,cwd:l,project_key:c,detail:af(u.pending.trigger,u.pending.flag,u.how)});for(let u of a)await oe({event:"override",session_id:n,cwd:l,project_key:c,reason:u.reason,detail:`skip-line:${u.trigger??"any"}`});return 0}catch{return 0}}var yj,cf=w(()=>{"use strict";Dt();tt();Ie();qa();ut();de();Zt();vw();gj();ks();pn();Je();Fo();yj=["EnterPlanMode","ExitPlanMode","Edit","Write"];s(xw,"sessionIdOf");s(sf,"str");s(_j,"marksOf");s(bj,"turnKeyOf");s(kj,"briefed");s(wj,"consultStep");s(vj,"decideStep");s(Sj,"applyDecision");s(xj,"consultDenyText");s(af,"detailOf");s(nee,"runGuardConsult");s(Ej,"markPrompt");s(ree,"runGuardPromptMark");s(Tj,"noteStop");s(oee,"runGuardSkipNote")});import{appendFile as iee,mkdir as see,readFile as Rj,rename as Cj,writeFile as Ij}from"node:fs/promises";import{homedir as Oj}from"node:os";import{join as Nj}from"node:path";function Dj(e,t,n,r){if(t==="off"||e.length===0)return null;let o={},i=new Map,a=1/0,l=-1/0;for(let u of e){u.at<a&&(a=u.at),u.at>l&&(l=u.at);let d=o[u.tool]??={calls:0,warns:0,denies:0};if(u.event==="tool_call"?d.calls+=1:u.event==="policy_warn"||u.event==="sha_warn"?d.warns+=1:d.denies+=1,(u.event==="policy_warn"||u.event==="policy_deny")&&u.convention_id!==void 0&&u.convention_version!==void 0){let p=i.get(u.convention_id);(p===void 0||u.convention_version>p)&&i.set(u.convention_id,u.convention_version)}}let c=Object.entries(o).sort((u,d)=>d[1].calls+d[1].warns+d[1].denies-(u[1].calls+u[1].warns+u[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(l).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(c),event_count:Math.min(e.length,1e5),citations:[...i.entries()].slice(0,32).map(([u,d])=>({convention_id:u,convention_version:d})),...r?{project_key:r}:{}}}function Vo(){return Nj(Oj(),".maind","gateway","attest-spool.jsonl")}async function Ew(e){let t=ee();if(t===null)return!1;let n=await Qt("gateway_attest",{...e},{apiKey:t,deviceId:ke(),projectKey:e.project_key??null,bridgeVersion:K,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function Pj(e){try{await see(Nj(Oj(),".maind","gateway"),{recursive:!0}),await iee(Vo(),JSON.stringify(e)+`
1177
+ `,{mode:384}),await aee()}catch{}}async function aee(){try{let t=(await Rj(Vo(),"utf8")).split(`
1178
1178
  `).filter(r=>r.trim());if(t.length<=Aj)return;let n=`${Vo()}.${process.pid}.tmp`;await Ij(n,t.slice(-Aj).join(`
1179
1179
  `)+`
1180
1180
  `,{mode:384}),await Cj(n,Vo())}catch{}}async function Mj(){let e;try{e=(await Rj(Vo(),"utf8")).split(`
1181
1181
  `).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 Ew(o)||(n=!0,t.push(r))}try{let r=`${Vo()}.${process.pid}.tmp`;await Ij(r,t.length>0?t.join(`
1182
1182
  `)+`
1183
- `:"",{mode:384}),await Cj(r,Vo())}catch{}}var Aj,$j=w(()=>{"use strict";we();Ln();Xe();Aj=256;s(Dj,"aggregateWindow");s(Vo,"attestSpoolPath");s(Ew,"postAttestation");s(Pj,"spoolAttestation");s(iee,"capSpool");s(Mj,"flushAttestSpool")});function Hl(e=process.env,t=re()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function uf(e=process.env,t=re()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Lj(e,t=Re()){let n={};try{let o=await W(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 G(t,JSON.stringify(r,null,2)+`
1184
- `,384)}async function jj(e,t=Re()){await Lj({gateway_mode:e},t)}async function Fj(e,t=Re()){await Lj({gateway_attest:e},t)}function Hj(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 Tw=w(()=>{"use strict";Ce();le();s(Hl,"resolveGatewayMode");s(uf,"resolveGatewayAttest");s(Lj,"writeGatewayConfigPatch");s(jj,"writeGatewayMode");s(Fj,"writeGatewayAttest");s(Hj,"resolveShaProofMode")});function Bj(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 l=typeof o.id=="string"&&o.id.length>0&&o.id.length<=64?o.id:null,c=typeof o.version=="number"&&Number.isInteger(o.version)&&o.version>=1?o.version:null;if(l===null||c===null)continue;let u=typeof o.severity=="string"&&see.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:l,conventionVersion:c,severity:u,summary:d})}}return n}function aee(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Gj(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)aee(i,e,t)&&(o===null||Uj[i.severity]>Uj[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function Kj(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 see,Uj,Aw=w(()=>{"use strict";see=new Set(["required","recommended","info"]);s(Bj,"extractGatewayRules");Uj={required:2,recommended:1,info:0};s(aee,"ruleMatches");s(Gj,"decideToolCall");s(Kj,"policyDenyText")});import{mkdirSync as lee,readFileSync as cee,renameSync as uee,writeFileSync as dee}from"node:fs";import{homedir as pee}from"node:os";import{dirname as fee,join as mee}from"node:path";function Wj(){return mee(pee(),".maind","gateway","policy-cache.json")}function df(e,t,n=new Date().toISOString()){try{let r={version:Rw,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=Wj();lee(fee(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;dee(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),uee(i,o)}catch{}}function pf(e){try{let t=cee(Wj(),"utf8"),n=JSON.parse(t);return n.version!==Rw||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Rw,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Rw,Cw=w(()=>{"use strict";Rw=1;s(Wj,"policyCachePath");s(df,"writePolicyCache");s(pf,"readPolicyCache")});function Ul(e=process.env){let t=e.MAIND_MCP_URL??ll,n=ee();return{mcpUrl:t,keyFp:n?tr(n):"anon"}}async function ff(e=6e3){let t=ee();if(t===null)return null;let n=null;try{n=Z()}catch{n=null}let r=await Qt("get_conventions",{},{apiKey:t,deviceId:ke(),projectKey:n,bridgeVersion:K,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return Bj(o)}var Iw=w(()=>{"use strict";Wt();we();Ln();de();Xe();Aw();s(Ul,"policyIdentity");s(ff,"fetchGatewayRules")});function Bl(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 hee(e){if(Bl(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 gee(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Bl(e)?{action:"skip",reason:"already-wrapped"}:hee(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Vj(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,l={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...o]};return a&&(l.env=a),l}function qj(e){if(!Bl(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 zj(e){return Object.entries(e).map(([t,n])=>{let r=gee(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Jj=w(()=>{"use strict";s(Bl,"isGatewayWrapped");s(hee,"isMaindProxyEntry");s(gee,"classifyServer");s(Vj,"wrapServerEntry");s(qj,"unwrapServerEntry");s(zj,"planRewrites")});var tF={};Q(tF,{runGatewayInstall:()=>vee,runGatewayUninstall:()=>See});import{existsSync as yee,readFileSync as _ee}from"node:fs";import{homedir as bee}from"node:os";import{join as Yj}from"node:path";import{createInterface as kee}from"node:readline";function Xj(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 Zj(){return[{label:"Claude Code (project .mcp.json)",path:Yj(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Yj(bee(),".claude.json")}]}async function Qj(e){let t=kee({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 eF(e){let t=wee(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 wee(e){try{return yee(e)?_ee(e,"utf8"):null}catch{return null}}async function vee(e){let t=Xj(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1183
+ `:"",{mode:384}),await Cj(r,Vo())}catch{}}var Aj,$j=w(()=>{"use strict";we();Ln();Xe();Aj=256;s(Dj,"aggregateWindow");s(Vo,"attestSpoolPath");s(Ew,"postAttestation");s(Pj,"spoolAttestation");s(aee,"capSpool");s(Mj,"flushAttestSpool")});function Hl(e=process.env,t=re()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function uf(e=process.env,t=re()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Lj(e,t=Re()){let n={};try{let o=await W(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 G(t,JSON.stringify(r,null,2)+`
1184
+ `,384)}async function jj(e,t=Re()){await Lj({gateway_mode:e},t)}async function Fj(e,t=Re()){await Lj({gateway_attest:e},t)}function Hj(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 Tw=w(()=>{"use strict";Ce();le();s(Hl,"resolveGatewayMode");s(uf,"resolveGatewayAttest");s(Lj,"writeGatewayConfigPatch");s(jj,"writeGatewayMode");s(Fj,"writeGatewayAttest");s(Hj,"resolveShaProofMode")});function Bj(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 l=typeof o.id=="string"&&o.id.length>0&&o.id.length<=64?o.id:null,c=typeof o.version=="number"&&Number.isInteger(o.version)&&o.version>=1?o.version:null;if(l===null||c===null)continue;let u=typeof o.severity=="string"&&lee.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:l,conventionVersion:c,severity:u,summary:d})}}return n}function cee(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Gj(e,t,n,r){if(r==="off")return{kind:"allow"};let o=null;for(let i of n)cee(i,e,t)&&(o===null||Uj[i.severity]>Uj[o.severity])&&(o=i);return o===null?{kind:"allow"}:o.severity==="required"&&r==="enforce"?{kind:"deny",rule:o}:{kind:"warn",rule:o}}function Kj(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 lee,Uj,Aw=w(()=>{"use strict";lee=new Set(["required","recommended","info"]);s(Bj,"extractGatewayRules");Uj={required:2,recommended:1,info:0};s(cee,"ruleMatches");s(Gj,"decideToolCall");s(Kj,"policyDenyText")});import{mkdirSync as uee,readFileSync as dee,renameSync as pee,writeFileSync as fee}from"node:fs";import{homedir as mee}from"node:os";import{dirname as hee,join as gee}from"node:path";function Wj(){return gee(mee(),".maind","gateway","policy-cache.json")}function df(e,t,n=new Date().toISOString()){try{let r={version:Rw,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},o=Wj();uee(hee(o),{recursive:!0});let i=`${o}.${process.pid}.tmp`;fee(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),pee(i,o)}catch{}}function pf(e){try{let t=dee(Wj(),"utf8"),n=JSON.parse(t);return n.version!==Rw||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Rw,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Rw,Cw=w(()=>{"use strict";Rw=1;s(Wj,"policyCachePath");s(df,"writePolicyCache");s(pf,"readPolicyCache")});function Ul(e=process.env){let t=e.MAIND_MCP_URL??ll,n=ee();return{mcpUrl:t,keyFp:n?tr(n):"anon"}}async function ff(e=6e3){let t=ee();if(t===null)return null;let n=null;try{n=Z()}catch{n=null}let r=await Qt("get_conventions",{},{apiKey:t,deviceId:ke(),projectKey:n,bridgeVersion:K,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return null}return Bj(o)}var Iw=w(()=>{"use strict";Wt();we();Ln();de();Xe();Aw();s(Ul,"policyIdentity");s(ff,"fetchGatewayRules")});function Bl(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 yee(e){if(Bl(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 _ee(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Bl(e)?{action:"skip",reason:"already-wrapped"}:yee(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Vj(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,l={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...o]};return a&&(l.env=a),l}function qj(e){if(!Bl(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 zj(e){return Object.entries(e).map(([t,n])=>{let r=_ee(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Jj=w(()=>{"use strict";s(Bl,"isGatewayWrapped");s(yee,"isMaindProxyEntry");s(_ee,"classifyServer");s(Vj,"wrapServerEntry");s(qj,"unwrapServerEntry");s(zj,"planRewrites")});var tF={};Q(tF,{runGatewayInstall:()=>xee,runGatewayUninstall:()=>Eee});import{existsSync as bee,readFileSync as kee}from"node:fs";import{homedir as wee}from"node:os";import{join as Yj}from"node:path";import{createInterface as vee}from"node:readline";function Xj(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 Zj(){return[{label:"Claude Code (project .mcp.json)",path:Yj(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Yj(wee(),".claude.json")}]}async function Qj(e){let t=vee({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 eF(e){let t=See(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 See(e){try{return bee(e)?kee(e,"utf8"):null}catch{return null}}async function xee(e){let t=Xj(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
1185
1185
  `),2;let n=Ee({entryPath:se(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let o of Zj()){let i=eF(o.path);if(i===null){process.stderr.write(` skipped ${o.label} \u2014 no mcpServers object
1186
1186
  `);continue}let a=zj(i.servers);for(let l of a){if(l.action==="skip"){process.stderr.write(` skipped ${o.label} \xB7 ${l.key} \u2014 ${l.reason}
1187
1187
  `);continue}if(!(t.yes||await Qj(`Wrap MCP server '${l.key}' in ${o.label} with the maind gateway?
@@ -1193,7 +1193,7 @@ ${a}`:`${o} Two exits:
1193
1193
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
1194
1194
  `:`
1195
1195
  Nothing to wrap.
1196
- `),0}async function See(e){let t=Xj(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1196
+ `),0}async function Eee(e){let t=Xj(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1197
1197
  `),2;let n=0;for(let r of Zj()){let o=eF(r.path);if(o===null)continue;let i=!1;for(let[a,l]of Object.entries(o.servers)){if(!Bl(l)||!(t.yes||await Qj(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let u=qj(l);if(u===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
1198
1198
  `);continue}o.servers[a]=u,i=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
1199
1199
  `)}!t.dryRun&&i&&await G(r.path,JSON.stringify(o.raw,null,2)+`
@@ -1201,26 +1201,26 @@ Nothing to wrap.
1201
1201
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
1202
1202
  `:`
1203
1203
  Nothing wrapped \u2014 nothing to restore.
1204
- `),0}var nF=w(()=>{"use strict";le();Ze();Jj();s(Xj,"parseFlags");s(Zj,"targets");s(Qj,"confirm");s(eF,"loadConfig");s(wee,"readFileSafeSync");s(vee,"runGatewayInstall");s(See,"runGatewayUninstall")});var rF={};Q(rF,{runGatewayAttest:()=>Eee,runGatewayMode:()=>xee,runGatewayPolicy:()=>Ree});async function xee(e){let t=e[0];if(t===void 0){let n=Hl(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1204
+ `),0}var nF=w(()=>{"use strict";le();Ze();Jj();s(Xj,"parseFlags");s(Zj,"targets");s(Qj,"confirm");s(eF,"loadConfig");s(See,"readFileSafeSync");s(xee,"runGatewayInstall");s(Eee,"runGatewayUninstall")});var rF={};Q(rF,{runGatewayAttest:()=>Aee,runGatewayMode:()=>Tee,runGatewayPolicy:()=>Iee});async function Tee(e){let t=e[0];if(t===void 0){let n=Hl(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
1205
1205
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
1206
1206
  `),2):(await jj(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
1207
1207
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
1208
1208
  `:`Convention policy is off; only explicit --deny-tool flags apply.
1209
- `)),0)}async function Eee(e){let t=e[0];if(t===void 0){let n=uf(),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)":""}.
1209
+ `)),0)}async function Aee(e){let t=e[0];if(t===void 0){let n=uf(),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)":""}.
1210
1210
  `+(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.
1211
1211
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
1212
1212
  `),2):(await Fj(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.
1213
1213
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
1214
- `),0)}function Tee(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1214
+ `),0)}function Ree(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
1215
1215
  `;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})
1216
- `}return t}function Aee(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 Ree(e){let t=e.includes("--refresh"),n=Hl(),r=Ul();if(t){let i=await ff();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1216
+ `}return t}function Cee(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 Iee(e){let t=e.includes("--refresh"),n=Hl(),r=Ul();if(t){let i=await ff();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
1217
1217
  `):(df(r,i),process.stdout.write(`maind: policy refreshed (${i.length} rule(s)).
1218
1218
  `))}let o=pf(r);return process.stdout.write(`maind: gateway mode '${n}'
1219
1219
  `),o===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
1220
- `),0):(process.stdout.write(`maind: policy from cache (${Aee(o)}, ${r.mcpUrl}):
1221
- `),process.stdout.write(Tee(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.
1222
- `),0)}var oF=w(()=>{"use strict";Tw();Cw();Iw();s(xee,"runGatewayMode");s(Eee,"runGatewayAttest");s(Tee,"renderRules");s(Aee,"cacheAge");s(Ree,"runGatewayPolicy")});var cF={};Q(cF,{gatewayEventsFile:()=>aF,parseGatewayArgs:()=>lF,runGateway:()=>$ee});import{spawn as Cee}from"node:child_process";import{appendFile as Iee,mkdir as Oee}from"node:fs/promises";import{homedir as iF}from"node:os";import{basename as Nee,join as sF}from"node:path";import{createInterface as Dee}from"node:readline";function aF(){return sF(iF(),".maind","gateway","events.jsonl")}async function Mee(e){try{let t=aF();await Oee(sF(iF(),".maind","gateway"),{recursive:!0}),await Iee(t,JSON.stringify(e)+`
1223
- `,{mode:384})}catch{}}function lF(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 $ee(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:x,runGatewayUninstall:T}=await Promise.resolve().then(()=>(nF(),tF));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:A}=await Promise.resolve().then(()=>(oF(),rF));return e[0]==="mode"?T(e.slice(1)):e[0]==="attest"?x(e.slice(1)):A(e.slice(1))}let t=lF(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1220
+ `),0):(process.stdout.write(`maind: policy from cache (${Cee(o)}, ${r.mcpUrl}):
1221
+ `),process.stdout.write(Ree(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.
1222
+ `),0)}var oF=w(()=>{"use strict";Tw();Cw();Iw();s(Tee,"runGatewayMode");s(Aee,"runGatewayAttest");s(Ree,"renderRules");s(Cee,"cacheAge");s(Iee,"runGatewayPolicy")});var cF={};Q(cF,{gatewayEventsFile:()=>aF,parseGatewayArgs:()=>lF,runGateway:()=>jee});import{spawn as Oee}from"node:child_process";import{appendFile as Nee,mkdir as Dee}from"node:fs/promises";import{homedir as iF}from"node:os";import{basename as Pee,join as sF}from"node:path";import{createInterface as Mee}from"node:readline";function aF(){return sF(iF(),".maind","gateway","events.jsonl")}async function Lee(e){try{let t=aF();await Dee(sF(iF(),".maind","gateway"),{recursive:!0}),await Nee(t,JSON.stringify(e)+`
1223
+ `,{mode:384})}catch{}}function lF(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 jee(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:x,runGatewayUninstall:T}=await Promise.resolve().then(()=>(nF(),tF));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:A}=await Promise.resolve().then(()=>(oF(),rF));return e[0]==="mode"?T(e.slice(1)):e[0]==="attest"?x(e.slice(1)):A(e.slice(1))}let t=lF(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
1224
1224
  maind-mcp-bridge gateway install [--yes] [--dry-run]
1225
1225
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
1226
1226
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -1230,13 +1230,13 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
1230
1230
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
1231
1231
  install/uninstall rewrite Claude Code MCP configs (consent per server).
1232
1232
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
1233
- `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??Nee(o),l=Hl(),c=Hj(),u=c==="off"?null:Si(),d=l==="off"?[]:pf(Ul())?.rules??[];l!=="off"&&ff().then(x=>{x!==null&&(d=x,df(Ul(),x))}).catch(()=>{});let p=[],f=uf()&&ee()!==null&&l!=="off",m=null;try{m=Z()}catch{m=null}let h=Promise.resolve(),g=s(x=>{h=h.then(()=>Mee(x)),f&&p.push(x)},"record"),_=s(async()=>{if(!f)return;let x=Dj(p.splice(0),l,a,m);x!==null&&(await Ew(x)||await Pj(x))},"attestAndReset");f&&Mj().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let k=Cee(o,i,{stdio:["pipe","pipe","inherit"]});k.stdout.pipe(process.stdout),k.on("error",x=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(x)}
1234
- `),process.exitCode=1});let v=Dee({input:process.stdin,terminal:!1});v.on("line",x=>{let T=gR(x);if(T.kind==="request"&&T.method==="tools/call"&&T.toolName){if(n.has(T.toolName)&&T.id!==void 0){process.stdout.write(wi(T.id,T.toolName)+`
1233
+ `),2;let{denyTools:n,label:r,command:o,args:i}=t,a=r??Pee(o),l=Hl(),c=Hj(),u=c==="off"?null:Si(),d=l==="off"?[]:pf(Ul())?.rules??[];l!=="off"&&ff().then(x=>{x!==null&&(d=x,df(Ul(),x))}).catch(()=>{});let p=[],f=uf()&&ee()!==null&&l!=="off",m=null;try{m=Z()}catch{m=null}let h=Promise.resolve(),g=s(x=>{h=h.then(()=>Lee(x)),f&&p.push(x)},"record"),_=s(async()=>{if(!f)return;let x=Dj(p.splice(0),l,a,m);x!==null&&(await Ew(x)||await Pj(x))},"attestAndReset");f&&Mj().catch(()=>{});let b=setInterval(()=>{_()},30*6e4);b.unref();let k=Oee(o,i,{stdio:["pipe","pipe","inherit"]});k.stdout.pipe(process.stdout),k.on("error",x=>{process.stderr.write(`[maind gateway] failed to start '${o}': ${String(x)}
1234
+ `),process.exitCode=1});let v=Mee({input:process.stdin,terminal:!1});v.on("line",x=>{let T=gR(x);if(T.kind==="request"&&T.method==="tools/call"&&T.toolName){if(n.has(T.toolName)&&T.id!==void 0){process.stdout.write(wi(T.id,T.toolName)+`
1235
1235
  `),g(Ig("deny",a,T.toolName,Date.now()));return}let A=Gj(T.toolName,a,d,l);if(A.kind==="deny"&&T.id!==void 0){process.stdout.write(wi(T.id,T.toolName,Kj(T.toolName,A.rule))+`
1236
1236
  `),g(Og("policy_deny",a,T.toolName,Date.now(),A.rule.conventionId,A.rule.conventionVersion));return}(A.kind==="warn"||A.kind==="deny")&&g(Og("policy_warn",a,T.toolName,Date.now(),A.rule.conventionId,A.rule.conventionVersion));let L=cu(x,u);if(L.length>0){let R=L.find(E=>E.verdict==="fabricated");if(R!==void 0&&c==="enforce"&&l==="enforce"&&T.id!==void 0&&R!==void 0&&T.id!==void 0){process.stdout.write(wi(T.id,T.toolName,vi(R,!0))+`
1237
1237
  `),g(Ng("sha_deny",a,T.toolName,Date.now()));return}let D=R??L[0];process.stderr.write(`[maind gateway] ${vi(D,!1)}
1238
1238
  `),g(Ng("sha_warn",a,T.toolName,Date.now()))}g(Ig("tool_call",a,T.toolName,Date.now()))}k.stdin.write(x+`
1239
- `)}),v.on("close",()=>{k.stdin.end()});let S=await new Promise(x=>{k.on("exit",(T,A)=>{x(T??(A?1:0))})});return clearInterval(b),await Promise.race([h,new Promise(x=>setTimeout(x,Pee).unref())]),await _(),S}var Pee,uF=w(()=>{"use strict";Dg();$j();Tw();Aw();uu();Cw();Iw();we();de();s(aF,"gatewayEventsFile");Pee=5e3;s(Mee,"logEvent");s(lF,"parseGatewayArgs");s($ee,"runGateway")});var pF={};Q(pF,{ACTIVITY_WHAT_IS_SENT:()=>Ow,runActivity:()=>jee,statusText:()=>dF});async function jee(e,t={}){let n=t.out??(l=>process.stdout.write(l)),r=t.err??(l=>process.stderr.write(l)),o=e[0];if(o===void 0||o==="status")return n(dF(t)),0;if(o!=="on"&&o!=="off")return r(`usage: maind-mcp-bridge activity [on|off|status]
1239
+ `)}),v.on("close",()=>{k.stdin.end()});let S=await new Promise(x=>{k.on("exit",(T,A)=>{x(T??(A?1:0))})});return clearInterval(b),await Promise.race([h,new Promise(x=>setTimeout(x,$ee).unref())]),await _(),S}var $ee,uF=w(()=>{"use strict";Dg();$j();Tw();Aw();uu();Cw();Iw();we();de();s(aF,"gatewayEventsFile");$ee=5e3;s(Lee,"logEvent");s(lF,"parseGatewayArgs");s(jee,"runGateway")});var pF={};Q(pF,{ACTIVITY_WHAT_IS_SENT:()=>Ow,runActivity:()=>Hee,statusText:()=>dF});async function Hee(e,t={}){let n=t.out??(l=>process.stdout.write(l)),r=t.err??(l=>process.stderr.write(l)),o=e[0];if(o===void 0||o==="status")return n(dF(t)),0;if(o!=="on"&&o!=="off")return r(`usage: maind-mcp-bridge activity [on|off|status]
1240
1240
  `),2;try{await(t.write??(l=>wL(l)))(o==="on")}catch(l){return r(`maind: could not write the bridge config: ${l instanceof Error?l.message:String(l)}
1241
1241
  `),1}let i=t.env??process.env,a=i[Es]!==void 0&&i[Es].trim().length>0?`maind: note \u2014 ${Es} is set in this environment and wins over the config file.
1242
1242
  `:"";return n(o==="on"?"maind: agent activity reporting ON. "+Ow+`
@@ -1244,13 +1244,13 @@ maind: sessions that are already running pick it up when their bridge restarts (
1244
1244
  `+a:`maind: agent activity reporting OFF. Running sessions stop reporting when their bridge restarts.
1245
1245
  `+a),0}function dF(e={}){let t=(e.setting??(()=>Yp(e.env??process.env)))(),n=[],r=t.source==="env"?` (from ${Es} 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 ${Ow}`);let o=null;try{o=(e.projectKey??Z)()}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(`
1246
1246
  `)+`
1247
- `;let i=[];try{i=(e.snapshots??(u=>nt(u)))(o)}catch{i=[]}let a=(e.now??Date.now)(),l=i.filter(u=>{let d=Date.parse(u.written_at);return u.announce_error===void 0&&Number.isFinite(d)&&a-d<=Lee});if(l.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(`
1247
+ `;let i=[];try{i=(e.snapshots??(u=>nt(u)))(o)}catch{i=[]}let a=(e.now??Date.now)(),l=i.filter(u=>{let d=Date.parse(u.written_at);return u.announce_error===void 0&&Number.isFinite(d)&&a-d<=Fee});if(l.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(`
1248
1248
  `)+`
1249
1249
  `;let c=t.enabled?"reports to":"would report to";n.push(`maind: live bridge sessions in this repository: ${l.length}`);for(let u of l){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=yr({branchObjectId:u.branch_object_id??null,boundObjects:u.bound_objects});n.push(`${d} ${p.objectId!==null?`${c} ${el(p)}`:`nothing to report to \u2014 ${el(p)}`}`)}return n.join(`
1250
1250
  `)+`
1251
- `}var Lee,Ow,fF=w(()=>{"use strict";Mn();de();rw();_r();Lee=120*6e4,Ow="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(jee,"runActivity");s(dF,"statusText")});var jw={};Q(jw,{MAX_ENTRIES:()=>Nw,TTL_MS:()=>Mw,crossSessionDir:()=>$w,decideCrossSession:()=>gF,parseSessionDb:()=>hF,pruneDb:()=>Lw,runGuardCrossCheck:()=>qee,runGuardCrossObserve:()=>Vee,staleReason:()=>Dw});import{mkdir as Fee,readFile as Hee,readdir as Uee,stat as mF,unlink as Bee,writeFile as Gee}from"node:fs/promises";import{homedir as Kee}from"node:os";import{join as Pw}from"node:path";function $w(){return Pw(Kee(),".maind","cross-session")}function hF(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 l=a;typeof l.m!="number"||typeof l.t!="number"||!Number.isFinite(l.m)||!Number.isFinite(l.t)||(r[i]={m:l.m,t:l.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 Lw(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Mw);return n.length>Nw&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-Nw)),{files:Object.fromEntries(n),warned:e.warned}}function gF(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Dw(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 yF(e){let t=$w();return await Fee(t,{recursive:!0}),Pw(t,`${e}.json`)}async function _F(e,t){try{let n=await Hee(await yF(e),"utf8");return Lw(hF(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function bF(e,t){try{await Gee(await yF(e),JSON.stringify(t),{mode:384})}catch{}}async function Wee(e){try{let t=$w();for(let n of await Uee(t)){if(!n.endsWith(".json"))continue;let r=Pw(t,n),o=await mF(r).catch(()=>null);o&&e-o.mtimeMs>Mw&&await Bee(r).catch(()=>{})}}catch{}}async function kF(e){try{return(await mF(e)).mtimeMs}catch{return}}async function Vee(e,t=Date.now()){try{if(Se().mode==="off")return 0;let r=e??await je();if(Yt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=k_(r);if(!o||!i)return 0;let a=await kF(i);if(a===void 0)return 0;let l=await _F(o,t);return l.files[i]={m:a,t},delete l.warned[i],await bF(o,Lw(l,t)),await Wee(t),0}catch{return 0}}async function qee(e,t=Date.now()){try{let n=Se();if(n.mode==="off")return 0;let r=e??await je();if(Yt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=k_(r);if(!o||!i)return 0;let a=await _F(o,t),l=gF(a.files[i]?.m,await kF(i));return l.kind==="allow"?0:n.mode==="block"?(process.stdout.write(dn(Dw(i,l))+`
1251
+ `}var Fee,Ow,fF=w(()=>{"use strict";Mn();de();rw();_r();Fee=120*6e4,Ow="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(Hee,"runActivity");s(dF,"statusText")});var jw={};Q(jw,{MAX_ENTRIES:()=>Nw,TTL_MS:()=>Mw,crossSessionDir:()=>$w,decideCrossSession:()=>gF,parseSessionDb:()=>hF,pruneDb:()=>Lw,runGuardCrossCheck:()=>Jee,runGuardCrossObserve:()=>zee,staleReason:()=>Dw});import{mkdir as Uee,readFile as Bee,readdir as Gee,stat as mF,unlink as Kee,writeFile as Wee}from"node:fs/promises";import{homedir as Vee}from"node:os";import{join as Pw}from"node:path";function $w(){return Pw(Vee(),".maind","cross-session")}function hF(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 l=a;typeof l.m!="number"||typeof l.t!="number"||!Number.isFinite(l.m)||!Number.isFinite(l.t)||(r[i]={m:l.m,t:l.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 Lw(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Mw);return n.length>Nw&&(n=n.sort((r,o)=>r[1].t-o[1].t).slice(n.length-Nw)),{files:Object.fromEntries(n),warned:e.warned}}function gF(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Dw(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 yF(e){let t=$w();return await Uee(t,{recursive:!0}),Pw(t,`${e}.json`)}async function _F(e,t){try{let n=await Bee(await yF(e),"utf8");return Lw(hF(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function bF(e,t){try{await Wee(await yF(e),JSON.stringify(t),{mode:384})}catch{}}async function qee(e){try{let t=$w();for(let n of await Gee(t)){if(!n.endsWith(".json"))continue;let r=Pw(t,n),o=await mF(r).catch(()=>null);o&&e-o.mtimeMs>Mw&&await Kee(r).catch(()=>{})}}catch{}}async function kF(e){try{return(await mF(e)).mtimeMs}catch{return}}async function zee(e,t=Date.now()){try{if(Se().mode==="off")return 0;let r=e??await je();if(Yt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=k_(r);if(!o||!i)return 0;let a=await kF(i);if(a===void 0)return 0;let l=await _F(o,t);return l.files[i]={m:a,t},delete l.warned[i],await bF(o,Lw(l,t)),await qee(t),0}catch{return 0}}async function Jee(e,t=Date.now()){try{let n=Se();if(n.mode==="off")return 0;let r=e??await je();if(Yt(r))return 0;let o=typeof r.session_id=="string"?r.session_id:"",i=k_(r);if(!o||!i)return 0;let a=await _F(o,t),l=gF(a.files[i]?.m,await kF(i));return l.kind==="allow"?0:n.mode==="block"?(process.stdout.write(dn(Dw(i,l))+`
1252
1252
  `),await oe({event:"cross_session_deny",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i}),0):(a.warned[i]===l.current||(process.stdout.write(Dn(Dw(i,l))+`
1253
- `),a.warned[i]=l.current,await bF(o,a),await oe({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var Mw,Nw,Fw=w(()=>{"use strict";tt();Ie();qa();Zt();pn();Mw=48*3600*1e3,Nw=500;s($w,"crossSessionDir");s(hF,"parseSessionDb");s(Lw,"pruneDb");s(gF,"decideCrossSession");s(Dw,"staleReason");s(yF,"dbPath");s(_F,"loadDb");s(bF,"saveDb");s(Wee,"sweepStaleSessionFiles");s(kF,"fileMtime");s(Vee,"runGuardCrossObserve");s(qee,"runGuardCrossCheck")});import{randomUUID as zee}from"node:crypto";Me();ha();import{createInterface as EW}from"node:readline";var nW=[["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"],["gemini-cli","gemini-cli"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function rW(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of nW)if(t.includes(n))return r;return null}s(rW,"mapClientInfoNameToFamily");function fR(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Rg(t)||t.method!=="initialize")return null;let n=t.params;if(!Rg(n))return null;let r=n.clientInfo;if(!Rg(r))return null;let o=r.name,i=rW(typeof o=="string"?o:null);if(i===null)return null;let a=r.version,l=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:l}}s(fR,"tryExtractInitializeClient");function Rg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Rg,"isRecord");import{fileURLToPath as oW}from"node:url";var Cg="maind-bridge-",iW=8,mR=8e3;function er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(er,"isRecord");function sW(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!er(t)||t.method!=="initialize"||!er(t.params))return!1;let n=t.params.capabilities;return er(n)&&er(n.roots)}catch{return!1}}s(sW,"clientDeclaresRoots");function aW(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(aW,"isInitializedNotification");function lW(e){if(!er(e)||!er(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!er(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=oW(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=iW)break}return n}s(lW,"rootPathsFrom");var lu=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(Cg)){let n;try{n=JSON.parse(t)}catch{n=null}if(er(n)&&typeof n.id=="string"&&n.id.startsWith(Cg)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&aW(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=mR){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(l=>{let c=s(d=>{clearTimeout(u),this.waiters=this.waiters.filter(p=>p!==c),l(d)},"done"),u=setTimeout(()=>c(!1),n);this.waiters.push(c)})||this.closed))return null;let o=`${Cg}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,i=new Promise(a=>{let l=s(u=>{clearTimeout(c),this.pending.delete(o),a(u)},"settle"),c=setTimeout(()=>l(null),Math.max(0,r-Date.now()));this.pending.set(o,{settle:l,timer:c})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:o,method:t})),i}};async function hR(e,t,n=mR){return sW(e)?lW(await t.request("roots/list",n)):null}s(hR,"listClientRoots");Dg();uu();function Pg(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(`
1253
+ `),a.warned[i]=l.current,await bF(o,a),await oe({event:"cross_session_warn",session_id:o,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var Mw,Nw,Fw=w(()=>{"use strict";tt();Ie();qa();Zt();pn();Mw=48*3600*1e3,Nw=500;s($w,"crossSessionDir");s(hF,"parseSessionDb");s(Lw,"pruneDb");s(gF,"decideCrossSession");s(Dw,"staleReason");s(yF,"dbPath");s(_F,"loadDb");s(bF,"saveDb");s(qee,"sweepStaleSessionFiles");s(kF,"fileMtime");s(zee,"runGuardCrossObserve");s(Jee,"runGuardCrossCheck")});import{randomUUID as Yee}from"node:crypto";Me();ha();import{createInterface as EW}from"node:readline";var nW=[["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"],["gemini-cli","gemini-cli"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function rW(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of nW)if(t.includes(n))return r;return null}s(rW,"mapClientInfoNameToFamily");function fR(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Rg(t)||t.method!=="initialize")return null;let n=t.params;if(!Rg(n))return null;let r=n.clientInfo;if(!Rg(r))return null;let o=r.name,i=rW(typeof o=="string"?o:null);if(i===null)return null;let a=r.version,l=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:l}}s(fR,"tryExtractInitializeClient");function Rg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Rg,"isRecord");import{fileURLToPath as oW}from"node:url";var Cg="maind-bridge-",iW=8,mR=8e3;function er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(er,"isRecord");function sW(e){if(e===null)return!1;try{let t=JSON.parse(e);if(!er(t)||t.method!=="initialize"||!er(t.params))return!1;let n=t.params.capabilities;return er(n)&&er(n.roots)}catch{return!1}}s(sW,"clientDeclaresRoots");function aW(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(aW,"isInitializedNotification");function lW(e){if(!er(e)||!er(e.result))return null;let t=e.result.roots;if(!Array.isArray(t))return null;let n=[];for(let r of t){if(!er(r)||typeof r.uri!="string"||!r.uri.startsWith("file://"))continue;let o;try{o=oW(r.uri)}catch{continue}if(n.includes(o)||n.push(o),n.length>=iW)break}return n}s(lW,"rootPathsFrom");var lu=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(Cg)){let n;try{n=JSON.parse(t)}catch{n=null}if(er(n)&&typeof n.id=="string"&&n.id.startsWith(Cg)&&n.method===void 0)return this.pending.get(n.id)?.settle(n),!0}if(!this.initialized&&aW(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=mR){if(this.closed)return null;let r=Date.now()+n;if(!this.initialized&&(!await new Promise(l=>{let c=s(d=>{clearTimeout(u),this.waiters=this.waiters.filter(p=>p!==c),l(d)},"done"),u=setTimeout(()=>c(!1),n);this.waiters.push(c)})||this.closed))return null;let o=`${Cg}${t.replace(/[^a-z]/gi,"-")}-${++this.seq}`,i=new Promise(a=>{let l=s(u=>{clearTimeout(c),this.pending.delete(o),a(u)},"settle"),c=setTimeout(()=>l(null),Math.max(0,r-Date.now()));this.pending.set(o,{settle:l,timer:c})});return this.writeLine(JSON.stringify({jsonrpc:"2.0",id:o,method:t})),i}};async function hR(e,t,n=mR){return sW(e)?lW(await t.request("roots/list",n)):null}s(hR,"listClientRoots");Dg();uu();function Pg(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(`
1254
1254
  `).trim();if(r=[],i.length!==0)try{n.push(JSON.parse(i))}catch{}},"flush");for(let i of t.split(`
1255
1255
  `)){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(Pg,"rpcMessagesOf");function vR(e,t){for(let n of Pg(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 l=r.error;return{kind:"rpc_error",code:typeof l.code=="number"?l.code:-32603,message:typeof l.message=="string"?l.message:""}}let o=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(o.content)?o.content:[]).find(l=>typeof l=="object"&&l!==null&&l.type==="text"&&typeof l.text=="string");return{kind:"result",isError:o.isError===!0,text:a?.text??""}}return null}s(vR,"parseCloudToolResponse");Wt();var TW="https://mcp.maind.dev/mcp",ga=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},hu=class{static{s(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;nestedProjectKeys;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=tr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=AW(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=RW(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;let i=t.nestedProjectKeys;this.nestedProjectKeys=()=>{try{return(i?.()??[]).filter(l=>/^[a-f0-9]{64}$/.test(l)&&l!==this.projectKey)}catch{return[]}},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 a=t.carry??null;a!==null&&(this.initFrame=a.initFrame,this.clientFamily===null&&(this.clientFamily=a.clientFamily),this.clientVersion===null&&(this.clientVersion=a.clientVersion),this.replayFrame=a.pendingFrame),this.clientChannel=new lu(l=>process.stdout.write(l+`
1256
1256
  `),a!==null&&a.initFrame!==null&&(a.pendingFrame===null||!xi(a.pendingFrame))),this.shaRepoRoot=Si(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??TW,this.stackHeader=MW(this.mcpUrl)?null:$W(t.stack!==void 0?t.stack:Rn(this.shaRepoRoot??process.cwd()))}async run(t=jg()){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 hR(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=fR(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&xi(t)&&(this.initFrame=t);let r=OW(t),o=null;if(r?.method==="tools/call"){this.presence?.onActivity();let d=cu(t,this.shaRepoRoot);if(d.length>0){let p=d.find(m=>m.verdict==="fabricated"),f=p??d[0];if(p!==void 0&&kR(p)&&r.id!==null){let m=vi(p,!0);process.stderr.write(`[maind] ${m}
@@ -1270,24 +1270,24 @@ maind: sessions that are already running pick it up when their bridge restarts (
1270
1270
  `).trim();i=[],l.length>0&&o.push(l)},"flushEvent");try{for(;;){let{value:l,done:c}=await t.read();if(c)break;r+=n.decode(l,{stream:!0});let u;for(;(u=r.indexOf(`
1271
1271
  `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return o.join(`
1272
1272
  `)}s($g,"collectSseText");function fu(e){try{return JSON.parse(e).id??null}catch{return null}}s(fu,"tryExtractId");function xi(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(xi,"isInitializeRequest");function RR(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(RR,"isSessionLossBody");function CR(e){return e instanceof Error?e.message:String(e)}s(CR,"stringifyErr");function NW(e){return e?.name==="TimeoutError"}s(NW,"isTimeoutError");function mu(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
1273
- `)}s(mu,"emitJsonRpcError");function DW(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(DW,"extractHint");function PW(e){try{let t=Pg(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(PW,"parsePresenceToolResult");function MW(e){try{return new URL(e).searchParams.has("stack")}catch{return!1}}s(MW,"urlDeclaresStack");function $W(e){let t=e?ho(e):[];return t.length>0?t.join(","):null}s($W,"stackHeaderValue");we();Bg();Gg();Xe();de();Rb();xr();xr();import{readFileSync as VZ}from"node:fs";import{join as Q$}from"node:path";function Gp(e){return e?Math.ceil(e.length/4):0}s(Gp,"estimateTokens");var eL=1e6,Kp=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 tL(e){try{let t=VZ(e,"utf8");return t.length>eL?t.slice(0,eL):t}catch{return""}}s(tL,"readFileCapped");function qZ(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(qZ,"distinctFilePaths");function nL(e,t,n,r){try{let o=Gp(n);if(e==="codebase_search"){let i=qZ(t);if(i.length===0)return 0;let a=0;for(let l of i)a+=Gp(tL(Q$(r,l)));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=Gp(tL(Q$(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(nL,"measureLocalToolSaved");Me();xr();import{createHash as d7}from"node:crypto";Me();import{execFileSync as zZ}from"node:child_process";import{createHash as JZ}from"node:crypto";xr();Pk();import{realpathSync as rL}from"node:fs";function YZ(e,t){try{return rL(e)===rL(t)}catch{return e===t}}s(YZ,"samePath");var Jk=30,XZ=10,oL=20,ZZ=new Map;function Yk(e){return e instanceof Error?e.message:String(e)}s(Yk,"msg");function Wp(e){let t=e.split(`
1274
- `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Wp,"firstLine");var iL=s(e=>e?e.slice(0,12):"?","short");async function QZ(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await XM(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(l){return{ok:!1,error:Yk(l)}}},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(QZ,"refreshIndex");function e7(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(e7,"isEmptyRange");function t7(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(t7,"localOnly");function n7(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(n7,"localGradeBlockers");function r7(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=Sg(!1,e.projectKey,e.result);if(!t.persist)return t;let n=n7(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(r7,"bridgePersistDecision");function sL(e,t){try{return zZ("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(sL,"git");function o7(e,t){let n=no(e),r=n&&sL(e,["merge-base",t,`origin/${n}`])||null,o=sL(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(o7,"gitPersistFacts");function i7(e,t){return JZ("sha256").update(`${e??""}
1275
- ${JSON.stringify(t)}`).digest("hex")}s(i7,"payloadKey");function en(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(en,"fail");var Go="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function aL(e){let t=ki(e);if(t!==null&&Eg(t))return en("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 en("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 en("cloud_unavailable",`review_verdict failed: ${Wp(t?.detail??e)||"no detail"}`,Go)}s(aL,"fromProtocolText");function s7(e,t,n){switch(e.kind){case"no_session":return en("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. ${Go}`);case"transport_error":return e.timedOut?en("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."):en("cloud_unavailable",`network error: ${e.message}`,Go);case"http_error":return e.status===401?en("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Wp(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?en("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."):en("cloud_unavailable",`HTTP ${e.status}: ${Wp(e.body)}`,Go);case"rpc_error":return aL(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return aL(e.text);let r;try{r=JSON.parse(e.text)}catch{return en("cloud_unavailable",`review_verdict returned non-JSON text: ${Wp(e.text)}`,Go)}return typeof r!="object"||r===null?en("cloud_unavailable","review_verdict returned no object",Go):{kind:"verdict",body:r}}}}s(s7,"interpretOutcome");var a7="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).",l7={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"},lL=s(e=>e.map(t=>l7[t]??t).join("; "),"adviceFor");function c7(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: ${lL(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 ${iL(n)}, but this branch forks off ${o??"the default branch"} at ${iL(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(c7,"skipText");function u7(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 l=lL(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(l?`To fix: ${l}.`:"")}let o=e.reason??"",i=c7(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(u7,"recordHint");async function cL(e,t,n){let r=n.repoRoot??pt(),o=r,i=e,a=n.projectKey,l=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(l!==void 0){let ge=rs(l,r);if(ge===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(l)} 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(!YZ(ge.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=ge.repoRoot,i=n.engineFor(o),a=n.projectKeyFor?.(o)??null}}let c=typeof t.since=="string"&&t.since.length>0?t.since:void 0,u=c!==void 0&&t.include_uncommitted===!0,d=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??ZZ,m=[],h=await QZ(i,o,n.lock,m);if(h.missing)return{ok:!1,error:"index_unavailable",message:h.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 g=await i.reviewChanges(wg(c,u)),_={repo_root:o,since:c??null,include_uncommitted:c===void 0?!0:u,base_kind:g.baseKind,base_sha:g.baseSha,merge_base_sha:g.mergeBaseSha??null,head_sha:g.headSha,dirty:g.dirty};if(e7(g,c,u))return{ok:!1,error:"empty_range",message:c===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${c} \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:c})}catch(ge){let qo=Rt(An(`reviewDetectorScopes failed: ${Yk(ge)}`));b={commit:qo,local:qo},m.push(`repo-health detectors unavailable (${Yk(ge)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:v}=vg(g,b.commit);v>0&&m.push(`${v} symbol(s) exceed the server schema (name > ${ru} or qualified name > ${ou} chars) and were left out \u2014 this run is not attestation-grade.`);let S=i7(a,k),x=d&&c!==void 0&&!g.dirty&&typeof g.headSha=="string",T=r7({persistWanted:d,since:c,projectKey:a,result:g,payload:k,git:x?(n.persistFacts??o7)(o,g.headSha):null,recordedRunId:f.get(S)??null}),A={changed_files:g.changedFiles,indexed_files:g.indexedFiles,stale_files:g.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:v,risk_flags:g.riskFlags,index:{action:h.action,...h.files_parsed!==void 0?{files_parsed:h.files_parsed}:{},...h.note?{note:h.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,oL),local_only:t7(b).slice(0,oL)}},L=await n.callCloudTool("review_verdict",{attest:k,persist:T.persist,...a?{project_key:a}:{}},{timeoutMs:p}),R=s7(L,p,T.persist);if(R.kind==="error")return{ok:!1,error:R.error,message:R.message,hint:R.hint,base:_,local:A,warnings:m};let P=R.body;if(P.ok!==!0){let ge=P.error==="requires_team"||P.error==="requires_enterprise";return{ok:!1,error:P.error??"unknown_error",message:P.message??"review_verdict returned no message",hint:ge?a7:P.hint??Go,base:_,local:A,warnings:m}}if(P.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:A,warnings:m};let D=P.attest,E=P.run??null,F=E&&typeof E.id=="string"?{persisted:!0,run_id:E.id,commit_sha:E.commit_sha??null,attestation_format:E.attestation_format??null}:{persisted:!1,reason:T.skipped??P.run_note??"not_persisted",...T.detail?{detail:T.detail}:{}};F.persisted&&f.set(S,E.id);let q=typeof D?.attestation_grade=="boolean"?D.attestation_grade:null,Ue=Array.isArray(D?.grade_blockers)?D.grade_blockers:[],Ht=P.counts??{},ae=Array.isArray(P.findings)?P.findings:[],rt=`Verdict ${P.verdict??"?"}: ${Ht.block??0} block, ${Ht.warn??0} warn, ${Ht.note??0} note`+(P.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:P.verdict??null,counts:Ht,record:F,attest:D?{attestation_grade:q,grade_blockers:Ue,attestation_format:D.attestation_format??null,input_hash:D.input_hash??null,policy_hash:D.policy_hash??null,evaluated_convention_count:D.evaluated_convention_count??null,detector_coverage:D.detector_coverage??null}:null,hint:`${rt} ${u7(F,q,Ue,g.headSha)}`,findings:ae.slice(0,Jk).map(ge=>({convention_id:ge.convention_id,convention_version:ge.convention_version,severity:ge.severity,action:ge.action,...ge.downgrade_reason?{downgrade_reason:ge.downgrade_reason}:{},summary:ge.summary,matched_changed_symbols:(ge.matched_changed_symbols??[]).slice(0,XZ),matched_symbol_count:ge.matched_symbols?.length??0})),...ae.length>Jk?{findings_not_shown:ae.length-Jk}:{},detector_findings:P.detector_findings??[],policy_source:P.policy_source??null,coverage_note:xg(g,D?.evaluated_convention_count,v),base:_,local:A,warnings:m}}s(cL,"runAttestReview");var uL=(()=>{let e=Object.keys(na),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Vp(e){return d7("sha256").update(e,"utf8").digest("hex")}s(Vp,"nodeKeyHash");var p7=["module","class","interface","function","method","type_alias","enum","variable"],Xk=[{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:p7,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 "+uL+" \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 "+uL+", 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). Supabase migrations (`supabase/migrations` at any depth) are an ORDERED ledger as well as a counter: a version below the newest one on the base is refused by the cloud push after the merge unless it runs with --include-all, although git merges it cleanly. A branch migration there is an `open` finding with rule `number.out_of_order`, and `for_path` answers `verdict: \"out_of_order\"` with `newest_on_base` instead of `free` (MAIND-1007).",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" | "out_of_order" | "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. Three rules per surviving public table. `acl.missing_revoke` (exposure): (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. Since Supabase's switch on 2026-10-30 (changelog #45329) new tables get NO default grants, service_role included, so two reachability rules join it: `acl.dead_policy` \u2014 a permissive policy names `authenticated` (TO authenticated or PUBLIC) or explicitly `anon` for a command that role holds no GRANT for, so the caller gets 42501 before RLS runs; and `acl.service_role_undecided` \u2014 no GRANT and no REVOKE on the table names `service_role`, so whether the backend's service key reaches it is left to a default that no longer exists. Each rule assumes the platform default that is worst for its own question: exposure assumes the old stamp, reachability assumes none and counts only grants the migrations show (a table GRANT, or a root `ALTER DEFAULT PRIVILEGES \u2026 GRANT` in force at CREATE). Findings grade `open` when THIS branch introduces them (new table, a deleted REVOKE or GRANT, a new dead policy) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed` (any finding, of any rule), `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` or `CREATE POLICY` 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, GRANTs and policies 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."}}}}],Zk=new Map([["codebase_review_verdict","attest_review_changes"]]),mL=new Set([...Xk.map(e=>e.name),...Zk.keys()]),Qk=new Set(["attest_review_changes",...[...Zk].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function hL(e,t,n,r){if(!Qk.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 cL(e,n,r),i=Zk.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(hL,"dispatchCloudBackedTool");function dL(e){let t=e.filter(r=>r.rule==="number.out_of_order").length,n=e.length-t;return[...n>0?[`${n} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`]:[],...t>0?[`${t} migration(s) this branch adds are older than the newest on the base \u2014 the cloud push after the merge refuses them without --include-all. Rename them above it (see suggestion) before the merge.`]:[]].join(" ")}s(dL,"openHint");function He(e){return typeof e=="string"&&e.length>0?e:void 0}s(He,"str");function Ko(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Ko,"num");function pL(e){if(e===void 0)return{repoRoot:pt(),scanDirs:void 0};let t=rs(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(pL,"anchorRepo");function fL(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(fL,"dirNotFound");async function gL(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=He(n.for_path);if(o!==void 0){let d=HN(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 Tn(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,m=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),h=f===null?"no_opinion":p.taken?"taken":p.outOfOrder!==null?"out_of_order":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="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:h==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),newest_on_base:p.outOfOrder===null?null:{number:p.outOfOrder.newest,where:p.outOfOrder.sighting.where,path:p.outOfOrder.sighting.path},hint:h==="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.`:p.outOfOrder!==null?`${m(p.number)} is free, but ${p.outOfOrder.sighting.where} already holds the newer migration ${p.outOfOrder.newest} (see newest_on_base). After the merge the cloud push refuses a version below the newest it has applied, unless it runs with --include-all. Create the file as ${m(p.suggestion)} or with a fresh timestamp instead.`:`${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=rs(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=[],h=[],g=[];for(let[v,S]of d){let x=[...S],T=x.includes(""),A=await io(v,{dirs:T?void 0:x,minFiles:r});f.push({repo_root:v,dirs:T?null:x}),m.push(...A.findings),h.push(...A.facts.namespaces.map(L=>({repo_root:v,dir:L.dir,prefix:L.prefix,file_count:L.fileCount}))),g.push(...A.facts.skipped)}let _=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:h,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?h.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.":dL(_))+k}}let a=pt(),l=await e.checkNumberCollisions({minFiles:r}),c=l.findings.filter(d=>d.status==="open"),u=l.findings.filter(d=>d.status==="info");return{ok:l.ok,repo_root:a,open_count:c.length,preexisting_count:u.length,findings:c,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:l.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:l.facts.skipped,hint:(l.ok?l.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.":dL(c))+" 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:He(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"),l=o("info"),c={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...c,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{...c,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:l.length,findings:[...i,...a],preexisting:l.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=He(n.dir),o,i;if(r!==void 0){let d=rs(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=pt(),i=void 0;let a=po(o,{dirs:i,baseRef:He(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 l=a.findings.filter(d=>d.status==="open").length,c=a.findings.length-l;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).`:l===0?`No dead class introduced by this branch; ${c} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${l} dead class(es) introduced by this branch${c>0?` (plus ${c} 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=pL(He(n.dir));if(r===null)return fL("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=uo(r.repoRoot,{dirs:r.scanDirs,baseRef:He(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, GRANTs and policies 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(c=>c.status==="open"),l=o.findings.filter(c=>c.status==="info");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,base_ref:o.facts.baseRef,projects:o.facts.projects.map(c=>({dir:c.dir,migration_count:c.migrationCount,table_count:c.tableCount})),open_count:a.length,preexisting_count:l.length,findings:a,preexisting:l.map(c=>`${c.table} (${c.rule})`),skipped:o.facts.skipped,hint:(a.length===0?l.length===0?"Every table born in these migrations addresses its default grants, keeps its policies reachable and decides service_role.":`Nothing this branch introduces is open. ${l.length} pre-existing finding(s) \u2014 inventory, not a blocker.`:[["missing_revoke","unrevoked default grants (anon/authenticated keep CRUD; RLS is the only line) \u2014 add the REVOKEs"],["dead_policy","a policy without the matching GRANT (42501 before RLS runs) \u2014 grant the command or drop the policy"],["service_role_undecided","no GRANT or REVOKE naming service_role (after 2026-10-30 a new table gives the service key nothing) \u2014 grant it or revoke it explicitly"]].map(([c,u])=>[a.filter(d=>d.rule===c).length,u]).filter(([c])=>c>0).map(([c,u])=>`${c} \xD7 ${u}`).join("; ")+". Fix it in the same migration; each finding carries its exact SQL hint.")+" "+i}}case"check_migration_ledger_drift":{let r=pL(He(n.dir));if(r===null)return fL("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=hg(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:He(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"),l=a("open"),c=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:l.length,warn_count:c.length,findings:[...l,...c],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.`:`${l.length} blocking + ${c.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=He(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:He(n.kind),limit:Ko(n.limit)})).map(i=>({...i,nodeKeyHash:Vp(i.nodeKey)}))}case"codebase_trace":{let r=He(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:Ko(n.max_depth),limit:Ko(n.limit)})}case"codebase_snippet":{let r=He(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:Vp(r)}}case"codebase_map":return e.getArchitecture({topN:Ko(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:He(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ko(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:Vp(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:He(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ko(n.limit)}),o;if(n.include_history!==!1)try{o=Tm(await e.fileHistory({since:He(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:He(n.since)})}catch(c){i=Rt(An(`reviewDetectors failed: ${c instanceof Error?c.message:String(c)}`))}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},l=i.findings.filter(c=>c.baseline==="introduced"&&c.level==="open").reduce((c,u)=>c+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(c=>({name:c.name,qualified_name:c.qualifiedName,kind:c.kind,language:c.language,change:c.change,changed_line_count:c.changedLineCount,stale_index:c.staleIndex,file:c.filePath,start_line:c.startLine,node_key:c.nodeKey,node_key_hash:Vp(c.nodeKey)})),review_args:{changed_symbols:r.symbols.map(c=>({name:c.name,qualified_name:c.qualifiedName,kind:c.kind,language:c.language,change:c.change,changed_line_count:c.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:l,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) (${l} 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:He(n.since),limit:Ko(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(gL,"dispatchLocalTool");var qp=class{constructor(t=BN,n=null,r=pt,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Xk}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&mL.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=Qk.has(o)?await hL(this.getEngine(),o,i,this.ctx??void 0):await gL(this.getEngine(),o,i),l=JSON.stringify(a,null,2);return this.recordSavings(o,a,l),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}]}})}catch(a){let l=a instanceof Error?a.message:String(a),c=jN(a)?`${FN} (${l})`:`codebase tool error: ${l}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}],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=nL(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};Ti();var f7="/mcp-client-metrics-ingest",m7=4e3,h7="codebase_search_tokens_saved";async function yL(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${_a()}${f7}`,n=new AbortController,r=setTimeout(()=>n.abort(),m7);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:h7,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)}
1276
- `),!1}finally{clearTimeout(r)}}s(yL,"postSavingsMetric");mk();Mn();ha();Za();de();import{execFile as g7}from"node:child_process";var y7=64;function _L(e,t,n){if(e.size>=y7){let r=e.keys().next().value;r!==void 0&&e.delete(r)}e.set(t,n)}s(_L,"remember");var zp=class{static{s(this,"WorkRepoResolver")}agentCwd;repoRootOf;keyOf;roots=new Map;keys=new Map;constructor(t){this.agentCwd=t.agentCwd,this.repoRootOf=t.repoRootOf??_7,this.keyOf=t.keyOf??Ke}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&&_L(this.roots,t,n)),n===null)return null;let r=this.keys.get(n);return r===void 0&&(r=this.keyOf(n),r!==null&&_L(this.keys,n,r)),r===null?null:{root:n,projectKey:r}}catch{return null}}};async function _7(e){return await new Promise(t=>{g7("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(_7,"defaultRepoRootOf");Wt();Ji();Eo();import{join as b7}from"node:path";var k7="<synthetic>";function ew(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:b7(Gy,Ky(e.cwd),`${e.transcript_stem}.jsonl`)}s(ew,"transcriptPathFromSideChannel");var Jp=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??By)(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!==k7&&(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 w7}from"node:child_process";var v7=8,S7=32;function x7(e){return e.split(`
1277
- `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,S7)}s(x7,"parsePorcelain");function E7(e,t=v7){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(E7,"condenseToDirs");async function bL(e=T7){let t=await e();if(t===null)return null;let n=E7(x7(t));return n.length>0?n:null}s(bL,"deriveWorkingPaths");async function T7(){return await new Promise(e=>{w7("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(T7,"defaultGitStatus");var tw=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],A7=["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-shell-write","on-shell-changes","on-hook","on-doc-duty","on-plan-accepted",...tw],R7=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function nw(e){return e.find(t=>!t.startsWith("-"))}s(nw,"firstPositionalOf");function kL(e){let t=nw(e);return t===void 0||!R7.test(t)||A7.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(kL,"unknownSubcommandError");rw();import{basename as ML}from"node:path";js();Dt();var Pl=3e3,iw=20,Ml=3e3,C7=new Set(["Read","NotebookRead","LS"]),I7=new Set(["Glob","Grep"]),O7=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),N7=new Set(["WebFetch","WebSearch"]),D7=new Set(["Bash","Shell","bash","shell"]),EL=new Set(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"]),Ts="mcp__maind__work_object_ask_decision";function sw(e,t){if(EL.has(e)||e===Ts)return null;if(C7.has(e))return"read";if(I7.has(e))return"search";if(O7.has(e))return"edit";if(N7.has(e))return"web";if(D7.has(e)){let n=t.command;return typeof n=="string"?TL(n):"run"}return"other"}s(sw,"actionKindOf");var vL=new Set(["vitest","jest","pytest","mocha","ava","nextest","unittest","phpunit","rspec"]),P7=new Set(["npm","pnpm","yarn","bun","deno","go","cargo","make","just","turbo","nx","dotnet","mvn","gradle","gradlew","swift","mix","rake","tox","nox","python","python3"]),M7=new Set(["npx","pnpx","bunx","npm","pnpm","yarn","bun","deno","node","python","python3","uv","poetry","pipenv","hatch","pdm","rye","cargo","bundle"]),$7=new Set(["git","gh"]),SL=/^[A-Za-z][A-Za-z0-9._:-]*$/,L7=/^test(?:$|[:-])/,j7=/^--test(?:$|[=-])/;function TL(e){let t="run";for(let n of Ao(e)){let r=ud(n)[0];if(!r||r===Ha)continue;let o=r.split(" ")[0],i=n.trim().split(/\s+/),a=i.findIndex(c=>(c.split("/").pop()??c)===o),l=a>=0?i.slice(a+1):[];if(F7(o,l))return"test";$7.has(o)&&(t="git")}return t}s(TL,"bashActionKind");function F7(e,t){if(vL.has(e))return!0;let n=t.filter(r=>SL.test(r));if(e==="playwright")return n.includes("test");if(e==="node"&&t.some(r=>j7.test(r))||P7.has(e)&&n.some(r=>L7.test(r)))return!0;if(M7.has(e)){let r=t.map(o=>o.includes("/")?o.split("/").pop()??"":o).filter(o=>SL.test(o));if(r.some(o=>vL.has(o))||r.includes("playwright")&&n.includes("test"))return!0}return!1}s(F7,"isTestInvocation");var H7=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,U7=/```[\s\S]*?(?:```|$)/g;function Nr(e,t){let n=e.replace(U7," \u2026 ").replace(H7,"").replace(/[ \t]+\n/g,`
1273
+ `)}s(mu,"emitJsonRpcError");function DW(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(DW,"extractHint");function PW(e){try{let t=Pg(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(PW,"parsePresenceToolResult");function MW(e){try{return new URL(e).searchParams.has("stack")}catch{return!1}}s(MW,"urlDeclaresStack");function $W(e){let t=e?ho(e):[];return t.length>0?t.join(","):null}s($W,"stackHeaderValue");we();Bg();Gg();Xe();de();Rb();xr();xr();import{readFileSync as zZ}from"node:fs";import{join as Q$}from"node:path";function Gp(e){return e?Math.ceil(e.length/4):0}s(Gp,"estimateTokens");var eL=1e6,Kp=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 tL(e){try{let t=zZ(e,"utf8");return t.length>eL?t.slice(0,eL):t}catch{return""}}s(tL,"readFileCapped");function JZ(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(JZ,"distinctFilePaths");function nL(e,t,n,r){try{let o=Gp(n);if(e==="codebase_search"){let i=JZ(t);if(i.length===0)return 0;let a=0;for(let l of i)a+=Gp(tL(Q$(r,l)));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=Gp(tL(Q$(r,i)));return Math.max(0,a-o)}return 0}catch{return 0}}s(nL,"measureLocalToolSaved");Me();xr();import{createHash as f7}from"node:crypto";Me();import{execFileSync as YZ}from"node:child_process";import{createHash as XZ}from"node:crypto";xr();Pk();import{realpathSync as rL}from"node:fs";function ZZ(e,t){try{return rL(e)===rL(t)}catch{return e===t}}s(ZZ,"samePath");var Jk=30,QZ=10,oL=20,e7=new Map;function Yk(e){return e instanceof Error?e.message:String(e)}s(Yk,"msg");function Wp(e){let t=e.split(`
1274
+ `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}s(Wp,"firstLine");var iL=s(e=>e?e.slice(0,12):"?","short");async function t7(e,t,n,r){let o=await e.status(),i=!o.indexed||o.fileCount===0,a=await XM(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(l){return{ok:!1,error:Yk(l)}}},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(t7,"refreshIndex");function n7(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}s(n7,"isEmptyRange");function r7(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(r7,"localOnly");function o7(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(o7,"localGradeBlockers");function i7(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=Sg(!1,e.projectKey,e.result);if(!t.persist)return t;let n=o7(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(i7,"bridgePersistDecision");function sL(e,t){try{return YZ("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}s(sL,"git");function s7(e,t){let n=no(e),r=n&&sL(e,["merge-base",t,`origin/${n}`])||null,o=sL(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:o!==null&&o.length>0}}s(s7,"gitPersistFacts");function a7(e,t){return XZ("sha256").update(`${e??""}
1275
+ ${JSON.stringify(t)}`).digest("hex")}s(a7,"payloadKey");function en(e,t,n){return{kind:"error",error:e,message:t,hint:n}}s(en,"fail");var Go="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function aL(e){let t=ki(e);if(t!==null&&Eg(t))return en("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 en("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 en("cloud_unavailable",`review_verdict failed: ${Wp(t?.detail??e)||"no detail"}`,Go)}s(aL,"fromProtocolText");function l7(e,t,n){switch(e.kind){case"no_session":return en("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. ${Go}`);case"transport_error":return e.timedOut?en("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."):en("cloud_unavailable",`network error: ${e.message}`,Go);case"http_error":return e.status===401?en("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Wp(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?en("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."):en("cloud_unavailable",`HTTP ${e.status}: ${Wp(e.body)}`,Go);case"rpc_error":return aL(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return aL(e.text);let r;try{r=JSON.parse(e.text)}catch{return en("cloud_unavailable",`review_verdict returned non-JSON text: ${Wp(e.text)}`,Go)}return typeof r!="object"||r===null?en("cloud_unavailable","review_verdict returned no object",Go):{kind:"verdict",body:r}}}}s(l7,"interpretOutcome");var c7="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).",u7={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"},lL=s(e=>e.map(t=>u7[t]??t).join("; "),"adviceFor");function d7(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: ${lL(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 ${iL(n)}, but this branch forks off ${o??"the default branch"} at ${iL(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(d7,"skipText");function p7(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 l=lL(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(l?`To fix: ${l}.`:"")}let o=e.reason??"",i=d7(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(p7,"recordHint");async function cL(e,t,n){let r=n.repoRoot??pt(),o=r,i=e,a=n.projectKey,l=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(l!==void 0){let ge=rs(l,r);if(ge===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(l)} 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(!ZZ(ge.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=ge.repoRoot,i=n.engineFor(o),a=n.projectKeyFor?.(o)??null}}let c=typeof t.since=="string"&&t.since.length>0?t.since:void 0,u=c!==void 0&&t.include_uncommitted===!0,d=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??e7,m=[],h=await t7(i,o,n.lock,m);if(h.missing)return{ok:!1,error:"index_unavailable",message:h.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 g=await i.reviewChanges(wg(c,u)),_={repo_root:o,since:c??null,include_uncommitted:c===void 0?!0:u,base_kind:g.baseKind,base_sha:g.baseSha,merge_base_sha:g.mergeBaseSha??null,head_sha:g.headSha,dirty:g.dirty};if(n7(g,c,u))return{ok:!1,error:"empty_range",message:c===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${c} \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:c})}catch(ge){let qo=Rt(An(`reviewDetectorScopes failed: ${Yk(ge)}`));b={commit:qo,local:qo},m.push(`repo-health detectors unavailable (${Yk(ge)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:v}=vg(g,b.commit);v>0&&m.push(`${v} symbol(s) exceed the server schema (name > ${ru} or qualified name > ${ou} chars) and were left out \u2014 this run is not attestation-grade.`);let S=a7(a,k),x=d&&c!==void 0&&!g.dirty&&typeof g.headSha=="string",T=i7({persistWanted:d,since:c,projectKey:a,result:g,payload:k,git:x?(n.persistFacts??s7)(o,g.headSha):null,recordedRunId:f.get(S)??null}),A={changed_files:g.changedFiles,indexed_files:g.indexedFiles,stale_files:g.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:v,risk_flags:g.riskFlags,index:{action:h.action,...h.files_parsed!==void 0?{files_parsed:h.files_parsed}:{},...h.note?{note:h.note}:{}},detectors:{coverage:b.commit.coverage,findings:b.commit.local.slice(0,oL),local_only:r7(b).slice(0,oL)}},L=await n.callCloudTool("review_verdict",{attest:k,persist:T.persist,...a?{project_key:a}:{}},{timeoutMs:p}),R=l7(L,p,T.persist);if(R.kind==="error")return{ok:!1,error:R.error,message:R.message,hint:R.hint,base:_,local:A,warnings:m};let P=R.body;if(P.ok!==!0){let ge=P.error==="requires_team"||P.error==="requires_enterprise";return{ok:!1,error:P.error??"unknown_error",message:P.message??"review_verdict returned no message",hint:ge?c7:P.hint??Go,base:_,local:A,warnings:m}}if(P.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:A,warnings:m};let D=P.attest,E=P.run??null,F=E&&typeof E.id=="string"?{persisted:!0,run_id:E.id,commit_sha:E.commit_sha??null,attestation_format:E.attestation_format??null}:{persisted:!1,reason:T.skipped??P.run_note??"not_persisted",...T.detail?{detail:T.detail}:{}};F.persisted&&f.set(S,E.id);let q=typeof D?.attestation_grade=="boolean"?D.attestation_grade:null,Ue=Array.isArray(D?.grade_blockers)?D.grade_blockers:[],Ht=P.counts??{},ae=Array.isArray(P.findings)?P.findings:[],rt=`Verdict ${P.verdict??"?"}: ${Ht.block??0} block, ${Ht.warn??0} warn, ${Ht.note??0} note`+(P.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:P.verdict??null,counts:Ht,record:F,attest:D?{attestation_grade:q,grade_blockers:Ue,attestation_format:D.attestation_format??null,input_hash:D.input_hash??null,policy_hash:D.policy_hash??null,evaluated_convention_count:D.evaluated_convention_count??null,detector_coverage:D.detector_coverage??null}:null,hint:`${rt} ${p7(F,q,Ue,g.headSha)}`,findings:ae.slice(0,Jk).map(ge=>({convention_id:ge.convention_id,convention_version:ge.convention_version,severity:ge.severity,action:ge.action,...ge.downgrade_reason?{downgrade_reason:ge.downgrade_reason}:{},summary:ge.summary,matched_changed_symbols:(ge.matched_changed_symbols??[]).slice(0,QZ),matched_symbol_count:ge.matched_symbols?.length??0})),...ae.length>Jk?{findings_not_shown:ae.length-Jk}:{},detector_findings:P.detector_findings??[],policy_source:P.policy_source??null,coverage_note:xg(g,D?.evaluated_convention_count,v),base:_,local:A,warnings:m}}s(cL,"runAttestReview");var uL=(()=>{let e=Object.keys(na),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Vp(e){return f7("sha256").update(e,"utf8").digest("hex")}s(Vp,"nodeKeyHash");var m7=["module","class","interface","function","method","type_alias","enum","variable"],Xk=[{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:m7,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 "+uL+" \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 "+uL+", 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). Supabase migrations (`supabase/migrations` at any depth) are an ORDERED ledger as well as a counter: a version below the newest one on the base is refused by the cloud push after the merge unless it runs with --include-all, although git merges it cleanly. A branch migration there is an `open` finding with rule `number.out_of_order`, and `for_path` answers `verdict: \"out_of_order\"` with `newest_on_base` instead of `free` (MAIND-1007).",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" | "out_of_order" | "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. Three rules per surviving public table. `acl.missing_revoke` (exposure): (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. Since Supabase's switch on 2026-10-30 (changelog #45329) new tables get NO default grants, service_role included, so two reachability rules join it: `acl.dead_policy` \u2014 a permissive policy names `authenticated` (TO authenticated or PUBLIC) or explicitly `anon` for a command that role holds no GRANT for, so the caller gets 42501 before RLS runs; and `acl.service_role_undecided` \u2014 no GRANT and no REVOKE on the table names `service_role`, so whether the backend's service key reaches it is left to a default that no longer exists. Each rule assumes the platform default that is worst for its own question: exposure assumes the old stamp, reachability assumes none and counts only grants the migrations show (a table GRANT, or a root `ALTER DEFAULT PRIVILEGES \u2026 GRANT` in force at CREATE). Findings grade `open` when THIS branch introduces them (new table, a deleted REVOKE or GRANT, a new dead policy) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed` (any finding, of any rule), `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` or `CREATE POLICY` 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, GRANTs and policies 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."}}}}],Zk=new Map([["codebase_review_verdict","attest_review_changes"]]),mL=new Set([...Xk.map(e=>e.name),...Zk.keys()]),Qk=new Set(["attest_review_changes",...[...Zk].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function hL(e,t,n,r){if(!Qk.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 cL(e,n,r),i=Zk.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(hL,"dispatchCloudBackedTool");function dL(e){let t=e.filter(r=>r.rule==="number.out_of_order").length,n=e.length-t;return[...n>0?[`${n} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`]:[],...t>0?[`${t} migration(s) this branch adds are older than the newest on the base \u2014 the cloud push after the merge refuses them without --include-all. Rename them above it (see suggestion) before the merge.`]:[]].join(" ")}s(dL,"openHint");function He(e){return typeof e=="string"&&e.length>0?e:void 0}s(He,"str");function Ko(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Ko,"num");function pL(e){if(e===void 0)return{repoRoot:pt(),scanDirs:void 0};let t=rs(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(pL,"anchorRepo");function fL(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(fL,"dirNotFound");async function gL(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=He(n.for_path);if(o!==void 0){let d=HN(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 Tn(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,m=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),h=f===null?"no_opinion":p.taken?"taken":p.outOfOrder!==null?"out_of_order":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="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:h==="no_opinion"?null:p.taken,suggestion:m(p.suggestion),held_by:p.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),newest_on_base:p.outOfOrder===null?null:{number:p.outOfOrder.newest,where:p.outOfOrder.sighting.where,path:p.outOfOrder.sighting.path},hint:h==="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.`:p.outOfOrder!==null?`${m(p.number)} is free, but ${p.outOfOrder.sighting.where} already holds the newer migration ${p.outOfOrder.newest} (see newest_on_base). After the merge the cloud push refuses a version below the newest it has applied, unless it runs with --include-all. Create the file as ${m(p.suggestion)} or with a fresh timestamp instead.`:`${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=rs(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=[],h=[],g=[];for(let[v,S]of d){let x=[...S],T=x.includes(""),A=await io(v,{dirs:T?void 0:x,minFiles:r});f.push({repo_root:v,dirs:T?null:x}),m.push(...A.findings),h.push(...A.facts.namespaces.map(L=>({repo_root:v,dir:L.dir,prefix:L.prefix,file_count:L.fileCount}))),g.push(...A.facts.skipped)}let _=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:b.length,findings:_,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:h,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?h.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.":dL(_))+k}}let a=pt(),l=await e.checkNumberCollisions({minFiles:r}),c=l.findings.filter(d=>d.status==="open"),u=l.findings.filter(d=>d.status==="info");return{ok:l.ok,repo_root:a,open_count:c.length,preexisting_count:u.length,findings:c,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:l.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:l.facts.skipped,hint:(l.ok?l.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.":dL(c))+" 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:He(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"),l=o("info"),c={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...c,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{...c,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:l.length,findings:[...i,...a],preexisting:l.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=He(n.dir),o,i;if(r!==void 0){let d=rs(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=pt(),i=void 0;let a=po(o,{dirs:i,baseRef:He(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 l=a.findings.filter(d=>d.status==="open").length,c=a.findings.length-l;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).`:l===0?`No dead class introduced by this branch; ${c} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${l} dead class(es) introduced by this branch${c>0?` (plus ${c} 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=pL(He(n.dir));if(r===null)return fL("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let o=uo(r.repoRoot,{dirs:r.scanDirs,baseRef:He(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, GRANTs and policies 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(c=>c.status==="open"),l=o.findings.filter(c=>c.status==="info");return{ok:o.ok,verdict:o.verdict,repo_root:r.repoRoot,base_ref:o.facts.baseRef,projects:o.facts.projects.map(c=>({dir:c.dir,migration_count:c.migrationCount,table_count:c.tableCount})),open_count:a.length,preexisting_count:l.length,findings:a,preexisting:l.map(c=>`${c.table} (${c.rule})`),skipped:o.facts.skipped,hint:(a.length===0?l.length===0?"Every table born in these migrations addresses its default grants, keeps its policies reachable and decides service_role.":`Nothing this branch introduces is open. ${l.length} pre-existing finding(s) \u2014 inventory, not a blocker.`:[["missing_revoke","unrevoked default grants (anon/authenticated keep CRUD; RLS is the only line) \u2014 add the REVOKEs"],["dead_policy","a policy without the matching GRANT (42501 before RLS runs) \u2014 grant the command or drop the policy"],["service_role_undecided","no GRANT or REVOKE naming service_role (after 2026-10-30 a new table gives the service key nothing) \u2014 grant it or revoke it explicitly"]].map(([c,u])=>[a.filter(d=>d.rule===c).length,u]).filter(([c])=>c>0).map(([c,u])=>`${c} \xD7 ${u}`).join("; ")+". Fix it in the same migration; each finding carries its exact SQL hint.")+" "+i}}case"check_migration_ledger_drift":{let r=pL(He(n.dir));if(r===null)return fL("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let o=hg(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:He(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"),l=a("open"),c=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:l.length,warn_count:c.length,findings:[...l,...c],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.`:`${l.length} blocking + ${c.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=He(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:He(n.kind),limit:Ko(n.limit)})).map(i=>({...i,nodeKeyHash:Vp(i.nodeKey)}))}case"codebase_trace":{let r=He(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:Ko(n.max_depth),limit:Ko(n.limit)})}case"codebase_snippet":{let r=He(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:Vp(r)}}case"codebase_map":return e.getArchitecture({topN:Ko(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:He(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ko(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:Vp(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:He(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ko(n.limit)}),o;if(n.include_history!==!1)try{o=Tm(await e.fileHistory({since:He(n.since),limit:1}))}catch{o=void 0}let i;try{i=await e.reviewDetectors({baseRef:He(n.since)})}catch(c){i=Rt(An(`reviewDetectors failed: ${c instanceof Error?c.message:String(c)}`))}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},l=i.findings.filter(c=>c.baseline==="introduced"&&c.level==="open").reduce((c,u)=>c+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(c=>({name:c.name,qualified_name:c.qualifiedName,kind:c.kind,language:c.language,change:c.change,changed_line_count:c.changedLineCount,stale_index:c.staleIndex,file:c.filePath,start_line:c.startLine,node_key:c.nodeKey,node_key_hash:Vp(c.nodeKey)})),review_args:{changed_symbols:r.symbols.map(c=>({name:c.name,qualified_name:c.qualifiedName,kind:c.kind,language:c.language,change:c.change,changed_line_count:c.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:l,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) (${l} 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:He(n.since),limit:Ko(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(gL,"dispatchLocalTool");var qp=class{constructor(t=BN,n=null,r=pt,o=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=o}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Xk}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&mL.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=Qk.has(o)?await hL(this.getEngine(),o,i,this.ctx??void 0):await gL(this.getEngine(),o,i),l=JSON.stringify(a,null,2);return this.recordSavings(o,a,l),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}]}})}catch(a){let l=a instanceof Error?a.message:String(a),c=jN(a)?`${FN} (${l})`:`codebase tool error: ${l}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}],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=nL(t,n,r,this.repoRootCache);this.aggregator.add(o)}catch{}}};Ti();var h7="/mcp-client-metrics-ingest",g7=4e3,y7="codebase_search_tokens_saved";async function yL(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${_a()}${h7}`,n=new AbortController,r=setTimeout(()=>n.abort(),g7);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:y7,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)}
1276
+ `),!1}finally{clearTimeout(r)}}s(yL,"postSavingsMetric");mk();Mn();ha();Za();de();import{execFile as _7}from"node:child_process";var b7=64;function _L(e,t,n){if(e.size>=b7){let r=e.keys().next().value;r!==void 0&&e.delete(r)}e.set(t,n)}s(_L,"remember");var zp=class{static{s(this,"WorkRepoResolver")}agentCwd;repoRootOf;keyOf;roots=new Map;keys=new Map;constructor(t){this.agentCwd=t.agentCwd,this.repoRootOf=t.repoRootOf??k7,this.keyOf=t.keyOf??Ke}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&&_L(this.roots,t,n)),n===null)return null;let r=this.keys.get(n);return r===void 0&&(r=this.keyOf(n),r!==null&&_L(this.keys,n,r)),r===null?null:{root:n,projectKey:r}}catch{return null}}};async function k7(e){return await new Promise(t=>{_7("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(k7,"defaultRepoRootOf");Wt();Ji();Eo();import{join as w7}from"node:path";var v7="<synthetic>";function ew(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:w7(Gy,Ky(e.cwd),`${e.transcript_stem}.jsonl`)}s(ew,"transcriptPathFromSideChannel");var Jp=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??By)(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!==v7&&(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 S7}from"node:child_process";var x7=8,E7=32;function T7(e){return e.split(`
1277
+ `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,E7)}s(T7,"parsePorcelain");function A7(e,t=x7){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(A7,"condenseToDirs");async function bL(e=R7){let t=await e();if(t===null)return null;let n=A7(T7(t));return n.length>0?n:null}s(bL,"deriveWorkingPaths");async function R7(){return await new Promise(e=>{S7("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(R7,"defaultGitStatus");var tw=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"],C7=["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-shell-write","on-shell-changes","on-hook","on-doc-duty","on-plan-accepted",...tw],I7=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function nw(e){return e.find(t=>!t.startsWith("-"))}s(nw,"firstPositionalOf");function kL(e){let t=nw(e);return t===void 0||!I7.test(t)||C7.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(kL,"unknownSubcommandError");rw();import{basename as ML}from"node:path";js();Dt();var Pl=3e3,iw=20,Ml=3e3,O7=new Set(["Read","NotebookRead","LS"]),N7=new Set(["Glob","Grep"]),D7=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),P7=new Set(["WebFetch","WebSearch"]),M7=new Set(["Bash","Shell","bash","shell"]),EL=new Set(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"]),Ts="mcp__maind__work_object_ask_decision";function sw(e,t){if(EL.has(e)||e===Ts)return null;if(O7.has(e))return"read";if(N7.has(e))return"search";if(D7.has(e))return"edit";if(P7.has(e))return"web";if(M7.has(e)){let n=t.command;return typeof n=="string"?TL(n):"run"}return"other"}s(sw,"actionKindOf");var vL=new Set(["vitest","jest","pytest","mocha","ava","nextest","unittest","phpunit","rspec"]),$7=new Set(["npm","pnpm","yarn","bun","deno","go","cargo","make","just","turbo","nx","dotnet","mvn","gradle","gradlew","swift","mix","rake","tox","nox","python","python3"]),L7=new Set(["npx","pnpx","bunx","npm","pnpm","yarn","bun","deno","node","python","python3","uv","poetry","pipenv","hatch","pdm","rye","cargo","bundle"]),j7=new Set(["git","gh"]),SL=/^[A-Za-z][A-Za-z0-9._:-]*$/,F7=/^test(?:$|[:-])/,H7=/^--test(?:$|[=-])/;function TL(e){let t="run";for(let n of Ao(e)){let r=ud(n)[0];if(!r||r===Ha)continue;let o=r.split(" ")[0],i=n.trim().split(/\s+/),a=i.findIndex(c=>(c.split("/").pop()??c)===o),l=a>=0?i.slice(a+1):[];if(U7(o,l))return"test";j7.has(o)&&(t="git")}return t}s(TL,"bashActionKind");function U7(e,t){if(vL.has(e))return!0;let n=t.filter(r=>SL.test(r));if(e==="playwright")return n.includes("test");if(e==="node"&&t.some(r=>H7.test(r))||$7.has(e)&&n.some(r=>F7.test(r)))return!0;if(L7.has(e)){let r=t.map(o=>o.includes("/")?o.split("/").pop()??"":o).filter(o=>SL.test(o));if(r.some(o=>vL.has(o))||r.includes("playwright")&&n.includes("test"))return!0}return!1}s(U7,"isTestInvocation");var B7=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,G7=/```[\s\S]*?(?:```|$)/g;function Nr(e,t){let n=e.replace(G7," \u2026 ").replace(B7,"").replace(/[ \t]+\n/g,`
1278
1278
  `).replace(/\n{3,}/g,`
1279
1279
 
1280
1280
  `).trim();if(n.length===0)return null;let r=Array.from(n);return r.length<=t?n:`${r.slice(0,Math.max(1,t-1)).join("").trimEnd()}\u2026`}s(Nr,"excerpt");function Zp(e,t){let n=[];for(let r of e){let o=n[n.length-1];if(r.type==="thought"){if(!t.textAllowed)continue;let a=Nr(r.text,2e3);if(!a)continue;o&&o.type==="thought"&&o.body?n[n.length-1]={type:"thought",body:Nr(`${o.body}
1281
1281
 
1282
- ${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?Nr(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(Zp,"drainItems");function Dr(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 l=a;l>0;l-=1e4)o.push({type:"action",kind:i,count:Math.min(l,1e4)});return o.push(...r),o}s(Dr,"coalesceItems");var aw={steps:[]};function Bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(Bn,"isRecord");function ow(e){return e==="in_progress"||e==="completed"||e==="canceled"?e:"pending"}s(ow,"stepStatus");function Xp(e){return typeof e=="string"?e:""}s(Xp,"contentOf");function lw(e,t,n,r){if(t==="TodoWrite"){let o=n.todos;return Array.isArray(o)?{steps:o.filter(Bn).map(i=>({id:null,content:Xp(i.content),status:ow(i.status)}))}:null}if(t==="TaskCreate"){let o=Bn(r)&&Bn(r.task)?r.task:null,i=o&&typeof o.id=="string"?o.id:null,a=Xp(n.subject)||Xp(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:ow(n.status)})}}if(t==="TaskList"){let o=Bn(r)?r.tasks:null;return Array.isArray(o)?{steps:o.filter(Bn).map(i=>({id:typeof i.id=="string"?i.id:null,content:Xp(i.subject),status:ow(i.status)}))}:null}return null}s(lw,"applyPlanTool");function cw(e,t){return e.steps.slice(0,30).map(n=>{let r=t?Nr(n.content,200):null;return r?{content:r,status:n.status}:{status:n.status}})}s(cw,"wirePlan");var B7=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xL(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(xL,"parseJsonLoose");function AL(e){return typeof e=="string"?[xL(e)]:Array.isArray(e)?e.flatMap(t=>Bn(t)&&t.type==="text"&&typeof t.text=="string"?[xL(t.text)]:[]):Bn(e)?Array.isArray(e.content)?AL(e.content):[e]:[]}s(AL,"jsonCandidates");function uw(e){for(let t of AL(e)){if(!Bn(t)||t.ok!==!0||!Bn(t.decision))continue;let n=t.decision.id;if(typeof n=="string"&&B7.test(n))return{id:n.toLowerCase(),answered:t.answered===!0}}return null}s(uw,"decisionFrom");function dw(e){let t=e.question;return typeof t=="string"&&t.trim().length>0?t:null}s(dw,"questionOf");function pw(e){return e.length>=9&&e.length<=2048&&/^https:\/\/[^/?#@\s\p{Cc}]+([/?#][^\s\p{Cc}]*)?$/u.test(e)}s(pw,"isAllowedLinkUrl");function fw(e,t){return e.slice(0,10).map(n=>{let r=t?Nr(n.label,60):null;return r?{url:n.url,label:r}:{url:n.url}})}s(fw,"wireLinks");var As=30,RL=600-2*As,Qp=10;function $l(e,t){let n=Math.max(0,t-e.at)*RL/36e5;return Math.min(As,e.tokens+n)}s($l,"bucketLevel");function Ll(e,t,n){return{tokens:$l(e,n)-t,at:n}}s(Ll,"bucketTake");function Rs(e){return/^[a-z][a-z0-9_]{0,39}$/.test(e)?e:"other"}s(Rs,"failureCode");js();function hw(e){return new Promise(t=>{setTimeout(t,e).unref?.()})}s(hw,"timerDelay");async function gw(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(gw,"timerDeadline");var CL=1e4,IL=1e3,OL=15e3,mw=3,NL=20,DL=200,G7=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"]),K7=new Set(["session_ended","agent_session_not_found","invalid_key","auth_rejected","dev_mode_disabled","unknown_tool"]);function yw(e,t,n){let r=e.startActivities??[],o=e.finalResponse??"always",i=null,a=null,l=0,c=null,u=!1,d=!1,p=!1,f=null,m=null,h=Promise.resolve(),g=!1,_=[],b=null,k=new Map,v=new Map,S=aw,x=!1,T=null,A=e.summary??null,L=[],R=!1,P=!1,D=null,E={tokens:As,at:n.now()},F=0,q=!1,Ue=0,Ht=0,ae=0,rt=0,ge=null,qo={},$r=s(O=>{let $=Rs(O);qo[$]=(qo[$]??0)+1},"fail"),zo=s(O=>{c||(c=Rs(O))},"stop"),Hw=s(O=>{F=n.now()+Math.max(1,O??60)*1e3,E={tokens:As,at:F},q=!0},"obeyRateLimit"),Uw=s(O=>{h=h.then(O).catch(()=>$r("internal"))},"enqueue"),Gn=s(()=>{p||c||g||(g=!0,Uw(async()=>{g=!1,await Kw(!1)}))},"requestFlush"),Bw=s(async O=>{try{let $=await n.deadline(O(),CL);return $.done?$.value:{ok:!1,error:"timeout",retryAfterSeconds:null,transient:!0}}catch{return{ok:!1,error:"unreachable",retryAfterSeconds:null,transient:!0}}},"attempt"),Os=s(async O=>{let $=await Bw(O);return!$.ok&&$.transient&&($r($.error),await n.delay(IL),$=await Bw(O)),$.ok?(Ue=0,$):($r($.error),$.transient?(Ue+=1,Ue>=NL&&zo("unreachable")):G7.has($.error)&&(zo($.error),K7.has($.error)&&(u=!0)),$)},"call"),Gw=s(async()=>{if(i||c)return;if(l>=mw){zo("start_failed");return}l+=1;let O=await Os(()=>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"&&zo(O.error),l>=mw&&zo("start_failed");return}if(!O.agentSessionId){zo("invalid_response");return}i=O.agentSessionId,a=O.textStored===!0;let $=O.appended??0;if($>0){Ht+=$,E=Ll(E,$,n.now());let te=r[r.length-1];D=te&&te.ephemeral===!0&&te.action?te.action:null}(a||T!==null||L.length>0)&&(R=!0)},"ensureStarted"),wF=s(async()=>{if(!i||c||!R)return;R=!1;let O=a&&!P&&A!==null?Nr(A,255):null,$=fw(L,a===!0);if(T===null&&O===null&&$.length===0)return;let te=A,xe=await Os(()=>t.start({projectKey:e.projectKey,sessionId:e.sessionId,objectId:e.objectId,...T!==null?{model:T}:{},...O!==null?{summary:O}:{},...$.length>0?{links:$}:{}}));if(xe.ok){O!==null&&A===te&&(P=!0);return}xe.transient&&(R=!0)},"sendHeader"),vF=s(O=>{let $=null;for(let te of k.values())te.kind!==null&&O-te.at>=Ml&&(!$||te.at>$.at)&&($={kind:te.kind,at:te.at});for(let te of v.values())O-te.at>=Ml&&(!$||te.at>$.at)&&($=te);return $?$.kind:null},"currentEphemeral"),SF=s(async O=>{if(!i||c)return;let $=n.now();if(!O&&$<F)return;let te=_.splice(0,_.length),xe=q?Dr(te):te,Ut=O?null:vF($),hf=Ut!==null&&(xe.length>0||Ut!==D),Ww=a===!0,ot=Zp(xe,{textAllowed:Ww,ephemeral:hf?Ut:null});if(ot.length===0)return;let Vw=$l(E,$),qw=O?Vw:Vw-Qp;if(ot.length>qw||ot.length>50){let Jo=Zp(Dr(xe),{textAllowed:Ww,ephemeral:hf?Ut:null});if(!O&&Jo.length>qw){_.unshift(...Dr(xe));return}ot=Jo}ot.length>50&&(rt+=ot.length-50,ot=ot.slice(ot.length-50));let EF=i,Kl=await Os(()=>t.append({projectKey:e.projectKey,agentSessionId:EF,activities:ot}));if(Kl.ok){Ht+=ot.length,E=Ll(E,ot.length,n.now()),q=!1;let Jo=ot[ot.length-1];D=Jo.ephemeral===!0&&Jo.action?Jo.action:null;return}if(!O&&Kl.error==="rate_limited"){Hw(Kl.retryAfterSeconds),_.unshift(...Dr(xe));return}if(!O&&Kl.transient&&!c){_.unshift(...Dr(xe));return}rt+=xe.length},"sendActivities"),xF=s(async O=>{if(!i||c||!x)return;let $=n.now();if(!O&&$<F||!O&&$l(E,$)-Qp<1)return;x=!1;let te=i,xe=await Os(()=>t.plan({projectKey:e.projectKey,agentSessionId:te,plan:cw(S,a===!0)}));if(xe.ok){ae+=1,E=Ll(E,1,n.now());return}xe.error==="rate_limited"&&Hw(xe.retryAfterSeconds),!O&&(xe.transient||xe.error==="rate_limited")&&(x=!0)},"sendPlan"),Kw=s(async O=>{c||!i&&(await Gw(),!i)||(await wF(),await SF(O),await xF(O))},"flushOnce"),mf=s(()=>{if(_.length<=DL)return;let O=Dr(_);_.length=0,_.push(...O)},"capPending"),Gl=s(()=>{b!==null&&(_.push({type:"thought",text:b}),b=null)},"flushThought");return{begin(){p||d||(d=!0,Uw(Gw),m=n.every(Pl,Gn))},onEvent(O){if(!(p||c))try{if(O.kind==="text"){if(O.subagent)return;Gl(),b=O.text}else if(O.kind==="tool_start")O.subagent||Gl(),k.set(O.id,{tool:O.tool,input:O.input,kind:sw(O.tool,O.input),at:n.now(),subagent:O.subagent});else{let $=k.get(O.id);if(!$)return;if(k.delete(O.id),$.kind!==null)_.push({type:"action",kind:$.kind,count:1});else if($.tool===Ts){let te=O.failed?null:uw(O.output);_.push(te&&!te.answered?{type:"elicitation",decisionId:te.id,text:dw($.input)}:{type:"action",kind:"other",count:1})}else if(!$.subagent&&!O.failed){let te=lw(S,$.tool,$.input,O.output);te&&(S=te,x=!0)}}mf(),_.length>=iw&&Gn()}catch{$r("internal")}},setModel(O){if(p||c)return;let $=O.trim().slice(0,100);$.length===0||$===T||(T=$,R=!0,Gn())},setSummary(O){if(p||c)return;let $=O.trim();$.length===0||$===A||(A=$,P=!1,R=!0,Gn())},addLink(O){p||c||!pw(O.url)||L.some($=>$.url===O.url)||(L.push({url:O.url,label:O.label}),R=!0,Gn())},step(O,$,te){if(!(p||c)){if(te==="start")v.set(O,{kind:$,at:n.now()-Ml});else{let xe=v.get(O);if(!xe)return;v.delete(O),_.push({type:"action",kind:xe.kind,count:1})}Gn()}},elicit(O){if(!(p||c))try{Gl(),_.push({type:"elicitation",decisionId:null,text:O}),mf(),Gn()}catch{$r("internal")}},endTurn(){p||c||b!==null&&(_.push({type:"response",text:b,textOnly:!0}),b=null,mf(),Gn())},close(O){return f||(p=!0,m?.clear(),d?(f=(async()=>{try{for(let Ut of k.values())Ut.kind!==null&&_.push({type:"action",kind:Ut.kind,count:1});k.clear();for(let Ut of v.values())_.push({type:"action",kind:Ut.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}):(Gl(),_.push({type:"error",text:O.reasonText??null})),b=null;let te=(async()=>{if(await h,await Kw(!0),!i||u)return;let Ut=i;(await Os(()=>t.end({projectKey:e.projectKey,agentSessionId:Ut,endState:$}))).ok&&(ge=$)})();(await n.deadline(te,OL)).done||$r("close_timeout")}catch{$r("internal")}rt+=_.length,_.length=0})(),f):(f=Promise.resolve(),f))},record(){return{agentSessionId:i,textStored:a,sent:Ht,plans:ae,dropped:rt,endState:ge,failures:{...qo},stoppedBy:c}}}}s(yw,"makeActivityReporter");var _w="work_object_report_activity",W7=new Set(["rpc_failed","session_not_announced"]);function bw(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"?Rs(t.error):"invalid_response";return{ok:!1,error:n,retryAfterSeconds:typeof t.retry_after_seconds=="number"?t.retry_after_seconds:null,transient:W7.has(n)}}s(bw,"activityAnswerFrom");var jl={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 kw(e){return{start:s(t=>e(jl.start(t)),"start"),append:s(t=>e(jl.append(t)),"append"),plan:s(t=>e(jl.plan(t)),"plan"),end:s(t=>e(jl.end(t)),"end")}}s(kw,"activityTransportFrom");_r();var V7="AskUserQuestion",q7=/^mcp__.+__work_object_ask_decision$/,z7="<synthetic>",J7=new Set(["end_turn","stop_sequence","max_tokens","refusal"]),Y7=new Set(["stop_hook_summary","turn_duration"]);function Wo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(Wo,"isRecord");function X7(e){let t=e.questions;if(Array.isArray(t)){let r=t.filter(Wo).map(o=>o.question).filter(o=>typeof o=="string"&&o.trim().length>0);if(r.length>0)return r.join(`
1283
- `)}let n=e.question;return typeof n=="string"&&n.trim().length>0?n:null}s(X7,"questionText");var Fl=class{static{s(this,"TranscriptEventMapper")}turnEnding=!1;questions=new Set;lastModel=null;lastTitle=null;map(t){try{if(!Wo(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"&&Y7.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(!Wo(n))return[];let r=[],o=n.model;typeof o=="string"&&o.length>0&&o!==z7&&o!==this.lastModel&&(this.lastModel=o,r.push({kind:"model",model:o}));let i=n.content;if(Array.isArray(i)){for(let l of i)if(Wo(l)){if(l.type==="text"){let c=l.text;typeof c=="string"&&c.trim().length>0&&r.push({kind:"text",text:c,subagent:!1})}else if(l.type==="tool_use"){let c=l.id,u=l.name;if(typeof c!="string"||typeof u!="string")continue;let d=Wo(l.input)?l.input:{};if(this.turnEnding=!1,u===V7){this.questions.add(c),r.push({kind:"question",text:X7(d)});continue}r.push({kind:"tool_start",id:c,tool:q7.test(u)?Ts:u,input:d,subagent:!1})}}}let a=n.stop_reason;return typeof a=="string"&&(this.turnEnding=J7.has(a)),r}user(t){if(t.isMeta===!0||t.isCompactSummary===!0||t.isVisibleInTranscriptOnly===!0)return[];let n=t.message,r=Wo(n)?n.content:void 0,o=Array.isArray(r)?r.filter(l=>Wo(l)&&l.type==="tool_result"&&typeof l.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 l of o){let c=l.tool_use_id;this.questions.delete(c)||a.push({kind:"tool_end",id:c,failed:l.is_error===!0,output:i!==void 0?i:l.content??null,subagent:!1})}return a}};import{open as Z7,stat as Q7}from"node:fs/promises";var eQ={async stat(e){try{let t=await Q7(e);return{size:t.size,id:`${t.dev}:${t.ino}`}}catch{return null}},async read(e,t,n){let r=await Z7(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()}}},tQ=4*1024*1024,nQ=16*1024*1024,PL=10,ef=class{constructor(t=eQ,n=tQ,r=nQ){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]!==PL}catch{this.skipToNewline=!0}}clearPartial(){this.partial=[],this.partialBytes=0}consume(t){let n=[],r=0;for(;;){let i=t.indexOf(PL,r);if(i===-1)break;let a=t.subarray(r,i);if(r=i+1,this.skipToNewline){this.skipToNewline=!1,this.clearPartial();continue}let l=this.partialBytes>0?Buffer.concat([...this.partial,a]):a;if(this.clearPartial(),l.length>this.maxLine)continue;let c=rQ(l);c!==void 0&&n.push(c)}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 rQ(e){let t=e.toString("utf8").trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}s(rQ,"parseLine");var oQ=Pl,iQ=2e3,sQ=5*6e4,aQ=10,lQ=new Set(["unknown_tool","invalid_params","dev_mode_disabled","invalid_key","auth_rejected"]),cQ={now:s(()=>Date.now(),"now"),every:s((e,t)=>{let n=setInterval(t,e);return n.unref?.(),{clear:s(()=>clearInterval(n),"clear")}},"every"),delay:hw,deadline:gw},tf=class{constructor(t){this.deps=t;this.clock=t.clock??cQ,this.tail=t.tail??new ef,this.log=t.log??(n=>process.stderr.write(n+`
1284
- `))}static{s(this,"ActivityProducer")}clock;tail;log;mapper=new Fl;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(oQ,()=>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=iQ){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&&ML(this.path)===ML(n)||(this.retire(),this.mapper=new Fl,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<aQ&&!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=yw({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 ${el(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&&(lQ.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()+sQ),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{}}}};_r();Me();var uQ=1e4,Pr=s((e,t)=>({ok:!1,error:e,retryAfterSeconds:null,transient:t}),"answer");function dQ(e){switch(e.kind){case"no_session":return Pr("no_session",!0);case"transport_error":return Pr(e.timedOut?"timeout":"unreachable",!0);case"http_error":return e.status===401?Pr("auth_rejected",!1):e.status>=400&&e.status<500&&e.status!==408&&e.status!==429?Pr(`http_${e.status}`,!1):Pr("unreachable",!0);case"rpc_error":{let t=ki(`MCP error ${e.code}: ${e.message}`);return Pr(t?.kind??"tool_error",!1)}case"result":{if(e.isError){let n=ki(e.text);if(n!==null)return Pr(n.kind,!1)}let t=null;try{t=JSON.parse(e.text)}catch{t=null}return bw(t)}}}s(dQ,"activityAnswerFromOutcome");function $L(e){return kw(async t=>{try{return dQ(await e(_w,t,{timeoutMs:uQ}))}catch{return Pr("unreachable",!0)}})}s($L,"bridgeActivityTransport");H_();B_();var pQ=6e4,LL=2*60*6e4,fQ=5*6e4,mQ=24*60*6e4,hQ=3e4,gQ=15e3,yQ=3,nf=class{constructor(t){this.deps=t;this.startIso=new Date(this.now()).toISOString()}static{s(this,"ThreadWatcher")}busy=!1;startIso;lastError=null;timer=null;nudgeTimer=null;wasIdle=!1;lastIdleReadAt=null;now(){return(this.deps.now??Date.now)()}start(t=pQ){this.timer!==null||this.deps.projectKey===null||(this.timer=setInterval(()=>void this.tick(),t),this.timer.unref(),this.nudgeTimer=setInterval(()=>this.nudge(),hQ),this.nudgeTimer.unref())}stop(){this.timer!==null&&clearInterval(this.timer),this.nudgeTimer!==null&&clearInterval(this.nudgeTimer),this.timer=null,this.nudgeTimer=null}nudge(){if(!this.wasIdle)return;let t=this.deps.activityAtMs();t===null||this.now()-t>LL||this.tick()}note(t){t!==this.lastError&&(this.lastError=t,this.deps.log?.(`maind-bridge: reading the work object's thread failed (${t}) \u2014 next poll retries.`))}async tick(){if(!this.busy){this.busy=!0;try{let t=this.deps.projectKey,n=this.deps.sessionId();if(t===null||!n)return;let r=this.now(),o=this.deps.activityAtMs(),i=o!==null&&r-o>LL;this.wasIdle=i;let l=(this.deps.readState??Sd)(t,n,this.deps.baseDir)??{v:1,written_at:this.startIso,session_id:n,items:[],since:{},stamped:[]},c={...l.awaiting??{}},u=!1;for(let[m,h]of Object.entries(c)){let g=Date.parse(h.since);(Number.isNaN(g)||r-g>mQ)&&(delete c[m],u=!0)}let d=Object.entries(c).map(([m,h])=>({id:m,key:h.key}));if(i)d.length>0&&(this.lastIdleReadAt!==null&&r-this.lastIdleReadAt<fQ?d.length=0:this.lastIdleReadAt=r);else for(let m of this.deps.boundObjects()??[])d.some(h=>h.id===m.id)||d.push({id:m.id,key:m.key});d.splice(yQ);let p=(this.deps.readTold??((m,h)=>xd(m,h,this.deps.baseDir)))(t,n);for(let m of d){let h=l.since[m.id]??c[m.id]?.since??this.startIso,g=p.delivered.filter(S=>S.objectId===m.id&&!l.stamped.includes(S.id)).map(S=>S.id).slice(0,20),_=await this.deps.call("work_object_read_comments",{project_key:t,session_id:n,object_id:m.id,since:h,audience:"holder",...g.length>0?{delivered_ids:g}:{}},{timeoutMs:gQ});if(_.kind!=="result"){this.note(_.kind);continue}if(_.isError){this.note("tool_error");continue}let b=oO(_.text,m.id,m.key);if(!b.ok){this.note(b.error);continue}this.lastError=null,g.length>0&&l.stamped.push(...g);let k=new Set(l.items.map(S=>S.id)),v=b.items.filter(S=>!k.has(S.id));l.items.push(...v),b.newest!==null&&(l.since[m.id]=b.newest),u=u||v.length>0||g.length>0||b.newest!==null,b.openQuestions!==null&&b.openQuestions>0&&c[m.id]===void 0?(c[m.id]={key:m.key,since:new Date(r).toISOString()},u=!0):b.openQuestions===0&&c[m.id]!==void 0&&(delete c[m.id],u=!0)}if(!u)return;l.awaiting=c;let f=new Set(p.told);l.items=l.items.filter(m=>!f.has(m.id)),l.written_at=new Date(this.now()).toISOString(),(this.deps.writeState??uO)(t,l,this.deps.baseDir,this.now())}catch(t){this.note(t instanceof Error?t.message:String(t))}finally{this.busy=!1}}}};var Jee=1;function Yee(e){return tw.includes(e)}s(Yee,"isHookSubcommand");var Xee=6e4;async function Zee(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==ee()&&yo(e),e;let t=ee();if(t!==null)return t;let n=await Ai(K);return n===null&&(_o("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:K}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1285
- `),process.exit(1)),_o("paired",null,{version:K}),n.apiKey}s(Zee,"ensureApiKey");async function Qee(e){let t=await Ai(K);return t===null&&(_o("auth_failed",`${e}; re-authorization did not complete`,{version:K}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1286
- `),process.exit(1)),_o("paired",null,{version:K}),t.apiKey}s(Qee,"reauth");async function ete(){let e=nw(process.argv.slice(2)),t=kL(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1287
- `),process.exit(2)),e==="install"){let E=process.argv.indexOf("install"),F=process.argv.slice(E+1),q=await Y$(F);process.exit(q)}if(e==="refresh-rules"){let{runRefreshRules:E}=await Promise.resolve().then(()=>(Bp(),zk));process.exit(await E(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:E}=await Promise.resolve().then(()=>(Ob(),AD));process.exit(await E(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:E}=await Promise.resolve().then(()=>(Dk(),Nk));process.exit(await E())}if(e==="session-end-run"){let{runSessionEndWorker:E}=await Promise.resolve().then(()=>(Ok(),UM));process.exit(await E())}if(e==="on-hook"){let{hooksFromArgv:E,runHooks:F}=await Promise.resolve().then(()=>(Oe(),Uo)),q=process.argv.slice(process.argv.indexOf("on-hook")+1);process.exit(await F(E(q),q))}if(e==="on-session-briefing"){let{runOnSessionBriefing:E}=await Promise.resolve().then(()=>(Gb(),Bb));process.exit(await E())}if(e==="on-session-reminder"){let{runOnSessionReminder:E}=await Promise.resolve().then(()=>(E_(),x_));process.exit(await E())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:E}=await Promise.resolve().then(()=>(VL(),WL));process.exit(await E())}if(e==="guard"){let E=process.argv.indexOf("guard"),{runGuard:F}=await Promise.resolve().then(()=>(tj(),ej));process.exit(await F(process.argv.slice(E+1)))}if(e==="guard-inject"){let{runGuardInject:E}=await Promise.resolve().then(()=>(Po(),QO));process.exit(await E())}if(e==="guard-gate"){let{runGuardGate:E}=await Promise.resolve().then(()=>(sj(),ij));process.exit(await E())}if(e==="guard-stop"){let{runGuardStop:E}=await Promise.resolve().then(()=>(cj(),lj));process.exit(await E())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="guard-capture"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="guard-consult"){let{runGuardConsult:E}=await Promise.resolve().then(()=>(cf(),lf));process.exit(await E())}if(e==="guard-prompt-mark"){let{runGuardPromptMark:E}=await Promise.resolve().then(()=>(cf(),lf));process.exit(await E())}if(e==="guard-skip-note"){let{runGuardSkipNote:E}=await Promise.resolve().then(()=>(cf(),lf));process.exit(await E())}if(e==="gateway"){let E=process.argv.indexOf("gateway"),{runGateway:F}=await Promise.resolve().then(()=>(uF(),cF));process.exit(await F(process.argv.slice(E+1)))}if(e==="activity"){let{runActivity:E}=await Promise.resolve().then(()=>(fF(),pF));process.exit(await E(process.argv.slice(process.argv.indexOf("activity")+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:E}=await Promise.resolve().then(()=>(Fw(),jw));process.exit(await E())}if(e==="guard-cross-check"){let{runGuardCrossCheck:E}=await Promise.resolve().then(()=>(Fw(),jw));process.exit(await E())}if(e==="on-index-refresh"){let{runOnIndexRefresh:E}=await Promise.resolve().then(()=>(Np(),Op));process.exit(await E())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:E}=await Promise.resolve().then(()=>(Np(),Op));process.exit(await E())}if(e==="on-doc-duty"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="on-prompt-context"){let{runOnPromptContext:E}=await Promise.resolve().then(()=>(Tl(),El));process.exit(await E())}if(e==="on-read-context"){let{runOnReadContext:E}=await Promise.resolve().then(()=>(Tl(),El));process.exit(await E())}if(e==="on-shell-write"||e==="on-shell-changes"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="on-plan-accepted"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e!==void 0&&Yee(e)){let E=await Promise.resolve().then(()=>(Lt(),gs)),F={"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 F())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(K+`
1288
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(tte(),process.exit(0)),process.argv.includes("--reauth")&&(ya(),await Ai(K,process.stdout)===null&&process.exit(1),_o("paired",null,{version:K}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1289
- `),process.exit(0));let n=ke(),r=await Zee(),o=Z(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Kp:null,l=null,c=new Map,u=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new qp(void 0,a,void 0,{callCloudTool:s((E,F,q)=>l===null?Promise.resolve({kind:"no_session"}):l.callCloudTool(E,F,q),"callCloudTool"),projectKey:o,engineFor:s(E=>{let F=c.get(E);return F===void 0&&(F=GN(E),c.set(E,F)),F},"engineFor"),projectKeyFor:Ke}),d=`bridge-${zee()}`,p=s(async()=>{if(!a)return;let E=a.takePending();E.tokens<=0||await yL({apiKey:r,deviceId:n,sessionId:d,tokensSaved:E.tokens,bridgeVersion:K})},"flushSavings"),f=a?setInterval(()=>{p()},Xee):null;f?.unref();let m=new Ad({projectKey:o}),h=new Jp({resolvePath:s(()=>ew(m.sideChannel()),"resolvePath"),fallbackModel:s(()=>m.sideChannel()?.model??null,"fallbackModel")}),g=new su,_=null,b=s(()=>(_===null&&(_=o!==null?Xa(gt(),o):[]),_),"nestedRepos"),k=s(E=>b().find(F=>F.projectKey===E)?.dir??null,"nestedDirOf"),v=new zp({agentCwd:s(()=>m.sideChannel()?.cwd??null,"agentCwd")}),S=null,x=new Tp({projectKey:o,identity:m,sessionMeta:s(()=>h.read(),"sessionMeta"),postToolCall:s((E,F)=>l===null?Promise.reject(new Error("presence: no active forwarder")):l.postPresenceToolCall(E,F),"postToolCall"),deriveWorkingPaths:s(()=>bL(),"deriveWorkingPaths"),snapshot:o!==null?nte(qI({projectKey:o}),g,k):void 0,nestedProjectKeys:s(()=>b().map(E=>E.projectKey),"nestedProjectKeys"),workRepo:s(()=>v.current(),"workRepo"),editRoots:s(()=>gO(m.sideChannel()),"editRoots"),onAnnounced:s(()=>S?.refresh(),"onAnnounced")});S=new tf({enabled:Yp().enabled&&x.isEnabled,projectKey:o,sessionId:s(()=>x.sessionId,"sessionId"),transcriptPath:s(()=>ew(m.sideChannel()),"transcriptPath"),target:s(()=>yr({branchObjectId:x.branchObjectId(),boundObjects:x.boundObjects()}),"target"),transport:$L((E,F,q)=>l===null?Promise.resolve({kind:"no_session"}):l.callCloudTool(E,F,q))});let T=x.isEnabled?setInterval(()=>{x.pollActivity()},uM):null;T?.unref();let A=x.isEnabled?new nf({projectKey:o,sessionId:s(()=>x.sessionId,"sessionId"),boundObjects:s(()=>x.boundObjects(),"boundObjects"),activityAtMs:s(()=>m.activityAtMs(),"activityAtMs"),call:s((E,F,q)=>l===null?Promise.resolve({kind:"no_session"}):l.callCloudTool(E,F,q),"call"),log:s(E=>process.stderr.write(`${E}
1290
- `),"log")}):null;if(A?.start(),x.isEnabled){let E=s(F=>{(S?.shutdown()??Promise.resolve()).then(()=>x.end()).finally(()=>process.exit(F))},"endAndExit");process.on("SIGTERM",()=>E(143)),process.on("SIGINT",()=>E(130))}let L=!1,R=s(E=>{if(L)return;L=!0;let F=s(()=>l?.listClientRoots()??Promise.resolve(null),"listRoots");setTimeout(()=>{Promise.resolve().then(()=>(jp(),K$)).then(({refreshAgentsMdForSession:Ue})=>Ue(E,{apiKey:r,projectKey:o,listRoots:F})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(Bp(),zk))).then(({refreshRulesForSession:Ue})=>Ue(E,{apiKey:s(()=>r,"apiKey"),listRoots:F})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),P=0,D=jg();try{for(;;){let E=l?.carryOver()??null,F=new hu({apiKey:r,deviceId:n,bridgeVersion:K,projectKey:o,nestedProjectKeys:s(()=>b().map(q=>q.projectKey),"nestedProjectKeys"),localRouter:u,presence:x,onConnectionOutcome:s((q,Ue)=>_o(q,Ue,{version:K}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:q})=>R(q),"onSessionReady"),assignedInbox:g,carry:E});l=F;try{await F.run(D);return}catch(q){if(q instanceof ga&&P<Jee){P+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${q.message}; re-authorizing\u2026
1291
- `),r=await Qee(q.reason);continue}throw q}}}finally{f&&clearInterval(f),T&&clearInterval(T),A?.stop(),await S?.shutdown(),await x.end(),await p()}}s(ete,"main");function tte(){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-shell-write before a Bash call: the literal files its command line writes get the file hooks' checks (MAIND-892; may refuse a taken number)"," on-shell-changes after a Bash call: files it changed that its command line did not name, via git status (MAIND-892, never blocks)"," on-plan-accepted after ExitPlanMode: a note to attach the accepted plan to its work object (MAIND-1189, 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|gemini-cli|...)"," 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(`
1292
- `))}s(tte,"printHelp");ete().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1293
- `),process.exit(1)});function nte(e,t,n){return{...e,write(r,o){let i=r;try{i=dR(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(nte,"withAssignedCapture");
1282
+ ${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?Nr(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(Zp,"drainItems");function Dr(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 l=a;l>0;l-=1e4)o.push({type:"action",kind:i,count:Math.min(l,1e4)});return o.push(...r),o}s(Dr,"coalesceItems");var aw={steps:[]};function Bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(Bn,"isRecord");function ow(e){return e==="in_progress"||e==="completed"||e==="canceled"?e:"pending"}s(ow,"stepStatus");function Xp(e){return typeof e=="string"?e:""}s(Xp,"contentOf");function lw(e,t,n,r){if(t==="TodoWrite"){let o=n.todos;return Array.isArray(o)?{steps:o.filter(Bn).map(i=>({id:null,content:Xp(i.content),status:ow(i.status)}))}:null}if(t==="TaskCreate"){let o=Bn(r)&&Bn(r.task)?r.task:null,i=o&&typeof o.id=="string"?o.id:null,a=Xp(n.subject)||Xp(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:ow(n.status)})}}if(t==="TaskList"){let o=Bn(r)?r.tasks:null;return Array.isArray(o)?{steps:o.filter(Bn).map(i=>({id:typeof i.id=="string"?i.id:null,content:Xp(i.subject),status:ow(i.status)}))}:null}return null}s(lw,"applyPlanTool");function cw(e,t){return e.steps.slice(0,30).map(n=>{let r=t?Nr(n.content,200):null;return r?{content:r,status:n.status}:{status:n.status}})}s(cw,"wirePlan");var K7=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xL(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(xL,"parseJsonLoose");function AL(e){return typeof e=="string"?[xL(e)]:Array.isArray(e)?e.flatMap(t=>Bn(t)&&t.type==="text"&&typeof t.text=="string"?[xL(t.text)]:[]):Bn(e)?Array.isArray(e.content)?AL(e.content):[e]:[]}s(AL,"jsonCandidates");function uw(e){for(let t of AL(e)){if(!Bn(t)||t.ok!==!0||!Bn(t.decision))continue;let n=t.decision.id;if(typeof n=="string"&&K7.test(n))return{id:n.toLowerCase(),answered:t.answered===!0}}return null}s(uw,"decisionFrom");function dw(e){let t=e.question;return typeof t=="string"&&t.trim().length>0?t:null}s(dw,"questionOf");function pw(e){return e.length>=9&&e.length<=2048&&/^https:\/\/[^/?#@\s\p{Cc}]+([/?#][^\s\p{Cc}]*)?$/u.test(e)}s(pw,"isAllowedLinkUrl");function fw(e,t){return e.slice(0,10).map(n=>{let r=t?Nr(n.label,60):null;return r?{url:n.url,label:r}:{url:n.url}})}s(fw,"wireLinks");var As=30,RL=600-2*As,Qp=10;function $l(e,t){let n=Math.max(0,t-e.at)*RL/36e5;return Math.min(As,e.tokens+n)}s($l,"bucketLevel");function Ll(e,t,n){return{tokens:$l(e,n)-t,at:n}}s(Ll,"bucketTake");function Rs(e){return/^[a-z][a-z0-9_]{0,39}$/.test(e)?e:"other"}s(Rs,"failureCode");js();function hw(e){return new Promise(t=>{setTimeout(t,e).unref?.()})}s(hw,"timerDelay");async function gw(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(gw,"timerDeadline");var CL=1e4,IL=1e3,OL=15e3,mw=3,NL=20,DL=200,W7=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"]),V7=new Set(["session_ended","agent_session_not_found","invalid_key","auth_rejected","dev_mode_disabled","unknown_tool"]);function yw(e,t,n){let r=e.startActivities??[],o=e.finalResponse??"always",i=null,a=null,l=0,c=null,u=!1,d=!1,p=!1,f=null,m=null,h=Promise.resolve(),g=!1,_=[],b=null,k=new Map,v=new Map,S=aw,x=!1,T=null,A=e.summary??null,L=[],R=!1,P=!1,D=null,E={tokens:As,at:n.now()},F=0,q=!1,Ue=0,Ht=0,ae=0,rt=0,ge=null,qo={},$r=s(O=>{let $=Rs(O);qo[$]=(qo[$]??0)+1},"fail"),zo=s(O=>{c||(c=Rs(O))},"stop"),Hw=s(O=>{F=n.now()+Math.max(1,O??60)*1e3,E={tokens:As,at:F},q=!0},"obeyRateLimit"),Uw=s(O=>{h=h.then(O).catch(()=>$r("internal"))},"enqueue"),Gn=s(()=>{p||c||g||(g=!0,Uw(async()=>{g=!1,await Kw(!1)}))},"requestFlush"),Bw=s(async O=>{try{let $=await n.deadline(O(),CL);return $.done?$.value:{ok:!1,error:"timeout",retryAfterSeconds:null,transient:!0}}catch{return{ok:!1,error:"unreachable",retryAfterSeconds:null,transient:!0}}},"attempt"),Os=s(async O=>{let $=await Bw(O);return!$.ok&&$.transient&&($r($.error),await n.delay(IL),$=await Bw(O)),$.ok?(Ue=0,$):($r($.error),$.transient?(Ue+=1,Ue>=NL&&zo("unreachable")):W7.has($.error)&&(zo($.error),V7.has($.error)&&(u=!0)),$)},"call"),Gw=s(async()=>{if(i||c)return;if(l>=mw){zo("start_failed");return}l+=1;let O=await Os(()=>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"&&zo(O.error),l>=mw&&zo("start_failed");return}if(!O.agentSessionId){zo("invalid_response");return}i=O.agentSessionId,a=O.textStored===!0;let $=O.appended??0;if($>0){Ht+=$,E=Ll(E,$,n.now());let te=r[r.length-1];D=te&&te.ephemeral===!0&&te.action?te.action:null}(a||T!==null||L.length>0)&&(R=!0)},"ensureStarted"),wF=s(async()=>{if(!i||c||!R)return;R=!1;let O=a&&!P&&A!==null?Nr(A,255):null,$=fw(L,a===!0);if(T===null&&O===null&&$.length===0)return;let te=A,xe=await Os(()=>t.start({projectKey:e.projectKey,sessionId:e.sessionId,objectId:e.objectId,...T!==null?{model:T}:{},...O!==null?{summary:O}:{},...$.length>0?{links:$}:{}}));if(xe.ok){O!==null&&A===te&&(P=!0);return}xe.transient&&(R=!0)},"sendHeader"),vF=s(O=>{let $=null;for(let te of k.values())te.kind!==null&&O-te.at>=Ml&&(!$||te.at>$.at)&&($={kind:te.kind,at:te.at});for(let te of v.values())O-te.at>=Ml&&(!$||te.at>$.at)&&($=te);return $?$.kind:null},"currentEphemeral"),SF=s(async O=>{if(!i||c)return;let $=n.now();if(!O&&$<F)return;let te=_.splice(0,_.length),xe=q?Dr(te):te,Ut=O?null:vF($),hf=Ut!==null&&(xe.length>0||Ut!==D),Ww=a===!0,ot=Zp(xe,{textAllowed:Ww,ephemeral:hf?Ut:null});if(ot.length===0)return;let Vw=$l(E,$),qw=O?Vw:Vw-Qp;if(ot.length>qw||ot.length>50){let Jo=Zp(Dr(xe),{textAllowed:Ww,ephemeral:hf?Ut:null});if(!O&&Jo.length>qw){_.unshift(...Dr(xe));return}ot=Jo}ot.length>50&&(rt+=ot.length-50,ot=ot.slice(ot.length-50));let EF=i,Kl=await Os(()=>t.append({projectKey:e.projectKey,agentSessionId:EF,activities:ot}));if(Kl.ok){Ht+=ot.length,E=Ll(E,ot.length,n.now()),q=!1;let Jo=ot[ot.length-1];D=Jo.ephemeral===!0&&Jo.action?Jo.action:null;return}if(!O&&Kl.error==="rate_limited"){Hw(Kl.retryAfterSeconds),_.unshift(...Dr(xe));return}if(!O&&Kl.transient&&!c){_.unshift(...Dr(xe));return}rt+=xe.length},"sendActivities"),xF=s(async O=>{if(!i||c||!x)return;let $=n.now();if(!O&&$<F||!O&&$l(E,$)-Qp<1)return;x=!1;let te=i,xe=await Os(()=>t.plan({projectKey:e.projectKey,agentSessionId:te,plan:cw(S,a===!0)}));if(xe.ok){ae+=1,E=Ll(E,1,n.now());return}xe.error==="rate_limited"&&Hw(xe.retryAfterSeconds),!O&&(xe.transient||xe.error==="rate_limited")&&(x=!0)},"sendPlan"),Kw=s(async O=>{c||!i&&(await Gw(),!i)||(await wF(),await SF(O),await xF(O))},"flushOnce"),mf=s(()=>{if(_.length<=DL)return;let O=Dr(_);_.length=0,_.push(...O)},"capPending"),Gl=s(()=>{b!==null&&(_.push({type:"thought",text:b}),b=null)},"flushThought");return{begin(){p||d||(d=!0,Uw(Gw),m=n.every(Pl,Gn))},onEvent(O){if(!(p||c))try{if(O.kind==="text"){if(O.subagent)return;Gl(),b=O.text}else if(O.kind==="tool_start")O.subagent||Gl(),k.set(O.id,{tool:O.tool,input:O.input,kind:sw(O.tool,O.input),at:n.now(),subagent:O.subagent});else{let $=k.get(O.id);if(!$)return;if(k.delete(O.id),$.kind!==null)_.push({type:"action",kind:$.kind,count:1});else if($.tool===Ts){let te=O.failed?null:uw(O.output);_.push(te&&!te.answered?{type:"elicitation",decisionId:te.id,text:dw($.input)}:{type:"action",kind:"other",count:1})}else if(!$.subagent&&!O.failed){let te=lw(S,$.tool,$.input,O.output);te&&(S=te,x=!0)}}mf(),_.length>=iw&&Gn()}catch{$r("internal")}},setModel(O){if(p||c)return;let $=O.trim().slice(0,100);$.length===0||$===T||(T=$,R=!0,Gn())},setSummary(O){if(p||c)return;let $=O.trim();$.length===0||$===A||(A=$,P=!1,R=!0,Gn())},addLink(O){p||c||!pw(O.url)||L.some($=>$.url===O.url)||(L.push({url:O.url,label:O.label}),R=!0,Gn())},step(O,$,te){if(!(p||c)){if(te==="start")v.set(O,{kind:$,at:n.now()-Ml});else{let xe=v.get(O);if(!xe)return;v.delete(O),_.push({type:"action",kind:xe.kind,count:1})}Gn()}},elicit(O){if(!(p||c))try{Gl(),_.push({type:"elicitation",decisionId:null,text:O}),mf(),Gn()}catch{$r("internal")}},endTurn(){p||c||b!==null&&(_.push({type:"response",text:b,textOnly:!0}),b=null,mf(),Gn())},close(O){return f||(p=!0,m?.clear(),d?(f=(async()=>{try{for(let Ut of k.values())Ut.kind!==null&&_.push({type:"action",kind:Ut.kind,count:1});k.clear();for(let Ut of v.values())_.push({type:"action",kind:Ut.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}):(Gl(),_.push({type:"error",text:O.reasonText??null})),b=null;let te=(async()=>{if(await h,await Kw(!0),!i||u)return;let Ut=i;(await Os(()=>t.end({projectKey:e.projectKey,agentSessionId:Ut,endState:$}))).ok&&(ge=$)})();(await n.deadline(te,OL)).done||$r("close_timeout")}catch{$r("internal")}rt+=_.length,_.length=0})(),f):(f=Promise.resolve(),f))},record(){return{agentSessionId:i,textStored:a,sent:Ht,plans:ae,dropped:rt,endState:ge,failures:{...qo},stoppedBy:c}}}}s(yw,"makeActivityReporter");var _w="work_object_report_activity",q7=new Set(["rpc_failed","session_not_announced"]);function bw(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"?Rs(t.error):"invalid_response";return{ok:!1,error:n,retryAfterSeconds:typeof t.retry_after_seconds=="number"?t.retry_after_seconds:null,transient:q7.has(n)}}s(bw,"activityAnswerFrom");var jl={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 kw(e){return{start:s(t=>e(jl.start(t)),"start"),append:s(t=>e(jl.append(t)),"append"),plan:s(t=>e(jl.plan(t)),"plan"),end:s(t=>e(jl.end(t)),"end")}}s(kw,"activityTransportFrom");_r();var z7="AskUserQuestion",J7=/^mcp__.+__work_object_ask_decision$/,Y7="<synthetic>",X7=new Set(["end_turn","stop_sequence","max_tokens","refusal"]),Z7=new Set(["stop_hook_summary","turn_duration"]);function Wo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(Wo,"isRecord");function Q7(e){let t=e.questions;if(Array.isArray(t)){let r=t.filter(Wo).map(o=>o.question).filter(o=>typeof o=="string"&&o.trim().length>0);if(r.length>0)return r.join(`
1283
+ `)}let n=e.question;return typeof n=="string"&&n.trim().length>0?n:null}s(Q7,"questionText");var Fl=class{static{s(this,"TranscriptEventMapper")}turnEnding=!1;questions=new Set;lastModel=null;lastTitle=null;map(t){try{if(!Wo(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"&&Z7.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(!Wo(n))return[];let r=[],o=n.model;typeof o=="string"&&o.length>0&&o!==Y7&&o!==this.lastModel&&(this.lastModel=o,r.push({kind:"model",model:o}));let i=n.content;if(Array.isArray(i)){for(let l of i)if(Wo(l)){if(l.type==="text"){let c=l.text;typeof c=="string"&&c.trim().length>0&&r.push({kind:"text",text:c,subagent:!1})}else if(l.type==="tool_use"){let c=l.id,u=l.name;if(typeof c!="string"||typeof u!="string")continue;let d=Wo(l.input)?l.input:{};if(this.turnEnding=!1,u===z7){this.questions.add(c),r.push({kind:"question",text:Q7(d)});continue}r.push({kind:"tool_start",id:c,tool:J7.test(u)?Ts:u,input:d,subagent:!1})}}}let a=n.stop_reason;return typeof a=="string"&&(this.turnEnding=X7.has(a)),r}user(t){if(t.isMeta===!0||t.isCompactSummary===!0||t.isVisibleInTranscriptOnly===!0)return[];let n=t.message,r=Wo(n)?n.content:void 0,o=Array.isArray(r)?r.filter(l=>Wo(l)&&l.type==="tool_result"&&typeof l.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 l of o){let c=l.tool_use_id;this.questions.delete(c)||a.push({kind:"tool_end",id:c,failed:l.is_error===!0,output:i!==void 0?i:l.content??null,subagent:!1})}return a}};import{open as eQ,stat as tQ}from"node:fs/promises";var nQ={async stat(e){try{let t=await tQ(e);return{size:t.size,id:`${t.dev}:${t.ino}`}}catch{return null}},async read(e,t,n){let r=await eQ(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()}}},rQ=4*1024*1024,oQ=16*1024*1024,PL=10,ef=class{constructor(t=nQ,n=rQ,r=oQ){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]!==PL}catch{this.skipToNewline=!0}}clearPartial(){this.partial=[],this.partialBytes=0}consume(t){let n=[],r=0;for(;;){let i=t.indexOf(PL,r);if(i===-1)break;let a=t.subarray(r,i);if(r=i+1,this.skipToNewline){this.skipToNewline=!1,this.clearPartial();continue}let l=this.partialBytes>0?Buffer.concat([...this.partial,a]):a;if(this.clearPartial(),l.length>this.maxLine)continue;let c=iQ(l);c!==void 0&&n.push(c)}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 iQ(e){let t=e.toString("utf8").trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}s(iQ,"parseLine");var sQ=Pl,aQ=2e3,lQ=5*6e4,cQ=10,uQ=new Set(["unknown_tool","invalid_params","dev_mode_disabled","invalid_key","auth_rejected"]),dQ={now:s(()=>Date.now(),"now"),every:s((e,t)=>{let n=setInterval(t,e);return n.unref?.(),{clear:s(()=>clearInterval(n),"clear")}},"every"),delay:hw,deadline:gw},tf=class{constructor(t){this.deps=t;this.clock=t.clock??dQ,this.tail=t.tail??new ef,this.log=t.log??(n=>process.stderr.write(n+`
1284
+ `))}static{s(this,"ActivityProducer")}clock;tail;log;mapper=new Fl;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(sQ,()=>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=aQ){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&&ML(this.path)===ML(n)||(this.retire(),this.mapper=new Fl,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<cQ&&!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=yw({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 ${el(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&&(uQ.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()+lQ),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{}}}};_r();Me();var pQ=1e4,Pr=s((e,t)=>({ok:!1,error:e,retryAfterSeconds:null,transient:t}),"answer");function fQ(e){switch(e.kind){case"no_session":return Pr("no_session",!0);case"transport_error":return Pr(e.timedOut?"timeout":"unreachable",!0);case"http_error":return e.status===401?Pr("auth_rejected",!1):e.status>=400&&e.status<500&&e.status!==408&&e.status!==429?Pr(`http_${e.status}`,!1):Pr("unreachable",!0);case"rpc_error":{let t=ki(`MCP error ${e.code}: ${e.message}`);return Pr(t?.kind??"tool_error",!1)}case"result":{if(e.isError){let n=ki(e.text);if(n!==null)return Pr(n.kind,!1)}let t=null;try{t=JSON.parse(e.text)}catch{t=null}return bw(t)}}}s(fQ,"activityAnswerFromOutcome");function $L(e){return kw(async t=>{try{return fQ(await e(_w,t,{timeoutMs:pQ}))}catch{return Pr("unreachable",!0)}})}s($L,"bridgeActivityTransport");H_();B_();var mQ=6e4,LL=2*60*6e4,hQ=5*6e4,gQ=24*60*6e4,yQ=3e4,_Q=15e3,bQ=3,nf=class{constructor(t){this.deps=t;this.startIso=new Date(this.now()).toISOString()}static{s(this,"ThreadWatcher")}busy=!1;startIso;lastError=null;timer=null;nudgeTimer=null;wasIdle=!1;lastIdleReadAt=null;now(){return(this.deps.now??Date.now)()}start(t=mQ){this.timer!==null||this.deps.projectKey===null||(this.timer=setInterval(()=>void this.tick(),t),this.timer.unref(),this.nudgeTimer=setInterval(()=>this.nudge(),yQ),this.nudgeTimer.unref())}stop(){this.timer!==null&&clearInterval(this.timer),this.nudgeTimer!==null&&clearInterval(this.nudgeTimer),this.timer=null,this.nudgeTimer=null}nudge(){if(!this.wasIdle)return;let t=this.deps.activityAtMs();t===null||this.now()-t>LL||this.tick()}note(t){t!==this.lastError&&(this.lastError=t,this.deps.log?.(`maind-bridge: reading the work object's thread failed (${t}) \u2014 next poll retries.`))}async tick(){if(!this.busy){this.busy=!0;try{let t=this.deps.projectKey,n=this.deps.sessionId();if(t===null||!n)return;let r=this.now(),o=this.deps.activityAtMs(),i=o!==null&&r-o>LL;this.wasIdle=i;let l=(this.deps.readState??Sd)(t,n,this.deps.baseDir)??{v:1,written_at:this.startIso,session_id:n,items:[],since:{},stamped:[]},c={...l.awaiting??{}},u=!1;for(let[m,h]of Object.entries(c)){let g=Date.parse(h.since);(Number.isNaN(g)||r-g>gQ)&&(delete c[m],u=!0)}let d=Object.entries(c).map(([m,h])=>({id:m,key:h.key}));if(i)d.length>0&&(this.lastIdleReadAt!==null&&r-this.lastIdleReadAt<hQ?d.length=0:this.lastIdleReadAt=r);else for(let m of this.deps.boundObjects()??[])d.some(h=>h.id===m.id)||d.push({id:m.id,key:m.key});d.splice(bQ);let p=(this.deps.readTold??((m,h)=>xd(m,h,this.deps.baseDir)))(t,n);for(let m of d){let h=l.since[m.id]??c[m.id]?.since??this.startIso,g=p.delivered.filter(S=>S.objectId===m.id&&!l.stamped.includes(S.id)).map(S=>S.id).slice(0,20),_=await this.deps.call("work_object_read_comments",{project_key:t,session_id:n,object_id:m.id,since:h,audience:"holder",...g.length>0?{delivered_ids:g}:{}},{timeoutMs:_Q});if(_.kind!=="result"){this.note(_.kind);continue}if(_.isError){this.note("tool_error");continue}let b=oO(_.text,m.id,m.key);if(!b.ok){this.note(b.error);continue}this.lastError=null,g.length>0&&l.stamped.push(...g);let k=new Set(l.items.map(S=>S.id)),v=b.items.filter(S=>!k.has(S.id));l.items.push(...v),b.newest!==null&&(l.since[m.id]=b.newest),u=u||v.length>0||g.length>0||b.newest!==null,b.openQuestions!==null&&b.openQuestions>0&&c[m.id]===void 0?(c[m.id]={key:m.key,since:new Date(r).toISOString()},u=!0):b.openQuestions===0&&c[m.id]!==void 0&&(delete c[m.id],u=!0)}if(!u)return;l.awaiting=c;let f=new Set(p.told);l.items=l.items.filter(m=>!f.has(m.id)),l.written_at=new Date(this.now()).toISOString(),(this.deps.writeState??uO)(t,l,this.deps.baseDir,this.now())}catch(t){this.note(t instanceof Error?t.message:String(t))}finally{this.busy=!1}}}};var Xee=1;function Zee(e){return tw.includes(e)}s(Zee,"isHookSubcommand");var Qee=6e4;async function ete(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==ee()&&yo(e),e;let t=ee();if(t!==null)return t;let n=await Ai(K);return n===null&&(_o("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:K}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1285
+ `),process.exit(1)),_o("paired",null,{version:K}),n.apiKey}s(ete,"ensureApiKey");async function tte(e){let t=await Ai(K);return t===null&&(_o("auth_failed",`${e}; re-authorization did not complete`,{version:K}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1286
+ `),process.exit(1)),_o("paired",null,{version:K}),t.apiKey}s(tte,"reauth");async function nte(){let e=nw(process.argv.slice(2)),t=kL(process.argv.slice(2));if(t!==null&&(process.stderr.write(`${t}
1287
+ `),process.exit(2)),e==="install"){let E=process.argv.indexOf("install"),F=process.argv.slice(E+1),q=await Y$(F);process.exit(q)}if(e==="refresh-rules"){let{runRefreshRules:E}=await Promise.resolve().then(()=>(Bp(),zk));process.exit(await E(process.argv.slice(process.argv.indexOf("refresh-rules")+1)))}if(e==="doctor"){let{runDoctor:E}=await Promise.resolve().then(()=>(Ob(),AD));process.exit(await E(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:E}=await Promise.resolve().then(()=>(Dk(),Nk));process.exit(await E())}if(e==="session-end-run"){let{runSessionEndWorker:E}=await Promise.resolve().then(()=>(Ok(),UM));process.exit(await E())}if(e==="on-hook"){let{hooksFromArgv:E,runHooks:F}=await Promise.resolve().then(()=>(Oe(),Uo)),q=process.argv.slice(process.argv.indexOf("on-hook")+1);process.exit(await F(E(q),q))}if(e==="on-session-briefing"){let{runOnSessionBriefing:E}=await Promise.resolve().then(()=>(Gb(),Bb));process.exit(await E())}if(e==="on-session-reminder"){let{runOnSessionReminder:E}=await Promise.resolve().then(()=>(E_(),x_));process.exit(await E())}if(e==="on-cursor-session-start"){let{runOnCursorSessionStart:E}=await Promise.resolve().then(()=>(VL(),WL));process.exit(await E())}if(e==="guard"){let E=process.argv.indexOf("guard"),{runGuard:F}=await Promise.resolve().then(()=>(tj(),ej));process.exit(await F(process.argv.slice(E+1)))}if(e==="guard-inject"){let{runGuardInject:E}=await Promise.resolve().then(()=>(Po(),QO));process.exit(await E())}if(e==="guard-gate"){let{runGuardGate:E}=await Promise.resolve().then(()=>(sj(),ij));process.exit(await E())}if(e==="guard-stop"){let{runGuardStop:E}=await Promise.resolve().then(()=>(cj(),lj));process.exit(await E())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="guard-capture"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="guard-consult"){let{runGuardConsult:E}=await Promise.resolve().then(()=>(cf(),lf));process.exit(await E())}if(e==="guard-prompt-mark"){let{runGuardPromptMark:E}=await Promise.resolve().then(()=>(cf(),lf));process.exit(await E())}if(e==="guard-skip-note"){let{runGuardSkipNote:E}=await Promise.resolve().then(()=>(cf(),lf));process.exit(await E())}if(e==="gateway"){let E=process.argv.indexOf("gateway"),{runGateway:F}=await Promise.resolve().then(()=>(uF(),cF));process.exit(await F(process.argv.slice(E+1)))}if(e==="activity"){let{runActivity:E}=await Promise.resolve().then(()=>(fF(),pF));process.exit(await E(process.argv.slice(process.argv.indexOf("activity")+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:E}=await Promise.resolve().then(()=>(Fw(),jw));process.exit(await E())}if(e==="guard-cross-check"){let{runGuardCrossCheck:E}=await Promise.resolve().then(()=>(Fw(),jw));process.exit(await E())}if(e==="on-index-refresh"){let{runOnIndexRefresh:E}=await Promise.resolve().then(()=>(Np(),Op));process.exit(await E())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:E}=await Promise.resolve().then(()=>(Np(),Op));process.exit(await E())}if(e==="on-doc-duty"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="on-prompt-context"){let{runOnPromptContext:E}=await Promise.resolve().then(()=>(Tl(),El));process.exit(await E())}if(e==="on-read-context"){let{runOnReadContext:E}=await Promise.resolve().then(()=>(Tl(),El));process.exit(await E())}if(e==="on-shell-write"||e==="on-shell-changes"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e==="on-plan-accepted"){let{runHooks:E}=await Promise.resolve().then(()=>(Oe(),Uo));process.exit(await E([e]))}if(e!==void 0&&Zee(e)){let E=await Promise.resolve().then(()=>(Lt(),gs)),F={"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 F())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(K+`
1288
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(rte(),process.exit(0)),process.argv.includes("--reauth")&&(ya(),await Ai(K,process.stdout)===null&&process.exit(1),_o("paired",null,{version:K}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1289
+ `),process.exit(0));let n=ke(),r=await ete(),o=Z(),a=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Kp:null,l=null,c=new Map,u=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new qp(void 0,a,void 0,{callCloudTool:s((E,F,q)=>l===null?Promise.resolve({kind:"no_session"}):l.callCloudTool(E,F,q),"callCloudTool"),projectKey:o,engineFor:s(E=>{let F=c.get(E);return F===void 0&&(F=GN(E),c.set(E,F)),F},"engineFor"),projectKeyFor:Ke}),d=`bridge-${Yee()}`,p=s(async()=>{if(!a)return;let E=a.takePending();E.tokens<=0||await yL({apiKey:r,deviceId:n,sessionId:d,tokensSaved:E.tokens,bridgeVersion:K})},"flushSavings"),f=a?setInterval(()=>{p()},Qee):null;f?.unref();let m=new Ad({projectKey:o}),h=new Jp({resolvePath:s(()=>ew(m.sideChannel()),"resolvePath"),fallbackModel:s(()=>m.sideChannel()?.model??null,"fallbackModel")}),g=new su,_=null,b=s(()=>(_===null&&(_=o!==null?Xa(gt(),o):[]),_),"nestedRepos"),k=s(E=>b().find(F=>F.projectKey===E)?.dir??null,"nestedDirOf"),v=new zp({agentCwd:s(()=>m.sideChannel()?.cwd??null,"agentCwd")}),S=null,x=new Tp({projectKey:o,identity:m,sessionMeta:s(()=>h.read(),"sessionMeta"),postToolCall:s((E,F)=>l===null?Promise.reject(new Error("presence: no active forwarder")):l.postPresenceToolCall(E,F),"postToolCall"),deriveWorkingPaths:s(()=>bL(),"deriveWorkingPaths"),snapshot:o!==null?ote(qI({projectKey:o}),g,k):void 0,nestedProjectKeys:s(()=>b().map(E=>E.projectKey),"nestedProjectKeys"),workRepo:s(()=>v.current(),"workRepo"),editRoots:s(()=>gO(m.sideChannel()),"editRoots"),onAnnounced:s(()=>S?.refresh(),"onAnnounced")});S=new tf({enabled:Yp().enabled&&x.isEnabled,projectKey:o,sessionId:s(()=>x.sessionId,"sessionId"),transcriptPath:s(()=>ew(m.sideChannel()),"transcriptPath"),target:s(()=>yr({branchObjectId:x.branchObjectId(),boundObjects:x.boundObjects()}),"target"),transport:$L((E,F,q)=>l===null?Promise.resolve({kind:"no_session"}):l.callCloudTool(E,F,q))});let T=x.isEnabled?setInterval(()=>{x.pollActivity()},uM):null;T?.unref();let A=x.isEnabled?new nf({projectKey:o,sessionId:s(()=>x.sessionId,"sessionId"),boundObjects:s(()=>x.boundObjects(),"boundObjects"),activityAtMs:s(()=>m.activityAtMs(),"activityAtMs"),call:s((E,F,q)=>l===null?Promise.resolve({kind:"no_session"}):l.callCloudTool(E,F,q),"call"),log:s(E=>process.stderr.write(`${E}
1290
+ `),"log")}):null;if(A?.start(),x.isEnabled){let E=s(F=>{(S?.shutdown()??Promise.resolve()).then(()=>x.end()).finally(()=>process.exit(F))},"endAndExit");process.on("SIGTERM",()=>E(143)),process.on("SIGINT",()=>E(130))}let L=!1,R=s(E=>{if(L)return;L=!0;let F=s(()=>l?.listClientRoots()??Promise.resolve(null),"listRoots");setTimeout(()=>{Promise.resolve().then(()=>(jp(),K$)).then(({refreshAgentsMdForSession:Ue})=>Ue(E,{apiKey:r,projectKey:o,listRoots:F})).catch(()=>{}).then(()=>Promise.resolve().then(()=>(Bp(),zk))).then(({refreshRulesForSession:Ue})=>Ue(E,{apiKey:s(()=>r,"apiKey"),listRoots:F})).catch(()=>{})},0).unref()},"scheduleChannelRefresh"),P=0,D=jg();try{for(;;){let E=l?.carryOver()??null,F=new hu({apiKey:r,deviceId:n,bridgeVersion:K,projectKey:o,nestedProjectKeys:s(()=>b().map(q=>q.projectKey),"nestedProjectKeys"),localRouter:u,presence:x,onConnectionOutcome:s((q,Ue)=>_o(q,Ue,{version:K}),"onConnectionOutcome"),onSessionReady:s(({clientFamily:q})=>R(q),"onSessionReady"),assignedInbox:g,carry:E});l=F;try{await F.run(D);return}catch(q){if(q instanceof ga&&P<Xee){P+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${q.message}; re-authorizing\u2026
1291
+ `),r=await tte(q.reason);continue}throw q}}}finally{f&&clearInterval(f),T&&clearInterval(T),A?.stop(),await S?.shutdown(),await x.end(),await p()}}s(nte,"main");function rte(){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-shell-write before a Bash call: the literal files its command line writes get the file hooks' checks (MAIND-892; may refuse a taken number)"," on-shell-changes after a Bash call: files it changed that its command line did not name, via git status (MAIND-892, never blocks)"," on-plan-accepted after ExitPlanMode: a note to attach the accepted plan to its work object (MAIND-1189, 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|gemini-cli|...)"," 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(`
1292
+ `))}s(rte,"printHelp");nte().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1293
+ `),process.exit(1)});function ote(e,t,n){return{...e,write(r,o){let i=r;try{i=dR(r,n)}catch{i=r}try{t.update(i)}catch{}e.write(i,o)}}}s(ote,"withAssignedCapture");